@did-btcr2/method 0.55.0 → 0.56.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.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var BTCR2=(()=>{var hI=Object.create;var Rf=Object.defineProperty;var pI=Object.getOwnPropertyDescriptor;var yI=Object.getOwnPropertyNames;var gI=Object.getPrototypeOf,mI=Object.prototype.hasOwnProperty;var wI=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),bu=(t,e)=>{for(var r in e)Rf(t,r,{get:e[r],enumerable:!0})},px=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yI(e))!mI.call(t,i)&&i!==r&&Rf(t,i,{get:()=>e[i],enumerable:!(n=pI(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?hI(gI(t)):{},px(e||!t||!t.__esModule?Rf(r,"default",{value:t,enumerable:!0}):r,t)),bI=t=>px(Rf({},"__esModule",{value:!0}),t);var mx=oe(Uf=>{"use strict";l();Uf.byteLength=EI;Uf.toByteArray=SI;Uf.fromByteArray=_I;var Mn=[],Yr=[],xI=typeof Uint8Array<"u"?Uint8Array:Array,sy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hs=0,yx=sy.length;hs<yx;++hs)Mn[hs]=sy[hs],Yr[sy.charCodeAt(hs)]=hs;var hs,yx;Yr[45]=62;Yr[95]=63;function gx(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 EI(t){var e=gx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function vI(t,e,r){return(e+r)*3/4-r}function SI(t){var e,r=gx(t),n=r[0],i=r[1],o=new xI(vI(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Yr[t.charCodeAt(a)]<<18|Yr[t.charCodeAt(a+1)]<<12|Yr[t.charCodeAt(a+2)]<<6|Yr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Yr[t.charCodeAt(a)]<<2|Yr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Yr[t.charCodeAt(a)]<<10|Yr[t.charCodeAt(a+1)]<<4|Yr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function AI(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function TI(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(AI(n));return i.join("")}function _I(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(TI(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 wx=oe(cy=>{l();cy.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)};cy.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 Ar=oe(Oc=>{"use strict";l();var ay=mx(),Uc=wx(),bx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Oc.Buffer=F;Oc.SlowBuffer=DI;Oc.INSPECT_MAX_BYTES=50;var Of=2147483647;Oc.kMaxLength=Of;F.TYPED_ARRAY_SUPPORT=BI();!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 BI(){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>Of)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 ly(t)}return vx(t,e,r)}F.poolSize=8192;function vx(t,e,r){if(typeof t=="string")return RI(t,e);if(ArrayBuffer.isView(t))return UI(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 dy(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=OI(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 vx(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function Sx(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 II(t,e,r){return Sx(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 II(t,e,r)};function ly(t){return Sx(t),wi(t<0?0:hy(t)|0)}F.allocUnsafe=function(t){return ly(t)};F.allocUnsafeSlow=function(t){return ly(t)};function RI(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=Ax(t,e)|0,n=wi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function uy(t){for(var e=t.length<0?0:hy(t.length)|0,r=wi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function UI(t){if(Kn(t,Uint8Array)){var e=new Uint8Array(t);return dy(e.buffer,e.byteOffset,e.byteLength)}return uy(t)}function dy(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 OI(t){if(F.isBuffer(t)){var e=hy(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"||py(t.length)?wi(0):uy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return uy(t.data)}function hy(t){if(t>=Of)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Of.toString(16)+" bytes");return t|0}function DI(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 Ax(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 fy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Ux(t).length;default:if(i)return n?-1:fy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Ax;function kI(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 qI(this,e,r);case"utf8":case"utf-8":return _x(this,e,r);case"ascii":return HI(this,e,r);case"latin1":case"binary":return VI(this,e,r);case"base64":return KI(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return FI(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?_x(this,0,e):kI.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=Oc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};bx&&(F.prototype[bx]=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 Tx(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,py(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:xx(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):xx(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function xx(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 Tx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return Tx(this,e,r,n,!1)};function NI(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(py(c))return s;t[r+s]=c}return s}function CI(t,e,r,n){return Df(fy(e,t.length-r),t,r,n)}function LI(t,e,r,n){return Df(GI(e),t,r,n)}function PI(t,e,r,n){return Df(Ux(e),t,r,n)}function MI(t,e,r,n){return Df(zI(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 NI(this,e,r,n);case"utf8":case"utf-8":return CI(this,e,r,n);case"ascii":case"latin1":case"binary":return LI(this,e,r,n);case"base64":return PI(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return MI(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 KI(t,e,r){return e===0&&r===t.length?ay.fromByteArray(t):ay.fromByteArray(t.slice(e,r))}function _x(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 $I(n)}var Ex=4096;function $I(t){var e=t.length;if(e<=Ex)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Ex));return r}function HI(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 VI(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 qI(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+=YI[t[o]];return i}function FI(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),Uc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Uc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Uc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Uc.read(this,e,!1,52,8)};function dr(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;dr(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;dr(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||dr(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||dr(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||dr(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||dr(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||dr(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);dr(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);dr(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||dr(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||dr(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||dr(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||dr(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||dr(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 Bx(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 Ix(t,e,r,n,i){return e=+e,r=r>>>0,i||Bx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Uc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Ix(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Ix(this,e,r,!1,n)};function Rx(t,e,r,n,i){return e=+e,r=r>>>0,i||Bx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Uc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return Rx(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return Rx(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 jI=/[^+/0-9A-Za-z-_]/g;function WI(t){if(t=t.split("=")[0],t=t.trim().replace(jI,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function fy(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 GI(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function zI(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 Ux(t){return ay.toByteArray(WI(t))}function Df(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 py(t){return t!==t}var YI=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((VL,Nx)=>{l();var at=Nx.exports={},$n,Hn;function yy(){throw new Error("setTimeout has not been defined")}function gy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?$n=setTimeout:$n=yy}catch{$n=yy}try{typeof clearTimeout=="function"?Hn=clearTimeout:Hn=gy}catch{Hn=gy}})();function Ox(t){if($n===setTimeout)return setTimeout(t,0);if(($n===yy||!$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 JI(t){if(Hn===clearTimeout)return clearTimeout(t);if((Hn===gy||!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=[],Dc=!1,ys,kf=-1;function ZI(){!Dc||!ys||(Dc=!1,ys.length?bi=ys.concat(bi):kf=-1,bi.length&&Dx())}function Dx(){if(!Dc){var t=Ox(ZI);Dc=!0;for(var e=bi.length;e;){for(ys=bi,bi=[];++kf<e;)ys&&ys[kf].run();kf=-1,e=bi.length}ys=null,Dc=!1,JI(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 kx(t,e)),bi.length===1&&!Dc&&Ox(Dx)};function kx(t,e){this.fun=t,this.array=e}kx.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,FL,l=wI(()=>{b=Pn(Ar()),w=Pn(Ei()),FL=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 t1=oe((SH,e1)=>{l();var i6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Hl=()=>i6.now(),o6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Q0=t=>t===1/0||o6(t),eg=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&&!Q0(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!Q0(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-Hl());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(Hl()+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(!Q0(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-Hl())):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(Hl());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()}};e1.exports=eg});var w1=oe(m1=>{"use strict";l();m1.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((GV,b1)=>{"use strict";l();b1.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 yg=oe((YV,x1)=>{"use strict";l();var pg=null;x1.exports=function(){return pg===null&&(pg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),pg}});var wg=oe(E1=>{"use strict";l();var gg=En(),M6=new Set(["buffer","view","utf8"]),mg=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"||!M6.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 gg(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new gg(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new gg(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};E1.Encoding=mg});var vg=oe(ql=>{"use strict";l();var{Buffer:xg}=Ar()||{},{Encoding:Eg}=wg(),K6=yg(),cd=class extends Eg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new ad({encode:this.encode,decode:e=>this.decode(xg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},ad=class extends Eg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new cd({encode:e=>{let r=this.encode(e);return xg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},bg=class extends Eg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new cd({encode:e=>xg.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 ad({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};ql.BufferFormat=cd;ql.ViewFormat=ad;ql.UTF8Format=bg});var T1=oe(Ks=>{"use strict";l();var{Buffer:Jt}=Ar()||{Buffer:{isBuffer:()=>!1}},{textEncoder:S1,textDecoder:v1}=yg()(),{BufferFormat:ud,ViewFormat:Sg,UTF8Format:A1}=vg(),Fl=t=>t;Ks.utf8=new A1({encode:function(t){return Jt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?v1.decode(t):String(t)},decode:Fl,name:"utf8",createViewTranscoder(){return new Sg({encode:function(t){return ArrayBuffer.isView(t)?t:S1.encode(t)},decode:function(t){return v1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new ud({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Ks.json=new A1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ks.buffer=new ud({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Fl,name:"buffer",createViewTranscoder(){return new Sg({encode:function(t){return ArrayBuffer.isView(t)?t:Jt.from(String(t),"utf8")},decode:function(t){return Jt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Ks.view=new Sg({encode:function(t){return ArrayBuffer.isView(t)?t:S1.encode(t)},decode:Fl,name:"view",createBufferTranscoder(){return new ud({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Fl,name:`${this.name}+buffer`})}});Ks.hex=new ud({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ks.base64=new ud({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var I1=oe(B1=>{"use strict";l();var _1=En(),Wl=T1(),{Encoding:$6}=wg(),{BufferFormat:H6,ViewFormat:V6,UTF8Format:q6}=vg(),dd=Symbol("formats"),jl=Symbol("encodings"),F6=new Set(["buffer","view","utf8"]),Ag=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>F6.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[jl]=new Map,this[dd]=new Set(e);for(let r in Wl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[jl].values()))}encoding(e){let r=this[jl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=z6[e],!r)throw new _1(`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=j6(e)}let{name:n,format:i}=r;if(!this[dd].has(i))if(this[dd].has("view"))r=r.createViewTranscoder();else if(this[dd].has("buffer"))r=r.createBufferTranscoder();else if(this[dd].has("utf8"))r=r.createUTF8Transcoder();else throw new _1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[jl].set(o,r)}return r}};B1.Transcoder=Ag;function j6(t){if(t instanceof $6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${Y6++}`;switch(W6(t)){case"view":return new V6({...t,name:r});case"utf8":return new q6({...t,name:r});case"buffer":return new H6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function W6(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 G6={binary:Wl.buffer,"utf-8":Wl.utf8},z6={...Wl,...G6},Y6=0});var la=oe((oq,Tg)=>{"use strict";l();var fa=typeof Reflect=="object"?Reflect:null,R1=fa&&typeof fa.apply=="function"?fa.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Gl;fa&&typeof fa.ownKeys=="function"?Gl=fa.ownKeys:Object.getOwnPropertySymbols?Gl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Gl=function(e){return Object.getOwnPropertyNames(e)};function J6(t){console&&console.warn&&console.warn(t)}var O1=Number.isNaN||function(e){return e!==e};function Le(){Le.init.call(this)}Tg.exports=Le;Tg.exports.once=eU;Le.EventEmitter=Le;Le.prototype._events=void 0;Le.prototype._eventsCount=0;Le.prototype._maxListeners=void 0;var U1=10;function zl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Le,"defaultMaxListeners",{enumerable:!0,get:function(){return U1},set:function(t){if(typeof t!="number"||t<0||O1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");U1=t}});Le.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};Le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||O1(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 D1(t){return t._maxListeners===void 0?Le.defaultMaxListeners:t._maxListeners}Le.prototype.getMaxListeners=function(){return D1(this)};Le.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")R1(a,this,r);else for(var u=a.length,d=P1(a,u),n=0;n<u;++n)R1(d[n],this,r);return!0};function k1(t,e,r,n){var i,o,s;if(zl(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=D1(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,J6(c)}return t}Le.prototype.addListener=function(e,r){return k1(this,e,r,!1)};Le.prototype.on=Le.prototype.addListener;Le.prototype.prependListener=function(e,r){return k1(this,e,r,!0)};function Z6(){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 N1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Z6.bind(n);return i.listener=r,n.wrapFn=i,i}Le.prototype.once=function(e,r){return zl(r),this.on(e,N1(this,e,r)),this};Le.prototype.prependOnceListener=function(e,r){return zl(r),this.prependListener(e,N1(this,e,r)),this};Le.prototype.removeListener=function(e,r){var n,i,o,s,c;if(zl(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():X6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Le.prototype.off=Le.prototype.removeListener;Le.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 C1(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?Q6(i):P1(i,i.length)}Le.prototype.listeners=function(e){return C1(this,e,!0)};Le.prototype.rawListeners=function(e){return C1(this,e,!1)};Le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):L1.call(t,e)};Le.prototype.listenerCount=L1;function L1(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}Le.prototype.eventNames=function(){return this._eventsCount>0?Gl(this._events):[]};function P1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function X6(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Q6(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function eU(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))}M1(t,e,o,{once:!0}),e!=="error"&&tU(t,i,{once:!0})})}function tU(t,e,r){typeof t.on=="function"&&M1(t,"error",e,r)}function M1(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 $1=oe((cq,K1)=>{l();K1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var fd=oe(_g=>{"use strict";l();var H1=$1();_g.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};_g.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){H1(()=>e(null,r))}).catch(function(r){H1(()=>e(r))})}});var Yl=oe(Bg=>{"use strict";l();Bg.getCallback=function(t,e){return typeof t=="function"?t:e};Bg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Mo=oe(Ql=>{"use strict";l();var{fromCallback:Ig}=fd(),Dr=En(),{getOptions:Rg,getCallback:V1}=Yl(),$s=Symbol("promise"),ha=Symbol("callback"),Xn=Symbol("working"),Hs=Symbol("handleOne"),Ki=Symbol("handleMany"),Ug=Symbol("autoClose"),Lo=Symbol("finishWork"),Qn=Symbol("returnMany"),ko=Symbol("closing"),ld=Symbol("handleClose"),Jl=Symbol("closed"),hd=Symbol("closeCallbacks"),Co=Symbol("keyEncoding"),Vs=Symbol("valueEncoding"),Og=Symbol("abortOnClose"),Zl=Symbol("legacy"),Dg=Symbol("keys"),kg=Symbol("values"),No=Symbol("limit"),tn=Symbol("count"),Xl=Object.freeze({}),rU=()=>{},q1=!1,pd=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[Jl]=!1,this[hd]=[],this[Xn]=!1,this[ko]=!1,this[Ug]=!1,this[ha]=null,this[Hs]=this[Hs].bind(this),this[Ki]=this[Ki].bind(this),this[ld]=this[ld].bind(this),this[Co]=r[Co],this[Vs]=r[Vs],this[Zl]=n,this[No]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[tn]=0,this[Og]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[tn]}get limit(){return this[No]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[Zl]?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[ko]?this.nextTick(e,new Dr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(e,new Dr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ha]=e,this[tn]>=this[No]?this.nextTick(this[Hs],null):this._next(this[Hs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=V1(r,n),n=Ig(n,$s),r=Rg(r,Xl),Number.isInteger(e)?(this[ko]?this.nextTick(n,new Dr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(n,new Dr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[No]<1/0&&(e=Math.min(e,this[No]-this[tn])),this[Xn]=!0,this[ha]=n,e<=0?this.nextTick(this[Ki],null,[]):this._nextv(e,r,this[Ki])),n[$s]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[$s])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[Zl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[Zl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=V1(e,r),r=Ig(r,$s),e=Rg(e,Xl),this[ko]?this.nextTick(r,new Dr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(r,new Dr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ha]=r,this[Ug]=!0,this[tn]>=this[No]?this.nextTick(this[Ki],null,[]):this._all(e,this[Ki])),r[$s]}_all(e,r){let n=this[tn],i=[],o=()=>{let c=this[No]<1/0?Math.min(1e3,this[No]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Xl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Lo](){let e=this[ha];return this[Og]&&e===null?rU:(this[Xn]=!1,this[ha]=null,this[ko]&&this._close(this[ld]),e)}[Qn](e,r,n){this[Ug]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=Rg(r,Xl),!this[ko]){if(this[Xn])throw new Dr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Co]),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 Dr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=Ig(e,$s),this[Jl]?this.nextTick(e):this[ko]?this[hd].push(e):(this[ko]=!0,this[hd].push(e),this[Xn]?this[Og]&&this[Lo]()(new Dr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[ld])),e[$s]}_close(e){this.nextTick(e)}[ld](){this[Jl]=!0,this.db.detachResource(this);let e=this[hd];this[hd]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[Jl]||await this.close()}}},pa=class extends pd{constructor(e,r){super(e,r,!0),this[Dg]=r.keys!==!1,this[kg]=r.values!==!1}[Hs](e,r,n){let i=this[Lo]();if(e)return i(e);try{r=this[Dg]&&r!==void 0?this[Co].decode(r):void 0,n=this[kg]&&n!==void 0?this[Vs].decode(n):void 0}catch(o){return i(new Po("entry",o))}r===void 0&&n===void 0||this[tn]++,i(null,r,n)}[Ki](e,r){let n=this[Lo]();if(e)return this[Qn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[Dg]&&o!==void 0?this[Co].decode(o):void 0,i[1]=this[kg]&&s!==void 0?this[Vs].decode(s):void 0}}catch(i){return this[Qn](n,new Po("entries",i))}this[tn]+=r.length,this[Qn](n,null,r)}end(e){return!q1&&typeof console<"u"&&(q1=!0,console.warn(new Dr("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)}},Ng=class extends pd{constructor(e,r){super(e,r,!1)}[Hs](e,r){let n=this[Lo]();if(e)return n(e);try{r=r!==void 0?this[Co].decode(r):void 0}catch(i){return n(new Po("key",i))}r!==void 0&&this[tn]++,n(null,r)}[Ki](e,r){let n=this[Lo]();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[Co].decode(o):void 0}}catch(i){return this[Qn](n,new Po("keys",i))}this[tn]+=r.length,this[Qn](n,null,r)}},Cg=class extends pd{constructor(e,r){super(e,r,!1)}[Hs](e,r){let n=this[Lo]();if(e)return n(e);try{r=r!==void 0?this[Vs].decode(r):void 0}catch(i){return n(new Po("value",i))}r!==void 0&&this[tn]++,n(null,r)}[Ki](e,r){let n=this[Lo]();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[Vs].decode(o):void 0}}catch(i){return this[Qn](n,new Po("values",i))}this[tn]+=r.length,this[Qn](n,null,r)}},Po=class extends Dr{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(pa.prototype,t.split(" ")[0],{get(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});pa.keyEncoding=Co;pa.valueEncoding=Vs;Ql.AbstractIterator=pa;Ql.AbstractKeyIterator=Ng;Ql.AbstractValueIterator=Cg});var F1=oe(Lg=>{"use strict";l();var{AbstractKeyIterator:nU,AbstractValueIterator:iU}=Mo(),qs=Symbol("iterator"),yd=Symbol("callback"),ya=Symbol("handleOne"),Fs=Symbol("handleMany"),gd=class extends nU{constructor(e,r){super(e,r),this[qs]=e.iterator({...r,keys:!0,values:!1}),this[ya]=this[ya].bind(this),this[Fs]=this[Fs].bind(this)}},eh=class extends iU{constructor(e,r){super(e,r),this[qs]=e.iterator({...r,keys:!1,values:!0}),this[ya]=this[ya].bind(this),this[Fs]=this[Fs].bind(this)}};for(let t of[gd,eh]){let e=t===gd,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[yd]=n,this[qs].next(this[ya])},t.prototype[ya]=function(n,i,o){let s=this[yd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[yd]=o,this[qs].nextv(n,i,this[Fs])},t.prototype._all=function(n,i){this[yd]=i,this[qs].all(n,this[Fs])},t.prototype[Fs]=function(n,i){let o=this[yd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[qs].seek(n,i)},t.prototype._close=function(n){this[qs].close(n)}}Lg.DefaultKeyIterator=gd;Lg.DefaultValueIterator=eh});var j1=oe(sh=>{"use strict";l();var{AbstractIterator:oU,AbstractKeyIterator:sU,AbstractValueIterator:cU}=Mo(),Pg=En(),pr=Symbol("nut"),ih=Symbol("undefer"),oh=Symbol("factory"),th=class extends oU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.iterator(r),this.db.defer(()=>this[ih]())}},rh=class extends sU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.keys(r),this.db.defer(()=>this[ih]())}},nh=class extends cU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.values(r),this.db.defer(()=>this[ih]())}};for(let t of[th,rh,nh])t.prototype[ih]=function(){this.db.status==="open"&&(this[pr]=this[oh]())},t.prototype._next=function(e){this[pr]!==null?this[pr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Pg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[pr]!==null?this[pr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Pg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[pr]!==null?this[pr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Pg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[pr]!==null?this[pr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[pr]!==null?this[pr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};sh.DeferredIterator=th;sh.DeferredKeyIterator=rh;sh.DeferredValueIterator=nh});var Kg=oe(G1=>{"use strict";l();var{fromCallback:W1}=fd(),ch=En(),{getCallback:aU,getOptions:uU}=Yl(),ah=Symbol("promise"),rn=Symbol("status"),ga=Symbol("operations"),md=Symbol("finishClose"),ma=Symbol("closeCallbacks"),Mg=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[ga]=[],this[ma]=[],this[rn]="open",this[md]=this[md].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[ga].length}put(e,r,n){if(this[rn]!=="open")throw new ch("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[ga].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[rn]!=="open")throw new ch("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[ga].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[rn]!=="open")throw new ch("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[ga]=[],this}_clear(){}write(e,r){return r=aU(e,r),r=W1(r,ah),e=uU(e),this[rn]!=="open"?this.nextTick(r,new ch("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[rn]="writing",this._write(e,n=>{this[rn]="closing",this[ma].push(()=>r(n)),n||this.db.emit("batch",this[ga]),this._close(this[md])})),r[ah]}_write(e,r){}close(e){return e=W1(e,ah),this[rn]==="closing"?this[ma].push(e):this[rn]==="closed"?this.nextTick(e):(this[ma].push(e),this[rn]!=="writing"&&(this[rn]="closing",this._close(this[md]))),e[ah]}_close(e){this.nextTick(e)}[md](){this[rn]="closed",this.db.detachResource(this);let e=this[ma];this[ma]=[];for(let r of e)r()}};G1.AbstractChainedBatch=Mg});var Y1=oe(z1=>{"use strict";l();var{AbstractChainedBatch:dU}=Kg(),fU=En(),wa=Symbol("encoded"),$g=class extends dU{constructor(e){super(e),this[wa]=[]}_put(e,r,n){this[wa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[wa].push({...r,type:"del",key:e})}_clear(){this[wa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[wa].length===0?this.nextTick(r):this.db._batch(this[wa],e,r):this.nextTick(r,new fU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};z1.DefaultChainedBatch=$g});var X1=oe((Sq,Z1)=>{"use strict";l();var J1=En(),lU=Object.prototype.hasOwnProperty,hU=new Set(["lt","lte","gt","gte"]);Z1.exports=function(t,e){let r={};for(let n in t)if(lU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new J1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new J1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});hU.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 Hg=oe((Tq,e2)=>{l();var Q1;e2.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 n2=oe((Bq,r2)=>{"use strict";l();var t2=Hg();r2.exports=function(t,...e){e.length===0?t2(t):t2(()=>t(...e))}});var i2=oe(uh=>{"use strict";l();var{AbstractIterator:pU,AbstractKeyIterator:yU,AbstractValueIterator:gU}=Mo(),ba=Symbol("unfix"),vn=Symbol("iterator"),js=Symbol("handleOne"),Ko=Symbol("handleMany"),$i=Symbol("callback"),wd=class extends pU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ba]=i,this[js]=this[js].bind(this),this[Ko]=this[Ko].bind(this),this[$i]=null}[js](e,r,n){let i=this[$i];if(e)return i(e);r!==void 0&&(r=this[ba](r)),i(e,r,n)}[Ko](e,r){let n=this[$i];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ba](o))}n(e,r)}},bd=class extends yU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ba]=i,this[js]=this[js].bind(this),this[Ko]=this[Ko].bind(this),this[$i]=null}[js](e,r){let n=this[$i];if(e)return n(e);r!==void 0&&(r=this[ba](r)),n(e,r)}[Ko](e,r){let n=this[$i];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ba](o))}n(e,r)}},xd=class extends gU{constructor(e,r,n){super(e,r),this[vn]=n}};for(let t of[wd,bd])t.prototype._next=function(e){this[$i]=e,this[vn].next(this[js])},t.prototype._nextv=function(e,r,n){this[$i]=n,this[vn].nextv(e,r,this[Ko])},t.prototype._all=function(e,r){this[$i]=r,this[vn].all(e,this[Ko])};for(let t of[xd])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[wd,bd,xd])t.prototype._seek=function(e,r){this[vn].seek(e,r)},t.prototype._close=function(e){this[vn].close(e)};uh.AbstractSublevelIterator=wd;uh.AbstractSublevelKeyIterator=bd;uh.AbstractSublevelValueIterator=xd});var a2=oe((Oq,c2)=>{"use strict";l();var Vg=En(),{Buffer:jg}=Ar()||{},{AbstractSublevelIterator:mU,AbstractSublevelKeyIterator:wU,AbstractSublevelValueIterator:bU}=i2(),Hi=Symbol("prefix"),o2=Symbol("upperBound"),Ed=Symbol("prefixRange"),kr=Symbol("parent"),qg=Symbol("unfix"),s2=new TextEncoder,xU={separator:"!"};c2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Vg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Vg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?xU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=vU(i,s);let u=s.charCodeAt(0)+1,d=n[kr]||n;if(!s2.encode(i).every(p=>p>u&&p<127))throw new Vg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(EU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[kr]=d,this[Hi]=new dh(f),this[o2]=new dh(h),this[qg]=new Wg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Hi].utf8+n;if(n.byteLength===0)return this[Hi][i];if(i==="view"){let o=this[Hi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Hi].buffer;return jg.concat([o,n],o.byteLength+n.byteLength)}}[Ed](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[Hi][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[o2][i]}get prefix(){return this[Hi].utf8}get db(){return this[kr]}_open(n,i){this[kr].open({passive:!0},i)}_put(n,i,o,s){this[kr].put(n,i,o,s)}_get(n,i,o){this[kr].get(n,i,o)}_getMany(n,i,o){this[kr].getMany(n,i,o)}_del(n,i,o){this[kr].del(n,i,o)}_batch(n,i,o){this[kr].batch(n,i,o)}_clear(n,i){this[Ed](n,n.keyEncoding),this[kr].clear(n,i)}_iterator(n){this[Ed](n,n.keyEncoding);let i=this[kr].iterator(n),o=this[qg].get(this[Hi].utf8.length,n.keyEncoding);return new mU(this,n,i,o)}_keys(n){this[Ed](n,n.keyEncoding);let i=this[kr].keys(n),o=this[qg].get(this[Hi].utf8.length,n.keyEncoding);return new wU(this,n,i,o)}_values(n){this[Ed](n,n.keyEncoding);let i=this[kr].values(n);return new bU(this,n,i)}}return{AbstractSublevel:e}};var EU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Fg(t,"utf8"),buffer:Fg(t,"buffer"),view:Fg(t,"view")}}},Fg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},dh=class{constructor(e){this.utf8=e,this.view=s2.encode(e),this.buffer=jg?jg.from(this.view.buffer,0,this.view.byteLength):{}}},Wg=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}},vU=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 Zg=oe(Jg=>{"use strict";l();var{supports:SU}=w1(),{Transcoder:AU}=I1(),{EventEmitter:TU}=la(),{fromCallback:$o}=fd(),Sn=En(),{AbstractIterator:Ws}=Mo(),{DefaultKeyIterator:_U,DefaultValueIterator:BU}=F1(),{DeferredIterator:IU,DeferredKeyIterator:RU,DeferredValueIterator:UU}=j1(),{DefaultChainedBatch:u2}=Y1(),{getCallback:Gs,getOptions:Ho}=Yl(),fh=X1(),pe=Symbol("promise"),Vi=Symbol("landed"),zs=Symbol("resources"),Gg=Symbol("closeResources"),vd=Symbol("operations"),Sd=Symbol("undefer"),lh=Symbol("deferOpen"),d2=Symbol("options"),we=Symbol("status"),Ys=Symbol("defaultOptions"),xa=Symbol("transcoder"),hh=Symbol("keyEncoding"),zg=Symbol("valueEncoding"),OU=()=>{},Ad=class extends TU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=Ho(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[zs]=new Set,this[vd]=[],this[lh]=!0,this[d2]=s,this[we]="opening",this.supports=SU(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[xa]=new AU(DU(this)),this[hh]=this[xa].encoding(n||"utf8"),this[zg]=this[xa].encoding(i||"utf8");for(let c of this[xa].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Ys]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[hh].commonName,valueEncoding:this[zg].commonName}),key:Object.freeze({keyEncoding:this[hh].commonName})},this.nextTick(()=>{this[lh]&&this.open({passive:!1},OU)})}get status(){return this[we]}keyEncoding(e){return this[xa].encoding(e??this[hh])}valueEncoding(e){return this[xa].encoding(e??this[zg])}open(e,r){r=Gs(e,r),r=$o(r,pe),e={...this[d2],...Ho(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[we]==="closing"||this[we]==="opening"?this.once(Vi,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(Vi,n):this.nextTick(n):this[we]==="closed"||this[lh]?(this[lh]=!1,this[we]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[we]="closed",this[Gg](()=>{this.emit(Vi),n(i)}),this[Sd]();return}this[we]="open",this[Sd](),this.emit(Vi),this[we]==="open"&&this.emit("open"),this[we]==="open"&&this.emit("ready"),n()})):this[we]==="open"?this.nextTick(n):this.once(Vi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=$o(e,pe);let r=n=>{this[we]==="opening"||this[we]==="closing"?this.once(Vi,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[Sd](),this.emit(Vi),r(i)};this[Gg](()=>{this._close(i=>{if(i)return n(i);this[we]="closed",this[Sd](),this.emit(Vi),this[we]==="closed"&&this.emit("closed"),r()})})}else this[we]==="closed"?this.nextTick(r):this.once(Vi,()=>this.close(e));return e[pe]}[Gg](e){if(this[zs].size===0)return this.nextTick(e);let r=this[zs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[zs])o.close(i);n=!1,this[zs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].entry),this[we]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(Ea(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=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].entry),this[we]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(Ea(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=Gs(n,i),i=$o(i,pe),n=Ho(n,this[Ys].entry),this[we]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(Ea(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=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].key),this[we]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(Ea(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 u2(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=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].empty),this[we]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(Ea(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,Yg.defaults(r))}_sublevel(e,r){return new Yg(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Gs(e,r),r=$o(r,pe),e=Ho(e,this[Ys].empty),this[we]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(Ea(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=fh(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=fh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new IU(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 Ws(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=fh(e,r),e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new RU(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 _U(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=fh(e,r),e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new UU(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 BU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[vd].push(e)}[Sd](){if(this[vd].length===0)return;let e=this[vd];this[vd]=[];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[zs].add(e)}detachResource(e){this[zs].delete(e)}_chainedBatch(){return new u2(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"})}};Ad.prototype.nextTick=n2();var{AbstractSublevel:Yg}=a2()({AbstractLevel:Ad});Jg.AbstractLevel=Ad;Jg.AbstractSublevel=Yg;var Ea=function(t,e){return t[we]!=="open"?(t.nextTick(e,new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},DU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var Xg=oe(Js=>{"use strict";l();Js.AbstractLevel=Zg().AbstractLevel;Js.AbstractSublevel=Zg().AbstractSublevel;Js.AbstractIterator=Mo().AbstractIterator;Js.AbstractKeyIterator=Mo().AbstractKeyIterator;Js.AbstractValueIterator=Mo().AbstractValueIterator;Js.AbstractChainedBatch=Kg().AbstractChainedBatch});var l2=oe((Pq,f2)=>{l();f2.exports=NU;var kU=Hg();function NU(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?kU(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 Qg=oe((Kq,h2)=>{"use strict";l();h2.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 em=oe((Hq,p2)=>{"use strict";l();var CU=new TextEncoder;p2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):CU.encode(t)}});var b2=oe(w2=>{"use strict";l();var{AbstractIterator:LU}=Xg(),y2=Qg(),ph=em(),ei=Symbol("cache"),qi=Symbol("finished"),Nr=Symbol("options"),Fi=Symbol("currentOptions"),Zs=Symbol("position"),tm=Symbol("location"),va=Symbol("first"),g2={},rm=class extends LU{constructor(e,r,n){super(e,n),this[ei]=[],this[qi]=this.limit===0,this[Nr]=n,this[Fi]={...n},this[Zs]=void 0,this[tm]=r,this[va]=!0}_nextv(e,r,n){if(this[va]=!1,this[qi])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[Zs]!==void 0&&(this[Nr].reverse?(this[Fi].lt=this[Zs],this[Fi].lte=void 0):(this[Fi].gt=this[Zs],this[Fi].gte=void 0));let i;try{i=y2(this[Fi])}catch{return this[qi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[tm]],"readonly"),s=o.objectStore(this[tm]),c=[];if(this[Nr].reverse){let a=!this[Nr].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[Zs]=f,c.push([this[Nr].keys&&f!==void 0?ph(f):void 0,this[Nr].values&&h!==void 0?ph(h):void 0]),c.length<e?d.continue():m2(o)}else this[qi]=!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[qi]=!0:this[Zs]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Nr].keys&&p!==void 0?ph(p):void 0,this[Nr].values&&g!==void 0?ph(g):void 0]}m2(o)};this[Nr].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[Nr].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[qi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[va]&&(this[va]=!1,r=1),this._nextv(r,g2,(n,i)=>{if(n)return e(n);this[ei]=i,this._next(e)})}}_all(e,r){this[va]=!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,g2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[va]=!0,this[ei]=[],this[qi]=!1,this[Zs]=void 0,this[Fi]={...this[Nr]};let n;try{n=y2(this[Nr])}catch{this[qi]=!0;return}n!==null&&!n.includes(e)?this[qi]=!0:this[Nr].reverse?this[Fi].lte=e:this[Fi].gte=e}};w2.Iterator=rm;function m2(t){typeof t.commit=="function"&&t.commit()}});var E2=oe((jq,x2)=>{"use strict";l();x2.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 B2=oe(_2=>{"use strict";l();var{AbstractLevel:PU}=Xg(),v2=En(),MU=l2(),{fromCallback:KU}=fd(),{Iterator:$U}=b2(),S2=em(),HU=E2(),VU=Qg(),T2="level-js-",Td=Symbol("idb"),nm=Symbol("namePrefix"),ji=Symbol("location"),im=Symbol("version"),Xs=Symbol("store"),_d=Symbol("onComplete"),A2=Symbol("promise"),yh=class extends PU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new v2("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[ji]=e,this[nm]=i??T2,this[im]=parseInt(o||1,10),this[Td]=null}get location(){return this[ji]}get namePrefix(){return this[nm]}get version(){return this[im]}get db(){return this[Td]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[nm]+this[ji],this[im]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Td]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[ji])||o.createObjectStore(this[ji])}}[Xs](e){return this[Td].transaction([this[ji]],e).objectStore(this[ji])}[_d](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[Xs]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[_d](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new v2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,S2(c))})}_getMany(e,r,n){let i=this[Xs]("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:S2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});MU(o,16,n)}_del(e,r,n){let i=this[Xs]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[_d](o,n)}_put(e,r,n,i){let o=this[Xs]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[_d](s,i)}_iterator(e){return new $U(this,this[ji],e)}_batch(e,r,n){let i=this[Xs]("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=VU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return HU(this,this[ji],n,e,r);try{let o=this[Xs]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[_d](i,r)}_close(e){this[Td].close(),this.nextTick(e)}};yh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=T2),r=KU(r,A2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[A2]};_2.BrowserLevel=yh});var om=oe(I2=>{l();I2.Level=B2().BrowserLevel});var nt=oe((rF,R2)=>{"use strict";l();R2.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 Sa=oe((iF,mh)=>{"use strict";l();var{AbortController:U2,AbortSignal:FU}=typeof self<"u"?self:typeof window<"u"?window:void 0;mh.exports=U2;mh.exports.AbortSignal=FU;mh.exports.default=U2});var Zt=oe((sF,cm)=>{"use strict";l();var jU=Ar(),{kResistStopPropagation:WU,SymbolDispose:GU}=nt(),zU=globalThis.AbortSignal||Sa().AbortSignal,YU=globalThis.AbortController||Sa().AbortController,JU=Object.getPrototypeOf(async function(){}).constructor,O2=globalThis.Blob||jU.Blob,ZU=typeof O2<"u"?function(e){return e instanceof O2}:function(e){return!1},D2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},XU=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},sm=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}};cm.exports={AggregateError:sm,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 JU},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:ZU,deprecate(t,e){return t},addAbortListener:la().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);D2(e,"signal"),XU(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[WU]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[GU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:zU.any||function(e){if(e.length===1)return e[0];let r=new YU,n=()=>r.abort();return e.forEach(i=>{D2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};cm.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var ir=oe((aF,C2)=>{"use strict";l();var{format:QU,inspect:wh,AggregateError:e5}=Zt(),t5=globalThis.AggregateError||e5,r5=Symbol("kIsNodeError"),n5=["string","function","number","object","Function","Object","boolean","bigint","symbol"],i5=/^([A-Z][a-z0-9]*)+$/,o5="__node_internal_",bh={};function ec(t,e){if(!t)throw new bh.ERR_INTERNAL_ASSERTION(e)}function k2(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 s5(t,e,r){if(typeof e=="function")return ec(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 ec(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:QU(e,...r)}function Mt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(s5(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[r5]=!0,bh[t]=n}function N2(t){let e=o5+t.name;return Object.defineProperty(t,"name",{value:e}),t}function c5(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new t5([e,t],e.message);return r.code=e.code,r}return t||e}var am=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new bh.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)=>{ec(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)ec(typeof a=="string","All expected entries have to be of type string"),n5.includes(a)?i.push(a.toLowerCase()):i5.test(a)?o.push(a):(ec(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=wh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=wh(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=wh(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)=>{ec(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)=>{ec(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=k2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=k2(n)),n+="n"):n=wh(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);C2.exports={AbortError:am,aggregateTwoErrors:N2(c5),hideStackFrames:N2,codes:bh}});var Ta=oe((dF,j2)=>{"use strict";l();var{ArrayIsArray:dm,ArrayPrototypeIncludes:K2,ArrayPrototypeJoin:$2,ArrayPrototypeMap:a5,NumberIsInteger:fm,NumberIsNaN:u5,NumberMAX_SAFE_INTEGER:d5,NumberMIN_SAFE_INTEGER:f5,NumberParseInt:l5,ObjectPrototypeHasOwnProperty:h5,RegExpPrototypeExec:H2,String:p5,StringPrototypeToUpperCase:y5,StringPrototypeTrim:g5}=nt(),{hideStackFrames:nn,codes:{ERR_SOCKET_BAD_PORT:m5,ERR_INVALID_ARG_TYPE:Xt,ERR_INVALID_ARG_VALUE:Aa,ERR_OUT_OF_RANGE:tc,ERR_UNKNOWN_SIGNAL:L2}}=ir(),{normalizeEncoding:w5}=Zt(),{isAsyncFunction:b5,isArrayBufferView:x5}=Zt().types,P2={};function E5(t){return t===(t|0)}function v5(t){return t===t>>>0}var S5=/^[0-7]+$/,A5="must be a 32-bit unsigned integer or an octal string";function T5(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(H2(S5,t)===null)throw new Aa(e,t,A5);t=l5(t,8)}return V2(t,e),t}var _5=nn((t,e,r=f5,n=d5)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!fm(t))throw new tc(e,"an integer",t);if(t<r||t>n)throw new tc(e,`>= ${r} && <= ${n}`,t)}),B5=nn((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!fm(t))throw new tc(e,"an integer",t);if(t<r||t>n)throw new tc(e,`>= ${r} && <= ${n}`,t)}),V2=nn((t,e,r=!1)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!fm(t))throw new tc(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new tc(e,`>= ${n} && <= ${i}`,t)});function lm(t,e){if(typeof t!="string")throw new Xt(e,"string",t)}function I5(t,e,r=void 0,n){if(typeof t!="number")throw new Xt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&u5(t))throw new tc(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var R5=nn((t,e,r)=>{if(!K2(r,t)){let i="must be one of: "+$2(a5(r,o=>typeof o=="string"?`'${o}'`:p5(o)),", ");throw new Aa(e,t,i)}});function q2(t,e){if(typeof t!="boolean")throw new Xt(e,"boolean",t)}function um(t,e,r){return t==null||!h5(t,e)?r:t[e]}var U5=nn((t,e,r=null)=>{let n=um(r,"allowArray",!1),i=um(r,"allowFunction",!1);if(!um(r,"nullable",!1)&&t===null||!n&&dm(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Xt(e,"Object",t)}),O5=nn((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Xt(e,"a dictionary",t)}),xh=nn((t,e,r=0)=>{if(!dm(t))throw new Xt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new Aa(e,t,n)}});function D5(t,e){xh(t,e);for(let r=0;r<t.length;r++)lm(t[r],`${e}[${r}]`)}function k5(t,e){xh(t,e);for(let r=0;r<t.length;r++)q2(t[r],`${e}[${r}]`)}function N5(t,e){xh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Xt(i,"AbortSignal",n);F2(n,i)}}function C5(t,e="signal"){if(lm(t,e),P2[t]===void 0)throw P2[y5(t)]!==void 0?new L2(t+" (signals must use all capital letters)"):new L2(t)}var L5=nn((t,e="buffer")=>{if(!x5(t))throw new Xt(e,["Buffer","TypedArray","DataView"],t)});function P5(t,e){let r=w5(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Aa("encoding",e,`is invalid for data of length ${n}`)}function M5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&g5(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new m5(e,t,r);return t|0}var F2=nn((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Xt(e,"AbortSignal",t)}),K5=nn((t,e)=>{if(typeof t!="function")throw new Xt(e,"Function",t)}),$5=nn((t,e)=>{if(typeof t!="function"||b5(t))throw new Xt(e,"Function",t)}),H5=nn((t,e)=>{if(t!==void 0)throw new Xt(e,"undefined",t)});function V5(t,e,r){if(!K2(r,t))throw new Xt(e,`('${$2(r,"|")}')`,t)}var q5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function M2(t,e){if(typeof t>"u"||!H2(q5,t))throw new Aa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function F5(t){if(typeof t=="string")return M2(t,"hints"),t;if(dm(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];M2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new Aa("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}j2.exports={isInt32:E5,isUint32:v5,parseFileMode:T5,validateArray:xh,validateStringArray:D5,validateBooleanArray:k5,validateAbortSignalArray:N5,validateBoolean:q2,validateBuffer:L5,validateDictionary:O5,validateEncoding:P5,validateFunction:K5,validateInt32:B5,validateInteger:_5,validateNumber:I5,validateObject:U5,validateOneOf:R5,validatePlainFunction:$5,validatePort:M5,validateSignalName:C5,validateString:lm,validateUint32:V2,validateUndefined:H5,validateUnion:V5,validateAbortSignal:F2,validateLinkHeaderValue:F5}});var ri=oe((lF,sS)=>{"use strict";l();var{SymbolAsyncIterator:W2,SymbolIterator:G2,SymbolFor:rc}=nt(),z2=rc("nodejs.stream.destroyed"),Y2=rc("nodejs.stream.errored"),hm=rc("nodejs.stream.readable"),pm=rc("nodejs.stream.writable"),J2=rc("nodejs.stream.disturbed"),j5=rc("nodejs.webstream.isClosedPromise"),W5=rc("nodejs.webstream.controllerErrorFunction");function Eh(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 vh(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 G5(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 Z2(t){return!!(t&&!ti(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function X2(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 z5(t){return Z2(t)||X2(t)||Q2(t)}function Y5(t,e){return t==null?!1:e===!0?typeof t[W2]=="function":e===!1?typeof t[G2]=="function":typeof t[W2]=="function"||typeof t[G2]=="function"}function Sh(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[z2]||n!=null&&n.destroyed)}function eS(t){if(!vh(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 J5(t,e){if(!vh(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 Z5(t){if(!Eh(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 tS(t,e){if(!Eh(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 rS(t){return t&&t[hm]!=null?t[hm]:typeof t?.readable!="boolean"?null:Sh(t)?!1:Eh(t)&&t.readable&&!tS(t)}function nS(t){return t&&t[pm]!=null?t[pm]:typeof t?.writable!="boolean"?null:Sh(t)?!1:vh(t)&&t.writable&&!eS(t)}function X5(t,e){return ti(t)?Sh(t)?!0:!(e?.readable!==!1&&rS(t)||e?.writable!==!1&&nS(t)):null}function Q5(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 e3(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 t3(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"&&iS(t)?t._closed:null}function iS(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function oS(t){return typeof t._sent100=="boolean"&&iS(t)}function r3(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 n3(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&oS(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function i3(t){var e;return!!(t&&((e=t[J2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function o3(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[Y2])!==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))}sS.exports={isDestroyed:Sh,kIsDestroyed:z2,isDisturbed:i3,kIsDisturbed:J2,isErrored:o3,kIsErrored:Y2,isReadable:rS,kIsReadable:hm,kIsClosedPromise:j5,kControllerErrorFunction:W5,kIsWritable:pm,isClosed:t3,isDuplexNodeStream:G5,isFinished:X5,isIterable:Y5,isReadableNodeStream:Eh,isReadableStream:Z2,isReadableEnded:Z5,isReadableFinished:tS,isReadableErrored:e3,isNodeStream:ti,isWebStream:z5,isWritable:nS,isWritableNodeStream:vh,isWritableStream:X2,isWritableEnded:eS,isWritableFinished:J5,isWritableErrored:Q5,isServerRequest:r3,isServerResponse:oS,willEmitClose:n3,isTransformStream:Q2}});var Wi=oe((pF,bm)=>{l();var Vo=Ei(),{AbortError:yS,codes:s3}=ir(),{ERR_INVALID_ARG_TYPE:c3,ERR_STREAM_PREMATURE_CLOSE:cS}=s3,{kEmptyObject:gm,once:mm}=Zt(),{validateAbortSignal:a3,validateFunction:u3,validateObject:d3,validateBoolean:f3}=Ta(),{Promise:l3,PromisePrototypeThen:h3,SymbolDispose:gS}=nt(),{isClosed:p3,isReadable:aS,isReadableNodeStream:ym,isReadableStream:y3,isReadableFinished:uS,isReadableErrored:dS,isWritable:fS,isWritableNodeStream:lS,isWritableStream:g3,isWritableFinished:hS,isWritableErrored:pS,isNodeStream:m3,willEmitClose:w3,kIsClosedPromise:b3}=ri(),_a;function x3(t){return t.setHeader&&typeof t.abort=="function"}var wm=()=>{};function mS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=gm):e==null?e=gm:d3(e,"options"),u3(r,"callback"),a3(e.signal,"options.signal"),r=mm(r),y3(t)||g3(t))return E3(t,e,r);if(!m3(t))throw new c3("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:ym(t),s=(i=e.writable)!==null&&i!==void 0?i:lS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=w3(t)&&ym(t)===o&&lS(t)===s,f=hS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=uS(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=p3(t),S=()=>{E=!0;let T=pS(t)||dS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&ym(t,!0)&&!uS(t,!1))return r.call(t,new cS);if(s&&!f&&!hS(t,!1))return r.call(t,new cS);r.call(t)},I=()=>{E=!0;let T=pS(t)||dS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};x3(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?Vo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Vo.nextTick(I):(!o&&(!d||aS(t))&&(f||fS(t)===!1)||!s&&(!d||fS(t))&&(p||aS(t)===!1)||a&&t.req&&t.aborted)&&Vo.nextTick(I);let O=()=>{r=wm,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 yS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Vo.nextTick(T);else{_a=_a||Zt().addAbortListener;let M=_a(e.signal,T),q=r;r=mm((...j)=>{M[gS](),q.apply(t,j)})}}return O}function E3(t,e,r){let n=!1,i=wm;if(e.signal)if(i=()=>{n=!0,r.call(t,new yS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Vo.nextTick(i);else{_a=_a||Zt().addAbortListener;let s=_a(e.signal,i),c=r;r=mm((...a)=>{s[gS](),c.apply(t,a)})}let o=(...s)=>{n||Vo.nextTick(()=>r.apply(t,s))};return h3(t[b3].promise,o,o),wm}function v3(t,e){var r;let n=!1;return e===null&&(e=gm),(r=e)!==null&&r!==void 0&&r.cleanup&&(f3(e.cleanup,"cleanup"),n=e.cleanup),new l3((i,o)=>{let s=mS(t,e,c=>{n&&s(),c?o(c):i()})})}bm.exports=mS;bm.exports.finished=v3});var nc=oe((gF,TS)=>{"use strict";l();var ni=Ei(),{aggregateTwoErrors:S3,codes:{ERR_MULTIPLE_CALLBACK:A3},AbortError:T3}=ir(),{Symbol:xS}=nt(),{kIsDestroyed:_3,isDestroyed:B3,isFinished:I3,isServerRequest:R3}=ri(),ES=xS("kDestroy"),xm=xS("kConstruct");function vS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function U3(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):(vS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?wS(this,t,e):this.once(ES,function(o){wS(this,S3(o,t),e)}),this)}function wS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;vS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ni.nextTick(O3,t,o):ni.nextTick(SS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function O3(t,e){Em(t,e),SS(t)}function SS(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 Em(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 D3(){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 vm(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(Em,t,e):Em(t,e))}function k3(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(xm,e),!(t.listenerCount(xm)>1)&&ni.nextTick(N3,t)}function N3(t){let e=!1;function r(n){if(e){vm(t,n??new A3);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(ES,n):n?vm(t,n,!0):ni.nextTick(C3,t)}try{t._construct(n=>{ni.nextTick(r,n)})}catch(n){ni.nextTick(r,n)}}function C3(t){t.emit(xm)}function bS(t){return t?.setHeader&&typeof t.abort=="function"}function AS(t){t.emit("close")}function L3(t,e){t.emit("error",e),ni.nextTick(AS,t)}function P3(t,e){!t||B3(t)||(!e&&!I3(t)&&(e=new T3),R3(t)?(t.socket=null,t.destroy(e)):bS(t)?t.abort():bS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ni.nextTick(L3,t,e):ni.nextTick(AS,t),t.destroyed||(t[_3]=!0))}TS.exports={construct:k3,destroyer:P3,destroy:U3,undestroy:D3,errorOrDestroy:vm}});var _h=oe((wF,BS)=>{"use strict";l();var{ArrayIsArray:M3,ObjectSetPrototypeOf:_S}=nt(),{EventEmitter:Ah}=la();function Th(t){Ah.call(this,t)}_S(Th.prototype,Ah.prototype);_S(Th,Ah);Th.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(),Ah.listenerCount(this,"error")===0&&this.emit("error",d)}Sm(r,"error",a),Sm(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 Sm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):M3(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}BS.exports={Stream:Th,prependListener:Sm}});var Bd=oe((xF,Bh)=>{"use strict";l();var{SymbolDispose:K3}=nt(),{AbortError:IS,codes:$3}=ir(),{isNodeStream:RS,isWebStream:H3,kControllerErrorFunction:V3}=ri(),q3=Wi(),{ERR_INVALID_ARG_TYPE:US}=$3,Am,F3=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new US(e,"AbortSignal",t)};Bh.exports.addAbortSignal=function(e,r){if(F3(e,"signal"),!RS(r)&&!H3(r))throw new US("stream",["ReadableStream","WritableStream","Stream"],r);return Bh.exports.addAbortSignalNoValidate(e,r)};Bh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=RS(e)?()=>{e.destroy(new IS(void 0,{cause:t.reason}))}:()=>{e[V3](new IS(void 0,{cause:t.reason}))};if(t.aborted)r();else{Am=Am||Zt().addAbortListener;let n=Am(t,r);q3(e,n[K3])}return e}});var kS=oe((SF,DS)=>{"use strict";l();var{StringPrototypeSlice:OS,SymbolIterator:j3,TypedArrayPrototypeSet:Ih,Uint8Array:W3}=nt(),{Buffer:Tm}=Ar(),{inspect:G3}=Zt();DS.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 Tm.alloc(0);let r=Tm.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Ih(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}*[j3](){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+=OS(o,0,e),this.head=n,n.data=OS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=Tm.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Ih(r,s,n-e),e-=s.length;else{e===s.length?(Ih(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Ih(r,new W3(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 G3(this,{...r,depth:0,customInspect:!1})}}});var Id=oe((TF,PS)=>{"use strict";l();var{MathFloor:z3,NumberIsInteger:Y3}=nt(),{validateInteger:J3}=Ta(),{ERR_INVALID_ARG_VALUE:Z3}=ir().codes,NS=16*1024,CS=16;function X3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function LS(t){return t?CS:NS}function Q3(t,e){J3(e,"value",0),t?CS=e:NS=e}function eO(t,e,r,n){let i=X3(e,n,r);if(i!=null){if(!Y3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new Z3(o,i)}return z3(i)}return LS(t.objectMode)}PS.exports={getHighWaterMark:eO,getDefaultHighWaterMark:LS,setDefaultHighWaterMark:Q3}});var $S=oe((_m,KS)=>{l();var Rh=Ar(),ii=Rh.Buffer;function MS(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?KS.exports=Rh:(MS(Rh,_m),_m.Buffer=ic);function ic(t,e,r){return ii(t,e,r)}ic.prototype=Object.create(ii.prototype);MS(ii,ic);ic.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};ic.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};ic.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};ic.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Rh.SlowBuffer(t)}});var qS=oe(VS=>{"use strict";l();var Im=$S().Buffer,HS=Im.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 tO(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 rO(t){var e=tO(t);if(typeof e!="string"&&(Im.isEncoding===HS||!HS(t)))throw new Error("Unknown encoding: "+t);return e||t}VS.StringDecoder=Rd;function Rd(t){this.encoding=rO(t);var e;switch(this.encoding){case"utf16le":this.text=aO,this.end=uO,e=4;break;case"utf8":this.fillLast=oO,e=4;break;case"base64":this.text=dO,this.end=fO,e=3;break;default:this.write=lO,this.end=hO;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Im.allocUnsafe(e)}Rd.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||""};Rd.prototype.end=cO;Rd.prototype.text=sO;Rd.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 Bm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function nO(t,e,r){var n=e.length-1;if(n<r)return 0;var i=Bm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=Bm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=Bm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function iO(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 oO(t){var e=this.lastTotal-this.lastNeed,r=iO(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 sO(t,e){var r=nO(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 cO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function aO(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 uO(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 dO(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 fO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function lO(t){return t.toString(this.encoding)}function hO(t){return t&&t.length?this.write(t):""}});var Rm=oe((UF,GS)=>{"use strict";l();var FS=Ei(),{PromisePrototypeThen:pO,SymbolAsyncIterator:jS,SymbolIterator:WS}=nt(),{Buffer:yO}=Ar(),{ERR_INVALID_ARG_TYPE:gO,ERR_STREAM_NULL_VALUES:mO}=ir().codes;function wO(t,e,r){let n;if(typeof e=="string"||e instanceof yO)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[jS])i=!0,n=e[jS]();else if(e&&e[WS])i=!1,n=e[WS]();else throw new gO("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){pO(c(u),()=>FS.nextTick(d,u),f=>FS.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 mO;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}GS.exports=wO});var Od=oe((DF,fA)=>{l();var An=Ei(),{ArrayPrototypeIndexOf:bO,NumberIsInteger:xO,NumberIsNaN:EO,NumberParseInt:vO,ObjectDefineProperties:Pm,ObjectKeys:SO,ObjectSetPrototypeOf:JS,Promise:ZS,SafeSet:AO,SymbolAsyncDispose:TO,SymbolAsyncIterator:_O,Symbol:BO}=nt();fA.exports=ye;ye.ReadableState=kh;var{EventEmitter:IO}=la(),{Stream:qo,prependListener:RO}=_h(),{Buffer:Um}=Ar(),{addAbortSignal:UO}=Bd(),XS=Wi(),be=Zt().debuglog("stream",t=>{be=t}),OO=kS(),Ra=nc(),{getHighWaterMark:DO,getDefaultHighWaterMark:kO}=Id(),{aggregateTwoErrors:zS,codes:{ERR_INVALID_ARG_TYPE:NO,ERR_METHOD_NOT_IMPLEMENTED:CO,ERR_OUT_OF_RANGE:LO,ERR_STREAM_PUSH_AFTER_EOF:PO,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:MO},AbortError:KO}=ir(),{validateObject:$O}=Ta(),oc=BO("kPaused"),{StringDecoder:QS}=qS(),HO=Rm();JS(ye.prototype,qo.prototype);JS(ye,qo);var Om=()=>{},{errorOrDestroy:Ba}=Ra,Ia=1,VO=2,eA=4,Ud=8,tA=16,Uh=32,Oh=64,rA=128,qO=256,FO=512,jO=1024,Cm=2048,Lm=4096,WO=8192,GO=16384,zO=32768,nA=65536,YO=1<<17,JO=1<<18;function St(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Pm(kh.prototype,{objectMode:St(Ia),ended:St(VO),endEmitted:St(eA),reading:St(Ud),constructed:St(tA),sync:St(Uh),needReadable:St(Oh),emittedReadable:St(rA),readableListening:St(qO),resumeScheduled:St(FO),errorEmitted:St(jO),emitClose:St(Cm),autoDestroy:St(Lm),destroyed:St(WO),closed:St(GO),closeEmitted:St(zO),multiAwaitDrain:St(nA),readingMore:St(YO),dataEmitted:St(JO)});function kh(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.state=Cm|Lm|tA|Uh,t&&t.objectMode&&(this.state|=Ia),r&&t&&t.readableObjectMode&&(this.state|=Ia),this.highWaterMark=t?DO(this,t,"readableHighWaterMark",r):kO(!1),this.buffer=new OO,this.length=0,this.pipes=[],this.flowing=null,this[oc]=null,t&&t.emitClose===!1&&(this.state&=~Cm),t&&t.autoDestroy===!1&&(this.state&=~Lm),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 kh(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&&UO(t.signal,this)),qo.call(this,t),Ra.construct(this,()=>{this._readableState.needReadable&&Dh(this,this._readableState)})}ye.prototype.destroy=Ra.destroy;ye.prototype._undestroy=Ra.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[IO.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[TO]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new KO,this.destroy(t)),new ZS((e,r)=>XS(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return iA(this,t,e,!1)};ye.prototype.unshift=function(t,e){return iA(this,t,e,!0)};function iA(t,e,r,n){be("readableAddChunk",e);let i=t._readableState,o;if(i.state&Ia||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Um.from(e,r).toString(i.encoding):(e=Um.from(e,r),r=""))):e instanceof Um?r="":qo._isUint8Array(e)?(e=qo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new NO("chunk",["string","Buffer","Uint8Array"],e))),o)Ba(t,o);else if(e===null)i.state&=~Ud,QO(t,i);else if(i.state&Ia||e&&e.length>0)if(n)if(i.state&eA)Ba(t,new MO);else{if(i.destroyed||i.errored)return!1;Dm(t,i,e,!0)}else if(i.ended)Ba(t,new PO);else{if(i.destroyed||i.errored)return!1;i.state&=~Ud,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?Dm(t,i,e,!1):Dh(t,i)):Dm(t,i,e,!1)}else n||(i.state&=~Ud,Dh(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function Dm(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&nA?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&Oh&&Nh(t)),Dh(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[oc]===!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 ZO=1073741824;function XO(t){if(t>ZO)throw new LO("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function YS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Ia?1:EO(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:xO(t)||(t=vO(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=XO(t)),t!==0&&(e.state&=~rA),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?km(this):Nh(this),null;if(t=YS(t,e),t===0&&e.ended)return e.length===0&&km(this),null;let n=(e.state&Oh)!==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|=Ud|Uh,e.length===0&&(e.state|=Oh);try{this._read(e.highWaterMark)}catch(o){Ba(this,o)}e.state&=~Uh,e.reading||(t=YS(r,e))}let i;return t>0?i=uA(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&&km(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function QO(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?Nh(t):(e.needReadable=!1,e.emittedReadable=!0,oA(t))}}function Nh(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(oA,t))}function oA(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,cA(t)}function Dh(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,An.nextTick(eD,t,e))}function eD(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 CO("_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 AO(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=tD(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?Ba(t,S):t.emit("error",S)}}RO(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 tD(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=bO(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=qo.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?Nh(this):n.reading||An.nextTick(rD,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=qo.prototype.removeListener.call(this,t,e);return t==="readable"&&An.nextTick(sA,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=qo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&An.nextTick(sA,this),e};function sA(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[oc]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function rD(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,nD(this,t)),t[oc]=!1,this};function nD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(iD,t,e))}function iD(t,e){be("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),cA(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[oc]=!0,this};function cA(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=>{Ba(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=SO(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[_O]=function(){return aA(this)};ye.prototype.iterator=function(t){return t!==void 0&&$O(t,"options"),aA(this,t)};function aA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=oD(t,e);return r.stream=t,r}async function*oD(t,e){let r=Om;function n(s){this===t?(r(),r=Om):r=s}t.on("readable",n);let i,o=XS(t,{writable:!1},s=>{i=s?zS(i,s):null,r(),r=Om});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 ZS(n)}}}catch(s){throw i=zS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ra.destroyer(t,null):(t.off("readable",n),o())}}Pm(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}}});Pm(kh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[oc]!==!1},set(t){this[oc]=!!t}}});ye._fromList=uA;function uA(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 km(t){let e=t._readableState;be("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,An.nextTick(sD,e,t))}function sD(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(cD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function cD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return HO(ye,t,e)};var Nm;function dA(){return Nm===void 0&&(Nm={}),Nm}ye.fromWeb=function(t,e){return dA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return dA().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){Ra.destroyer(t,i),o(i)}}).wrap(t)}});var Kh=oe((NF,SA)=>{l();var sc=Ei(),{ArrayPrototypeSlice:pA,Error:aD,FunctionPrototypeSymbolHasInstance:yA,ObjectDefineProperty:gA,ObjectDefineProperties:uD,ObjectSetPrototypeOf:mA,StringPrototypeToLowerCase:dD,Symbol:fD,SymbolHasInstance:lD}=nt();SA.exports=it;it.WritableState=Nd;var{EventEmitter:hD}=la(),Dd=_h().Stream,{Buffer:Ch}=Ar(),Mh=nc(),{addAbortSignal:pD}=Bd(),{getHighWaterMark:yD,getDefaultHighWaterMark:gD}=Id(),{ERR_INVALID_ARG_TYPE:mD,ERR_METHOD_NOT_IMPLEMENTED:wD,ERR_MULTIPLE_CALLBACK:wA,ERR_STREAM_CANNOT_PIPE:bD,ERR_STREAM_DESTROYED:kd,ERR_STREAM_ALREADY_FINISHED:xD,ERR_STREAM_NULL_VALUES:ED,ERR_STREAM_WRITE_AFTER_END:vD,ERR_UNKNOWN_ENCODING:bA}=ir().codes,{errorOrDestroy:Ua}=Mh;mA(it.prototype,Dd.prototype);mA(it,Dd);function $m(){}var Oa=fD("kOnFinished");function Nd(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?yD(this,t,"writableHighWaterMark",r):gD(!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=AD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Ph(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[Oa]=[]}function Ph(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Nd.prototype.getBuffer=function(){return pA(this.buffered,this.bufferedIndex)};gA(Nd.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof oi();if(!e&&!yA(it,this))return new it(t);this._writableState=new Nd(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&&pD(t.signal,this)),Dd.call(this,t),Mh.construct(this,()=>{let r=this._writableState;r.writing||Vm(this,r),qm(this,r)})}gA(it,lD,{__proto__:null,value:function(t){return yA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Nd}});it.prototype.pipe=function(){Ua(this,new bD)};function xA(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"&&!Ch.isEncoding(r))throw new bA(r);typeof n!="function"&&(n=$m)}if(e===null)throw new ED;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Ch.from(e,r),r="buffer");else if(e instanceof Ch)r="buffer";else if(Dd._isUint8Array(e))e=Dd._uint8ArrayToBuffer(e),r="buffer";else throw new mD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new vD:i.destroyed&&(o=new kd("write")),o?(sc.nextTick(n,o),Ua(t,o,!0),o):(i.pendingcb++,SD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return xA(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||Vm(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=dD(e)),!Ch.isEncoding(e))throw new bA(e);return this._writableState.defaultEncoding=e,this};function SD(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!==$m&&(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 lA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new kd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hA(t,e,r,n){--e.pendingcb,n(r),Hm(e),Ua(t,r)}function AD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Ua(t,new wA);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?sc.nextTick(hA,t,r,e,i):hA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Vm(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},sc.nextTick(TD,r.afterWriteTickInfo)):EA(t,r,1,i))}function TD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,EA(t,e,r,n)}function EA(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&&Hm(e),qm(t,e)}function Hm(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 kd("write"))}let r=t[Oa].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new kd("end"))}Ph(t)}function Vm(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?$m:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:pA(r,s);a.allBuffers=e.allBuffers,lA(t,e,!0,e.length,a,"",c),Ph(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;lA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Ph(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 wD("_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=xA(this,t,e);o instanceof aD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,qm(this,n,!0),n.ended=!0):n.finished?i=new xD("end"):n.destroyed&&(i=new kd("end"))),typeof r=="function"&&(i||n.finished?sc.nextTick(r,i):n[Oa].push(r)),this};function Lh(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 _D(t,e){let r=!1;function n(i){if(r){Ua(t,i??wA());return}if(r=!0,e.pendingcb--,i){let o=e[Oa].splice(0);for(let s=0;s<o.length;s++)o[s](i);Ua(t,i,e.sync)}else Lh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,sc.nextTick(Km,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function BD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,_D(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function qm(t,e,r){Lh(e)&&(BD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,sc.nextTick((n,i)=>{Lh(i)?Km(n,i):i.pendingcb--},t,e)):Lh(e)&&(e.pendingcb++,Km(t,e))))}function Km(t,e){e.pendingcb--,e.finished=!0;let r=e[Oa].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()}}uD(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 ID=Mh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Oa].length)&&sc.nextTick(Hm,r),ID.call(this,t,e),this};it.prototype._undestroy=Mh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[hD.captureRejectionSymbol]=function(t){this.destroy(t)};var Mm;function vA(){return Mm===void 0&&(Mm={}),Mm}it.fromWeb=function(t,e){return vA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return vA().newWritableStreamFromStreamWritable(t)}});var MA=oe((LF,PA)=>{l();var Fm=Ei(),RD=Ar(),{isReadable:UD,isWritable:OD,isIterable:AA,isNodeStream:DD,isReadableNodeStream:TA,isWritableNodeStream:_A,isDuplexNodeStream:kD,isReadableStream:BA,isWritableStream:IA}=ri(),RA=Wi(),{AbortError:CA,codes:{ERR_INVALID_ARG_TYPE:ND,ERR_INVALID_RETURN_VALUE:UA}}=ir(),{destroyer:ka}=nc(),CD=oi(),LA=Od(),LD=Kh(),{createDeferredPromise:OA}=Zt(),DA=Rm(),kA=globalThis.Blob||RD.Blob,PD=typeof kA<"u"?function(e){return e instanceof kA}:function(e){return!1},MD=globalThis.AbortController||Sa().AbortController,{FunctionPrototypeCall:NA}=nt(),Fo=class extends CD{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)}};PA.exports=function t(e,r){if(kD(e))return e;if(TA(e))return Da({readable:e});if(_A(e))return Da({writable:e});if(DD(e))return Da({writable:!1,readable:!1});if(BA(e))return Da({readable:LA.fromWeb(e)});if(IA(e))return Da({writable:LD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=KD(e);if(AA(i))return DA(Fo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=NA(a,i,f=>{if(f!=null)throw new UA("nully","body",f)},f=>{ka(u,f)});return u=new Fo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Fm.nextTick(f,null)}catch(h){Fm.nextTick(f,h)}})},destroy:c})}throw new UA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(PD(e))return t(e.arrayBuffer());if(AA(e))return DA(Fo,e,{objectMode:!0,writable:!1});if(BA(e?.readable)&&IA(e?.writable))return Fo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?TA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?_A(e?.writable)?e?.writable:t(e.writable):void 0;return Da({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return NA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{ka(i,o)}),i=new Fo({objectMode:!0,writable:!1,read(){}})}throw new ND(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function KD(t){let{promise:e,resolve:r}=OA(),n=new MD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Fm.nextTick(u),a)return;if(i.aborted)throw new CA(void 0,{cause:i.reason});({promise:e,resolve:r}=OA()),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 Da(t){let e=t.readable&&typeof t.readable.read!="function"?LA.wrap(t.readable):t.readable,r=t.writable,n=!!UD(e),i=!!OD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new Fo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(RA(r,f=>{i=!1,f&&ka(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&&(RA(e,f=>{n=!1,f&&ka(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 CA),c=null,o=null,s=null,a===null?h(f):(a=h,ka(r,f),ka(e,f))},u}});var oi=oe((MF,HA)=>{"use strict";l();var{ObjectDefineProperties:$D,ObjectGetOwnPropertyDescriptor:Gi,ObjectKeys:HD,ObjectSetPrototypeOf:KA}=nt();HA.exports=Tn;var Gm=Od(),on=Kh();KA(Tn.prototype,Gm.prototype);KA(Tn,Gm);{let t=HD(on.prototype);for(let e=0;e<t.length;e++){let r=t[e];Tn.prototype[r]||(Tn.prototype[r]=on.prototype[r])}}function Tn(t){if(!(this instanceof Tn))return new Tn(t);Gm.call(this,t),on.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}$D(Tn.prototype,{writable:{__proto__:null,...Gi(on.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Gi(on.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Gi(on.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Gi(on.prototype,"writableBuffer")},writableLength:{__proto__:null,...Gi(on.prototype,"writableLength")},writableFinished:{__proto__:null,...Gi(on.prototype,"writableFinished")},writableCorked:{__proto__:null,...Gi(on.prototype,"writableCorked")},writableEnded:{__proto__:null,...Gi(on.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Gi(on.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 jm;function $A(){return jm===void 0&&(jm={}),jm}Tn.fromWeb=function(t,e){return $A().newStreamDuplexFromReadableWritablePair(t,e)};Tn.toWeb=function(t){return $A().newReadableWritablePairFromDuplex(t)};var Wm;Tn.from=function(t){return Wm||(Wm=MA()),Wm(t,"body")}});var Jm=oe(($F,qA)=>{"use strict";l();var{ObjectSetPrototypeOf:VA,Symbol:VD}=nt();qA.exports=zi;var{ERR_METHOD_NOT_IMPLEMENTED:qD}=ir().codes,Ym=oi(),{getHighWaterMark:FD}=Id();VA(zi.prototype,Ym.prototype);VA(zi,Ym);var Cd=VD("kCallback");function zi(t){if(!(this instanceof zi))return new zi(t);let e=t?FD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),Ym.call(this,t),this._readableState.sync=!1,this[Cd]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",jD)}function zm(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 jD(){this._final!==zm&&zm.call(this)}zi.prototype._final=zm;zi.prototype._transform=function(t,e,r){throw new qD("_transform()")};zi.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[Cd]=r})};zi.prototype._read=function(){if(this[Cd]){let t=this[Cd];this[Cd]=null,t()}}});var Xm=oe((VF,jA)=>{"use strict";l();var{ObjectSetPrototypeOf:FA}=nt();jA.exports=Na;var Zm=Jm();FA(Na.prototype,Zm.prototype);FA(Na,Zm);function Na(t){if(!(this instanceof Na))return new Na(t);Zm.call(this,t)}Na.prototype._transform=function(t,e,r){r(null,t)}});var qh=oe((FF,JA)=>{l();var Ld=Ei(),{ArrayIsArray:WD,Promise:GD,SymbolAsyncIterator:zD,SymbolDispose:YD}=nt(),Vh=Wi(),{once:JD}=Zt(),ZD=nc(),WA=oi(),{aggregateTwoErrors:XD,codes:{ERR_INVALID_ARG_TYPE:cw,ERR_INVALID_RETURN_VALUE:Qm,ERR_MISSING_ARGS:QD,ERR_STREAM_DESTROYED:e4,ERR_STREAM_PREMATURE_CLOSE:t4},AbortError:r4}=ir(),{validateFunction:n4,validateAbortSignal:i4}=Ta(),{isIterable:cc,isReadable:ew,isReadableNodeStream:Hh,isNodeStream:GA,isTransformStream:Ca,isWebStream:o4,isReadableStream:tw,isReadableFinished:s4}=ri(),c4=globalThis.AbortController||Sa().AbortController,rw,nw,iw;function zA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Vh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,ZD.destroyer(t,o||new e4("pipe")))},cleanup:i}}function a4(t){return n4(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function ow(t){if(cc(t))return t;if(Hh(t))return u4(t);throw new cw("val",["Readable","Iterable","AsyncIterable"],t)}async function*u4(t){nw||(nw=Od()),yield*nw.prototype[zD].call(t)}async function $h(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new GD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Vh(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?XD(i,u):u)}finally{a(),e.off("drain",s)}}async function sw(t,e,r,{end:n}){Ca(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 d4(...t){return YA(t,JD(a4(t)))}function YA(t,e,r){if(t.length===1&&WD(t[0])&&(t=t[0]),t.length<2)throw new QD("streams");let n=new c4,i=n.signal,o=r?.signal,s=[];i4(o,"options.signal");function c(){g(new r4)}iw=iw||Zt().addAbortListener;let a;o&&(a=iw(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[YD](),n.abort(),O&&(u||s.forEach(M=>M()),Ld.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(GA(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}=zA(O,T,M);f.push(X),ew(O)&&j&&s.push(Q)}O.on("error",$),ew(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!cc(y))throw new Qm("Iterable, AsyncIterable or Stream","source",y)}else cc(O)||Hh(O)||Ca(O)?y=O:y=WA.from(O);else if(typeof O=="function"){if(Ca(y)){var E;y=ow((E=y)===null||E===void 0?void 0:E.readable)}else y=ow(y);if(y=O(y,{signal:i}),T){if(!cc(y,!0))throw new Qm("AsyncIterable",`transform[${A-1}]`,y)}else{var S;rw||(rw=Xm());let $=new rw({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(),Ld.nextTick(p)},_=>{$.destroy(_),Ld.nextTick(p,_)});else if(cc(y,!0))h++,$h(y,$,p,{end:q});else if(tw(y)||Ca(y)){let _=y.readable||y;h++,$h(_,$,p,{end:q})}else throw new Qm("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=zA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(GA(O)){if(Hh(y)){h+=2;let $=f4(y,O,p,{end:q});ew(O)&&j&&s.push($)}else if(Ca(y)||tw(y)){let $=y.readable||y;h++,$h($,O,p,{end:q})}else if(cc(y))h++,$h(y,O,p,{end:q});else throw new cw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(o4(O)){if(Hh(y))h++,sw(ow(y),O,p,{end:q});else if(tw(y)||cc(y))h++,sw(y,O,p,{end:q});else if(Ca(y))h++,sw(y.readable,O,p,{end:q});else throw new cw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=WA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Ld.nextTick(c),y}function f4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new t4)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;s4(t)?Ld.nextTick(s):t.once("end",s)}else r();return Vh(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)}),Vh(e,{readable:!1,writable:!0},r)}JA.exports={pipelineImpl:YA,pipeline:d4}});var uw=oe((WF,rT)=>{"use strict";l();var{pipeline:l4}=qh(),Fh=oi(),{destroyer:h4}=nc(),{isNodeStream:jh,isReadable:ZA,isWritable:XA,isWebStream:aw,isTransformStream:ac,isWritableStream:QA,isReadableStream:eT}=ri(),{AbortError:p4,codes:{ERR_INVALID_ARG_VALUE:tT,ERR_MISSING_ARGS:y4}}=ir(),g4=Wi();rT.exports=function(...e){if(e.length===0)throw new y4("streams");if(e.length===1)return Fh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Fh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Fh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!jh(e[p])&&!aw(e[p]))){if(p<e.length-1&&!(ZA(e[p])||eT(e[p])||ac(e[p])))throw new tT(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(XA(e[p])||QA(e[p])||ac(e[p])))throw new tT(`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=l4(e,a),f=!!(XA(u)||QA(u)||ac(u)),h=!!(ZA(d)||eT(d)||ac(d));if(c=new Fh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(jh(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(aw(u)){let y=(ac(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=ac(d)?d.readable:d;g4(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(jh(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(aw(d)){let g=(ac(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 p4),o=null,n=null,i=null,s===null?g(p):(s=g,jh(d)&&h4(d,p))},c}});var lT=oe((zF,lw)=>{"use strict";l();var m4=globalThis.AbortController||Sa().AbortController,{codes:{ERR_INVALID_ARG_VALUE:w4,ERR_INVALID_ARG_TYPE:Pd,ERR_MISSING_ARGS:b4,ERR_OUT_OF_RANGE:x4},AbortError:si}=ir(),{validateAbortSignal:uc,validateInteger:nT,validateObject:dc}=Ta(),E4=nt().Symbol("kWeak"),v4=nt().Symbol("kResistStopPropagation"),{finished:S4}=Wi(),A4=uw(),{addAbortSignalNoValidate:T4}=Bd(),{isWritable:_4,isNodeStream:B4}=ri(),{deprecate:I4}=Zt(),{ArrayPrototypePush:R4,Boolean:U4,MathFloor:iT,Number:O4,NumberIsNaN:D4,Promise:oT,PromiseReject:sT,PromiseResolve:k4,PromisePrototypeThen:cT,Symbol:uT}=nt(),Wh=uT("kEmpty"),aT=uT("kEof");function N4(t,e){if(e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),B4(t)&&!_4(t))throw new w4("stream",t,"must be writable");let r=A4(this,t);return e!=null&&e.signal&&T4(e.signal,r),r}function Gh(t,e){if(typeof t!="function")throw new Pd("fn",["Function","AsyncFunction"],t);e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=iT(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=iT(e.highWaterMark)),nT(r,"options.concurrency",1),nT(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Zt().AbortSignalAny([e?.signal].filter(U4)),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===Wh)continue;S=k4(S)}catch(I){S=sT(I)}h+=1,cT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new oT(I=>{d=I})}c.push(aT)}catch(S){let I=sT(S);cT(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===aT)return;if(o.aborted)throw new si;S!==Wh&&(yield S),c.shift(),y()}await new oT(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function C4(t=void 0){return t!=null&&dc(t,"options"),t?.signal!=null&&uc(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 dT(t,e=void 0){for await(let r of fw.call(this,t,e))return!0;return!1}async function L4(t,e=void 0){if(typeof t!="function")throw new Pd("fn",["Function","AsyncFunction"],t);return!await dT.call(this,async(...r)=>!await t(...r),e)}async function P4(t,e){for await(let r of fw.call(this,t,e))return r}async function M4(t,e){if(typeof t!="function")throw new Pd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Wh}for await(let n of Gh.call(this,r,e));}function fw(t,e){if(typeof t!="function")throw new Pd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:Wh}return Gh.call(this,r,e)}var dw=class extends b4{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 Pd("reducer",["Function","AsyncFunction"],t);r!=null&&dc(r,"options"),r?.signal!=null&&uc(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 S4(this.destroy(u)),u}let o=new m4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[E4]:this,[v4]:!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 dw}finally{o.abort()}return e}async function $4(t){t!=null&&dc(t,"options"),t?.signal!=null&&uc(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});R4(e,n)}return e}function H4(t,e){let r=Gh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function fT(t){if(t=O4(t),D4(t))return 0;if(t<0)throw new x4("number",">= 0",t);return t}function V4(t,e=void 0){return e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),t=fT(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 q4(t,e=void 0){return e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),t=fT(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)}lw.exports.streamReturningOperators={asIndexedPairs:I4(C4,"readable.asIndexedPairs will be removed in a future version."),drop:V4,filter:fw,flatMap:H4,map:Gh,take:q4,compose:N4};lw.exports.promiseReturningOperators={every:L4,forEach:M4,reduce:K4,toArray:$4,some:dT,find:P4}});var hw=oe((JF,hT)=>{"use strict";l();var{ArrayPrototypePop:F4,Promise:j4}=nt(),{isIterable:W4,isNodeStream:G4,isWebStream:z4}=ri(),{pipelineImpl:Y4}=qh(),{finished:J4}=Wi();pw();function Z4(...t){return new j4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!G4(o)&&!W4(o)&&!z4(o)){let s=F4(t);n=s.signal,i=s.end}Y4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}hT.exports={finished:J4,pipeline:Z4}});var pw=oe((XF,vT)=>{l();var{Buffer:X4}=Ar(),{ObjectDefineProperty:Yi,ObjectKeys:gT,ReflectApply:mT}=nt(),{promisify:{custom:wT}}=Zt(),{streamReturningOperators:pT,promiseReturningOperators:yT}=lT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:bT}}=ir(),Q4=uw(),{setDefaultHighWaterMark:ek,getDefaultHighWaterMark:tk}=Id(),{pipeline:xT}=qh(),{destroyer:rk}=nc(),ET=Wi(),yw=hw(),Md=ri(),We=vT.exports=_h().Stream;We.isDestroyed=Md.isDestroyed;We.isDisturbed=Md.isDisturbed;We.isErrored=Md.isErrored;We.isReadable=Md.isReadable;We.isWritable=Md.isWritable;We.Readable=Od();for(let t of gT(pT)){let r=function(...n){if(new.target)throw bT();return We.Readable.from(mT(e,this,n))};gw=r;let e=pT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var gw;for(let t of gT(yT)){let r=function(...i){if(new.target)throw bT();return mT(e,this,i)};gw=r;let e=yT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var gw;We.Writable=Kh();We.Duplex=oi();We.Transform=Jm();We.PassThrough=Xm();We.pipeline=xT;var{addAbortSignal:nk}=Bd();We.addAbortSignal=nk;We.finished=ET;We.destroy=rk;We.compose=Q4;We.setDefaultHighWaterMark=ek;We.getDefaultHighWaterMark=tk;Yi(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return yw}});Yi(xT,wT,{__proto__:null,enumerable:!0,get(){return yw.pipeline}});Yi(ET,wT,{__proto__:null,enumerable:!0,get(){return yw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return X4.from(e.buffer,e.byteOffset,e.byteLength)}});var mw=oe((ej,lt)=>{"use strict";l();var At=pw(),ik=hw(),ok=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=ok;lt.exports.pipeline=At.pipeline;lt.exports.compose=At.compose;Object.defineProperty(At,"promises",{configurable:!0,enumerable:!0,get(){return ik}});lt.exports.Stream=At.Stream;lt.exports.default=lt.exports});var F_=oe((Cp,q_)=>{l();(function(t,e){typeof Cp=="object"&&typeof q_<"u"?e(Cp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Cp,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]",ve="[\\x20]",Ue=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),pt="[\\:\\/\\?\\#\\[\\]\\@]",Ee="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(pt,Ee),yt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=B?"[\\uE000-\\uF8FF]":"[]",Ae=e(v,K,"[\\-\\.\\_\\~]",yt),rt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(Ue+"|"+e(Ae,Ee,"[\\:]"))+"*"),ds=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),vr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Gr=r(vr+"\\."+vr+"\\."+vr+"\\."+vr),Ke=r(te+"{1,4}"),Sr=r(r(Ke+"\\:"+Ke)+"|"+Gr),zr=r(r(Ke+"\\:")+"{6}"+Sr),Ln=r("\\:\\:"+r(Ke+"\\:")+"{5}"+Sr),fs=r(r(Ke)+"?\\:\\:"+r(Ke+"\\:")+"{4}"+Sr),yi=r(r(r(Ke+"\\:")+"{0,1}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{3}"+Sr),pu=r(r(r(Ke+"\\:")+"{0,2}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{2}"+Sr),_f=r(r(r(Ke+"\\:")+"{0,3}"+Ke)+"?\\:\\:"+Ke+"\\:"+Sr),Bf=r(r(r(Ke+"\\:")+"{0,4}"+Ke)+"?\\:\\:"+Sr),Ac=r(r(r(Ke+"\\:")+"{0,5}"+Ke)+"?\\:\\:"+Ke),Tc=r(r(r(Ke+"\\:")+"{0,6}"+Ke)+"?\\:\\:"),gi=r([zr,Ln,fs,yi,pu,_f,Bf,Ac,Tc].join("|")),_c=r(r(Ae+"|"+Ue)+"+"),iy=r(gi+"\\%25"+_c),ls=r(gi+r("\\%25|\\%(?!"+te+"{2})")+_c),sI=r("[vV]"+te+"+\\."+e(Ae,Ee,"[\\:]")+"+"),cI=r("\\["+r(ls+"|"+gi+"|"+sI)+"\\]"),dx=r(r(Ue+"|"+e(Ae,Ee))+"*"),yu=r(cI+"|"+Gr+"(?!"+dx+")|"+dx),gu=r(K+"*"),fx=r(r(Ne+"@")+"?"+yu+r("\\:"+gu)+"?"),mu=r(Ue+"|"+e(Ae,Ee,"[\\:\\@]")),aI=r(mu+"*"),lx=r(mu+"+"),uI=r(r(Ue+"|"+e(Ae,Ee,"[\\@]"))+"+"),mi=r(r("\\/"+aI)+"*"),Bc=r("\\/"+r(lx+mi)+"?"),oy=r(uI+mi),If=r(lx+mi),Ic="(?!"+mu+")",BL=r(mi+"|"+Bc+"|"+oy+"|"+If+"|"+Ic),Rc=r(r(mu+"|"+e("[\\/\\?]",Ze))+"*"),wu=r(r(mu+"|[\\/\\?]")+"*"),hx=r(r("\\/\\/"+fx+mi)+"|"+Bc+"|"+If+"|"+Ic),dI=r(rt+"\\:"+hx+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),fI=r(r("\\/\\/"+fx+mi)+"|"+Bc+"|"+oy+"|"+Ic),lI=r(fI+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),IL=r(dI+"|"+lI),RL=r(rt+"\\:"+hx+r("\\?"+Rc)+"?"),UL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Bc+"|"+If+"|"+Ic+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",OL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Bc+"|"+oy+"|"+Ic+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",DL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Bc+"|"+If+"|"+Ic+")")+r("\\?("+Rc+")")+"?$",kL="^"+r("\\#("+wu+")")+"?$",NL="^"+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ae,Ee),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ae,Ee),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ae,Ee),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ae,Ee),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]",Ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ae,Ee),"g"),UNRESERVED:new RegExp(Ae,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ae,tt),"g"),PCT_ENCODED:new RegExp(Ue,"g"),IPV4ADDRESS:new RegExp("^("+Gr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+gi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+_c+")")+"?\\]?$")}}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 ve=v[Symbol.iterator](),Ue;!(H=(Ue=ve.next()).done)&&(K.push(Ue.value),!(k&&K.length===k));H=!0);}catch(pt){te=!0,fe=pt}finally{try{!H&&ve.return&&ve.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,ve=v.lastIndexOf(O);ve<0&&(ve=0);for(var Ue=0;Ue<ve;++Ue)v.charCodeAt(Ue)>=128&&G("not-basic"),k.push(v.charCodeAt(Ue));for(var pt=ve>0?ve+1:0;pt<K;){for(var Ee=H,tt=1,yt=p;;yt+=p){pt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(pt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Ae=yt<=fe?g:yt>=fe+y?y:yt-fe;if(Ze<Ae)break;var rt=p-Ae;tt>X(h/rt)&&G("overflow"),tt*=rt}var Ne=k.length+1;fe=R(H-Ee,Ne,Ee==0),X(H/Ne)>h-te&&G("overflow"),te+=X(H/Ne),H%=Ne,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,ve=!0,Ue=!1,pt=void 0;try{for(var Ee=v[Symbol.iterator](),tt;!(ve=(tt=Ee.next()).done);ve=!0){var yt=tt.value;yt<128&&k.push(Q(yt))}}catch(ls){Ue=!0,pt=ls}finally{try{!ve&&Ee.return&&Ee.return()}finally{if(Ue)throw pt}}var Ze=k.length,Ae=Ze;for(Ze&&k.push(O);Ae<K;){var rt=h,Ne=!0,ds=!1,vr=void 0;try{for(var Gr=v[Symbol.iterator](),Ke;!(Ne=(Ke=Gr.next()).done);Ne=!0){var Sr=Ke.value;Sr>=H&&Sr<rt&&(rt=Sr)}}catch(ls){ds=!0,vr=ls}finally{try{!Ne&&Gr.return&&Gr.return()}finally{if(ds)throw vr}}var zr=Ae+1;rt-H>X((h-te)/zr)&&G("overflow"),te+=(rt-H)*zr,H=rt;var Ln=!0,fs=!1,yi=void 0;try{for(var pu=v[Symbol.iterator](),_f;!(Ln=(_f=pu.next()).done);Ln=!0){var Bf=_f.value;if(Bf<H&&++te>h&&G("overflow"),Bf==H){for(var Ac=te,Tc=p;;Tc+=p){var gi=Tc<=fe?g:Tc>=fe+y?y:Tc-fe;if(Ac<gi)break;var _c=Ac-gi,iy=p-gi;k.push(Q(N(gi+_c%iy,0))),Ac=X(_c/iy)}k.push(Q(N(Ac,0))),fe=R(te,zr,Ae==Ze),te=0,++Ae}}}catch(ls){fs=!0,yi=ls}finally{try{!Ln&&pu.return&&pu.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),ve=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|ve&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 Re(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(),ve=d(fe,2),Ue=ve[0],pt=ve[1],Ee=pt?pt.split(":").map(ee):[],tt=Ue.split(":").map(ee),yt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=yt?7:8,Ae=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=Ee[Ne]||tt[Ae+Ne]||"";yt&&(rt[Ze-1]=ce(rt[Ze-1],v));var ds=rt.reduce(function(zr,Ln,fs){if(!Ln||Ln==="0"){var yi=zr[zr.length-1];yi&&yi.index+yi.length===fs?yi.length++:zr.push({index:fs,length:1})}return zr},[]),vr=ds.sort(function(zr,Ln){return Ln.length-zr.length})[0],Gr=void 0;if(vr&&vr.length>1){var Ke=rt.slice(0,vr.index),Sr=rt.slice(vr.index+vr.length);Gr=Ke.join(":")+"::"+Sr.join(":")}else Gr=rt.join(":");return te&&(Gr+="%"+te),Gr}else return B}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".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(Me);if(H){Je?(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=Re(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(Re(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 lo=/^\.\.?\//,du=/^\/\.(\/|$)/,xf=/^\/\.\.(\/|$)/,ty=/^\/?(?:.|\n)*?(?=\/|$)/;function ho(B){for(var v=[];B.length;)if(B.match(lo))B=B.replace(lo,"");else if(B.match(du))B=B.replace(du,"/");else if(B.match(xf))B=B.replace(xf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(ty);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 jr(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(ve){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+ve}}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=ho(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 fu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=wt(jr(B,k),k),v=wt(jr(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=ho(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=ho(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=ho(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=ho(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 Ef(B,v,k){var K=s({scheme:"null"},k);return jr(fu(wt(B,K),wt(v,K),K,!0),K)}function lu(B,v){return typeof B=="string"?B=jr(wt(B,v),v):n(B)==="object"&&(B=wt(jr(B,v),v)),B}function vf(B,v,k){return typeof B=="string"?B=jr(wt(B,k),k):n(B)==="object"&&(B=jr(B,k)),typeof v=="string"?v=jr(wt(v,k),k):n(v)==="object"&&(v=jr(v,k)),B===v}function Sf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function Wr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var po={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}},hu={scheme:"https",domainHost:po.domainHost,parse:po.parse,serialize:po.serialize};function Af(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=Af(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===(Af(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}},Tf={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},ry={},YB=!0,ox="[A-Za-z0-9\\-\\.\\_\\~"+(YB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",JB=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),ZB="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",XB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",QB=e(XB,'[\\"\\\\]'),eI="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",tI=new RegExp(ox,"g"),Sc=new RegExp(JB,"g"),rI=new RegExp(e("[^]",ZB,"[\\.]",'[\\"]',QB),"g"),sx=new RegExp(e("[^]",ox,eI),"g"),nI=sx;function ny(B){var v=Z(B);return v.match(tI)?v:B}var cx={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={},ve=K.query.split("&"),Ue=0,pt=ve.length;Ue<pt;++Ue){var Ee=ve[Ue].split("=");switch(Ee[0]){case"to":for(var tt=Ee[1].split(","),yt=0,Ze=tt.length;yt<Ze;++yt)H.push(tt[yt]);break;case"subject":K.subject=Wr(Ee[1],k);break;case"body":K.body=Wr(Ee[1],k);break;default:te=!0,fe[Wr(Ee[0],k)]=Wr(Ee[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Ae=0,rt=H.length;Ae<rt;++Ae){var Ne=H[Ae].split("@");if(Ne[0]=Wr(Ne[0]),k.unicodeSupport)Ne[1]=Wr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(Wr(Ne[1],k).toLowerCase())}catch(ds){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ds}H[Ae]=Ne.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 ve=String(H[te]),Ue=ve.lastIndexOf("@"),pt=ve.slice(0,Ue).replace(Sc,ny).replace(Sc,i).replace(rI,Y),Ee=ve.slice(Ue+1);try{Ee=k.iri?z.toUnicode(Ee):z.toASCII(Wr(Ee,k).toLowerCase())}catch(Ae){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ae}H[te]=pt+"@"+Ee}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var yt=[];for(var Ze in tt)tt[Ze]!==ry[Ze]&&yt.push(Ze.replace(Sc,ny).replace(Sc,i).replace(sx,Y)+"="+tt[Ze].replace(Sc,ny).replace(Sc,i).replace(nI,Y));return yt.length&&(K.query=yt.join("&")),K}},iI=/^([^\:]+)\:(.*)/,ax={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(iI),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),ve=K[2],Ue=te+":"+(k.nid||fe),pt=W[Ue];H.nid=fe,H.nss=ve,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 ve=v,Ue=v.nss;return ve.path=(H||k.nid)+":"+Ue,ve}},oI=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ux={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(oI))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[po.scheme]=po,W[hu.scheme]=hu,W[us.scheme]=us,W[Tf.scheme]=Tf,W[cx.scheme]=cx,W[ax.scheme]=ax,W[ux.scheme]=ux,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=wt,t.removeDotSegments=ho,t.serialize=jr,t.resolveComponents=fu,t.resolve=Ef,t.normalize=lu,t.equal=vf,t.escapeComponent=Sf,t.unescapeComponent=Wr,Object.defineProperty(t,"__esModule",{value:!0})})});var W_=oe((_Z,j_)=>{"use strict";l();j_.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 oB=oe((RQ,iB)=>{l();var tu=1e3,ru=tu*60,nu=ru*60,mc=nu*24,$C=mc*7,HC=mc*365.25;iB.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return VC(t);if(r==="number"&&isFinite(t))return e.long?FC(t):qC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function VC(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*HC;case"weeks":case"week":case"w":return r*$C;case"days":case"day":case"d":return r*mc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*nu;case"minutes":case"minute":case"mins":case"min":case"m":return r*ru;case"seconds":case"second":case"secs":case"sec":case"s":return r*tu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function qC(t){var e=Math.abs(t);return e>=mc?Math.round(t/mc)+"d":e>=nu?Math.round(t/nu)+"h":e>=ru?Math.round(t/ru)+"m":e>=tu?Math.round(t/tu)+"s":t+"ms"}function FC(t){var e=Math.abs(t);return e>=mc?$p(t,e,mc,"day"):e>=nu?$p(t,e,nu,"hour"):e>=ru?$p(t,e,ru,"minute"):e>=tu?$p(t,e,tu,"second"):t+" ms"}function $p(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var _L={};bu(_L,{AggregateBeaconError:()=>R0,Appendix:()=>Er,BECH32M_CHARS:()=>EL,BTCR2_DID_DOCUMENT_CONTEXT:()=>jB,BeaconError:()=>zt,BeaconFactory:()=>Cs,BeaconSignalDiscovery:()=>Xb,BeaconUtils:()=>Vr,CASBeacon:()=>Gu,CASBeaconError:()=>U0,CHANGE_OUTPUT_VBYTES:()=>C0,DEFAULT_FEE_ESTIMATOR:()=>Ol,DID_REGEX:()=>WB,DUST_LIMIT_SATS:()=>L0,DidBtcr2:()=>wf,DidDocument:()=>Fr,DidDocumentBuilder:()=>ix,DidVerificationMethod:()=>Qp,GenesisDocument:()=>ey,ID_PLACEHOLDER_VALUE:()=>qr,Identifier:()=>ur,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>vc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Ec,P2PKH_BEACON_TX_VSIZE:()=>Iv,P2TR_BEACON_TX_VSIZE:()=>_v,P2WPKH_BEACON_TX_VSIZE:()=>Bv,Resolver:()=>fo,SINGLETON_BEACON_TX_VSIZE:()=>Rv,SMTBeacon:()=>td,SMTBeaconError:()=>ta,SPENDABLE_DUST_LIMIT_SATS:()=>Dl,SinglePartyBeacon:()=>Ni,SingletonBeacon:()=>zu,SingletonBeaconError:()=>I0,StaticFeeEstimator:()=>ra,Updater:()=>mf,beaconTxVsize:()=>P0,buildAggregationBeaconTx:()=>JR,deriveSingletonAddress:()=>Uv,detectSingletonScriptKind:()=>M0,extractOpReturnSignal:()=>Zb,getAggregationCommunicationKey:()=>zB,isMultikeyVerificationMethod:()=>GB,opReturnScript:()=>$0,resolveBtcr2SenderPk:()=>TL,resolveChangeAddress:()=>K0,selectSpendableUtxo:()=>Dv});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 xu(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 Nf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xu(t.outputLen),xu(t.blockLen)}function Nc(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 Lx(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 Cf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function yn(t,e){return t<<32-e|t>>>e}function Eu(t,e){return t<<e|t>>>32-e>>>0}var Px=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",XI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ct(t){if(pn(t),Px)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=XI[t[r]];return e}var vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cx(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 Tr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Px)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=Cx(t.charCodeAt(o)),c=Cx(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 vu(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 kc=class{};function Lf(t){let e=n=>t().update(vu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function _r(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 QI(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 my(t,e,r){return t&e^~t&r}function wy(t,e,r){return t&e^t&r^e&r}var Cc=class extends kc{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=Cf(this.buffer)}update(e){Nc(this),e=vu(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=Cf(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){Nc(this),Lx(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;QI(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Cf(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 e8=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]),yo=new Uint32Array(64),by=class extends Cc{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)yo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=yo[f-15],p=yo[f-2],g=yn(h,7)^yn(h,18)^h>>>3,y=yn(p,17)^yn(p,19)^p>>>10;yo[f]=y+yo[f-7]+g+yo[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+my(c,a,u)+e8[f]+yo[f]|0,y=(yn(n,2)^yn(n,13)^yn(n,22))+wy(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(yo)}destroy(){this.set(0,0,0,0,0,0,0,0),Vn(this.buffer)}};var De=Lf(()=>new by);l();l();l();var Pf=class extends kc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Nf(e);let n=vu(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 Nc(this),this.iHash.update(e),this}digestInto(e){Nc(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()}},xy=(t,e,r)=>new Pf(t,e).update(r).digest();xy.create=(t,e)=>new Pf(t,e);l();var Sy=BigInt(0),vy=BigInt(1);function Su(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function go(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 Au(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Mx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Sy:BigInt("0x"+t)}function Ai(t){return Mx(Ct(t))}function Ay(t){return pn(t),Mx(Ct(Uint8Array.from(t).reverse()))}function Lc(t,e){return Tr(t.toString(16).padStart(e*2,"0"))}function Ty(t,e){return Lc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=Tr(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 Tu(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 Ey=t=>typeof t=="bigint"&&Sy<=t;function _u(t,e,r){return Ey(t)&&Ey(e)&&Ey(r)&&e<=t&&t<r}function Kx(t,e,r,n){if(!_u(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mf(t){let e;for(e=0;t>Sy;t>>=vy,e+=1);return e}var mo=t=>(vy<<BigInt(t))-vy;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 Bu(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 _y(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 tr=BigInt(0),qt=BigInt(1),bs=BigInt(2),qx=BigInt(3),Fx=BigInt(4),jx=BigInt(5),t8=BigInt(7),Wx=BigInt(8),r8=BigInt(9),Gx=BigInt(16);function Br(t,e){let r=t%e;return r>=tr?r:e+r}function Ir(t,e,r){let n=t;for(;e-- >tr;)n*=n,n%=r;return n}function Hx(t,e){if(t===tr)throw new Error("invert: expected non-zero number");if(e<=tr)throw new Error("invert: expected positive modulus, got "+e);let r=Br(t,e),n=e,i=tr,o=qt,s=qt,c=tr;for(;r!==tr;){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 Br(i,e)}function By(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function zx(t,e){let r=(t.ORDER+qt)/Fx,n=t.pow(e,r);return By(t,n,e),n}function n8(t,e){let r=(t.ORDER-jx)/Wx,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 By(t,c,e),c}function i8(t){let e=wo(t),r=Yx(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+t8)/Gx;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 By(c,E,a),E}}function Yx(t){if(t<qx)throw new Error("sqrt is not defined for small field");let e=t-qt,r=0;for(;e%bs===tr;)e/=bs,r++;let n=bs,i=wo(t);for(;Vx(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return zx;let o=i.pow(n,e),s=(e+qt)/bs;return function(a,u){if(a.is0(u))return u;if(Vx(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 o8(t){return t%Fx===qx?zx:t%Wx===jx?n8:t%Gx===r8?i8(t):Yx(t)}var s8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Iy(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=s8.reduce((n,i)=>(n[i]="function",n),e);return Bu(t,r),t}function c8(t,e,r){if(r<tr)throw new Error("invalid exponent, negatives unsupported");if(r===tr)return t.ONE;if(r===qt)return e;let n=t.ONE,i=e;for(;r>tr;)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 Vx(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 $f(t,e){e!==void 0&&xu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function wo(t,e,r=!1,n={}){if(t<=tr)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}=$f(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:mo(a),ZERO:tr,ONE:qt,allowedLengths:c,create:h=>Br(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return tr<=h&&h<t},is0:h=>h===tr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&qt)===qt,neg:h=>Br(-h,t),eql:(h,p)=>h===p,sqr:h=>Br(h*h,t),add:(h,p)=>Br(h+p,t),sub:(h,p)=>Br(h-p,t),mul:(h,p)=>Br(h*p,t),pow:(h,p)=>c8(f,h,p),div:(h,p)=>Br(h*Hx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Hx(h,t),sqrt:o||(h=>(d||(d=o8(t)),d(f,h))),toBytes:h=>r?Ty(h,u):Lc(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?Ay(h):Ai(h);if(s&&(g=Br(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 Jx(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 Ry(t){let e=Jx(t);return e+Math.ceil(e/2)}function Hf(t,e,r=!1){let n=t.length,i=Jx(e),o=Ry(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Ay(t):Ai(t),c=Br(s,e-qt)+qt;return r?Ty(c,i):Lc(c,i)}var Pc=BigInt(0),xs=BigInt(1);function Iu(t,e){let r=e.negate();return t?r:e}function qf(t,e){let r=Kf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function eE(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Uy(t,e){eE(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=mo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Zx(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 a8(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 u8(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 Oy=new WeakMap,tE=new WeakMap;function Dy(t){return tE.get(t)||1}function Xx(t){if(t!==Pc)throw new Error("invalid wNAF")}var Vf=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>Pc;)r&xs&&(n=n.add(i)),i=i.double(),r>>=xs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Uy(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=Uy(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Zx(n,c,s);n=a,d?o=o.add(Iu(h,r[p])):i=i.add(Iu(f,r[u]))}return Xx(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Uy(e,this.bits);for(let s=0;s<o.windows&&n!==Pc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Zx(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return Xx(n),i}getPrecomputes(e,r,n){let i=Oy.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Oy.set(r,i))),i}cached(e,r,n){let i=Dy(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Dy(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){eE(r,this.bits),tE.set(e,r),Oy.delete(e)}hasCache(e){return Dy(e)!==1}};function rE(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Pc||n>Pc;)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 nE(t,e,r,n){a8(r,t),u8(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=Mf(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=mo(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 Qx(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Iy(e),e}else return wo(t,{isLE:r})}function iE(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>Pc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=Qx(e.p,r.Fp,n),o=Qx(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 oE=(t,e)=>(t+(t>=0?e:-e)/sE)/e;function d8(t,e,r){let[[n,i],[o,s]]=e,c=oE(s*t,r),a=oE(-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=mo(Math.ceil(Mf(r)/2))+Mc;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 Ny(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ky(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Su(r.lowS,"lowS"),Su(r.prehash,"prehash"),r.format!==void 0&&Ny(r.format),r}var Cy=class extends Error{constructor(e=""){super(e)}},Ti={Err:Cy,_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=Au(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Au(i.length/2|128):"";return Au(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=Au(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),Mc=BigInt(1),sE=BigInt(2),Ff=BigInt(3),f8=BigInt(4);function bo(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 l8(t,e={}){let r=iE("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Bu(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=aE(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(Su(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ut(cE(N),L)}else return ut(Uint8Array.of(4),L,n.toBytes(U))}function h(G){go(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,Ff),f8),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 d8(G,a.basises,i.ORDER)}let M=_y((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=_y(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),_=Iu(x,_),D=Iu(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(go(_,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(Ff),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,Ff),{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,Ff),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=>qf($,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 qf($,[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(_===Mc)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}=rE($,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===Mc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Mc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Su(_,"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 qf($,_)}static msm(_,D){return nE($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(bo(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 Vf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function cE(t){return Uint8Array.of(t?2:3)}function aE(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function h8(t,e={}){let{Fn:r}=t,n=e.randomBytes||_r,i=Object.assign(aE(t.Fp,r),{seed:Ry(r.ORDER)});function o(p){try{return!!bo(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 Hf(go(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(bo(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=bo(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=>bo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function p8(t,e,r={}){Nf(e),Bu(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_r,i=r.hmac||((D,...x)=>xy(e,D,ut(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=h8(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>>Mc;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){Ny(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return go(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(go(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(Tr(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*sE<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(cE((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(Ny(x),x==="der")return Tr(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=mo(a);function q(D){return Kx("num < 2^"+a,D,_i,M),s.toBytes(D)}function j(D,x){return go(D,void 0,"message"),x?go(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}=ky(U,g);D=j(D,N);let C=T(D),P=bo(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 Re=s.create(ue*s.create(z+ce*P));if(Re===_i)return;let Me=(ee.x===ce?0:2)|Number(ee.y&Mc),Je=Re;return L&&E(Re)&&(Je=s.neg(Re),Me^=1),new A(ce,Je,Me)}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}=ky(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}=ky(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 y8(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=wo(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 g8(t){let{CURVE:e,curveOpts:r}=y8(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 m8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,$f(r.Fn.ORDER,r.Fn.BITS))})}function uE(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=g8(t),o=l8(e,r),s=p8(o,n,i);return m8(t,s)}function dE(t,e){let r=n=>uE({...t,hash:n});return{...r(e),create:r}}var Kc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},w8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},b8=BigInt(0),fE=BigInt(1),Ly=BigInt(2);function x8(t){let e=Kc.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=Ir(d,r,e)*d%e,h=Ir(f,r,e)*d%e,p=Ir(h,Ly,e)*u%e,g=Ir(p,i,e)*p%e,y=Ir(g,o,e)*g%e,E=Ir(y,c,e)*y%e,S=Ir(E,a,e)*E%e,I=Ir(S,c,e)*y%e,A=Ir(I,r,e)*d%e,O=Ir(A,s,e)*g%e,T=Ir(O,n,e)*u%e,M=Ir(T,Ly,e);if(!jf.eql(jf.sqr(M),t))throw new Error("Cannot find square root");return M}var jf=wo(Kc.p,{sqrt:x8}),xo=dE({...Kc,Fp:jf,lowS:!0,endo:w8},De),lE={};function Wf(t,...e){let r=lE[t];if(r===void 0){let n=De(ws(t));r=ut(n,n),lE[t]=r}return De(ut(r,...e))}var My=t=>t.toBytes(!0).slice(1),$c=xo.Point,Ky=t=>t%Ly===b8;function Py(t){let{Fn:e,BASE:r}=$c,n=bo(e,t),i=r.multiply(n);return{scalar:Ky(i.y)?n:e.neg(n),bytes:My(i)}}function pE(t){let e=jf;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);Ky(i)||(i=e.neg(i));let o=$c.fromAffine({x:t,y:i});return o.assertValidity(),o}var Ru=Ai;function yE(...t){return $c.Fn.create(Ru(Wf("BIP0340/challenge",...t)))}function hE(t){return Py(t).bytes}function E8(t,e,r=_r(32)){let{Fn:n}=$c,i=ot("message",t),{bytes:o,scalar:s}=Py(e),c=ot("auxRand",r,32),a=n.toBytes(s^Ru(Wf("BIP0340/aux",c))),u=Wf("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Py(u),h=yE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!gE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function gE(t,e,r){let{Fn:n,BASE:i}=$c,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=pE(Ru(c)),u=Ru(o.subarray(0,32));if(!_u(u,fE,Kc.p))return!1;let d=Ru(o.subarray(32,64));if(!_u(d,fE,Kc.n))return!1;let f=yE(n.toBytes(u),My(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Ky(g)||p!==u)}catch{return!1}}var Rr=(()=>{let r=(i=_r(48))=>Hf(i,Kc.n);xo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:hE(o)}}return{keygen:n,getPublicKey:hE,sign:E8,verify:gE,Point:$c,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Wf,lift_x:pE,pointToBytes:My,numberToBytesBE:Lc,bytesToNumberBE:Ai,mod:Br},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var v8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),wE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),S8=wE.map(t=>(9*t+5)%16),bE=(()=>{let r=[[wE],[S8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>v8[o]));return r})(),xE=bE[0],EE=bE[1],vE=[[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)),A8=xE.map((t,e)=>t.map(r=>vE[e][r])),T8=EE.map((t,e)=>t.map(r=>vE[e][r])),_8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),B8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function mE(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 Gf=new Uint32Array(16),$y=class extends Cc{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)Gf[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=_8[p],E=B8[p],S=xE[p],I=EE[p],A=A8[p],O=T8[p];for(let T=0;T<16;T++){let M=Eu(n+mE(p,o,c,u)+Gf[S[T]]+y,A[T])+f|0;n=f,f=u,u=Eu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=Eu(i+mE(g,s,a,d)+Gf[I[T]]+E,O[T])+h|0;i=h,h=d,d=Eu(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(Gf)}destroy(){this.destroyed=!0,Vn(this.buffer),this.set(0,0,0,0,0)}},SE=Lf(()=>new $y);l();l();function Hc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function I8(t,...e){if(!Hc(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 IE(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 qy(t){if(typeof t!="function")throw new Error("function expected");return!0}function Vc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Ou(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Yf(t){if(!Array.isArray(t))throw new Error("array expected")}function RE(t,e){if(!IE(!0,e))throw new Error(`${t}: array of strings expected`)}function Fy(t,e){if(!IE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Du(...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 Zf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;RE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Yf(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=>(Yf(i),i.map(o=>{Vc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Xf(t=""){return Vc("join",t),{encode:e=>(RE("join.decode",e),e.join(t)),decode:e=>(Vc("join.decode",e),e.split(t))}}function R8(t){return qy(t),{encode:e=>e,decode:e=>t(e)}}function AE(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(Yf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Ou(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 UE=(t,e)=>e===0?t:UE(e,t%e),Jf=(t,e)=>t+(e-UE(t,e)),zf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Hy(t,e,r,n){if(Yf(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(Jf(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Jf(e,r)}`);let i=0,o=0,s=zf[e],c=zf[r]-1,a=[];for(let u of t){if(Ou(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=zf[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 U8(t){Ou(t);let e=2**8;return{encode:r=>{if(!Hc(r))throw new Error("radix.encode input should be Uint8Array");return AE(Array.from(r),e,t)},decode:r=>(Fy("radix.decode",r),Uint8Array.from(AE(r,t,e)))}}function jy(t,e=!1){if(Ou(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Jf(8,t)>32||Jf(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Hc(r))throw new Error("radix2.encode input should be Uint8Array");return Hy(Array.from(r),8,t,!e)},decode:r=>(Fy("radix2.decode",r),Uint8Array.from(Hy(r,t,8,e)))}}function TE(t){return qy(t),function(...e){try{return t.apply(null,e)}catch{}}}function O8(t,e){return Ou(t),qy(e),{encode(r){if(!Hc(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(!Hc(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 qc=Du(jy(6),Zf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Xf("")),D8=t=>Du(U8(58),Zf(t),Xf("")),Qf=D8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var OE=t=>Du(O8(4,e=>t(t(e))),Qf);var Vy=Du(Zf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Xf("")),_E=[996825010,642813549,513874426,1027748829,705979059];function Uu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<_E.length;n++)(e>>n&1)===1&&(r^=_E[n]);return r}function BE(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=Uu(i)^s>>5}i=Uu(i);for(let o=0;o<n;o++)i=Uu(i)^t.charCodeAt(o)&31;for(let o of e)i=Uu(i)^o;for(let o=0;o<6;o++)i=Uu(i);return i^=r,Vy.encode(Hy([i%zf[30]],30,5,!1))}function DE(t){let e=t==="bech32"?1:734539939,r=jy(5),n=r.decode,i=r.encode,o=TE(n);function s(f,h,p=90){Vc("bech32.encode prefix",f),Hc(h)&&(h=Array.from(h)),Fy("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=BE(E,h,e);return`${E}1${Vy.encode(h)}${S}`}function c(f,h=90){Vc("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=Vy.decode(S).slice(0,-6),A=BE(E,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:E,words:I}}let a=TE(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 el=DE("bech32"),Fc=DE("bech32m"),kE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},k8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",N8={encode(t){return I8(t),t.toHex()},decode(t){return Vc("hex",t),Uint8Array.fromHex(t)}},Te=k8?N8:Du(jy(4),Zf("0123456789abcdef"),Xf(""),R8(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 He=new Uint8Array,Yy=new Uint8Array([0]);function jc(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 Jr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function C8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Jr(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 Wc(t){return Object.prototype.toString.call(t)==="[object Object]"}function qn(t){return Number.isSafeInteger(t)}var tl={equalBytes:jc,isBytes:Jr,isCoder:Ur,checkBounds:CE,concatBytes:C8,createView:Jy,isPlainObject:Wc},NE=t=>{if(t!==null&&typeof t!="string"&&!Ur(t)&&!Jr(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(Ur(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(Ur(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}},Wy=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: ${Te.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})[${Te.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: ${Te.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(!Jr(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(jc(e,this.data.subarray(n,n+e.length)))return n}}},Gy=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++)}}},zy=t=>Uint8Array.from(t).reverse();function CE(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 LE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Gy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Wy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function Ft(t,e){if(!Ur(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return LE({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=LE(t);return t.validate?Ft(e,t.validate):e},rl=t=>Wc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Ur(t){return Wc(t)&&rl(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||qn(t.size))}function L8(){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(!Wc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var P8={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 M8(t){if(!Wc(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 K8(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 $8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!rl(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 PE=t=>{if(!rl(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Ii={dict:L8,numberBigint:P8,tsEnum:M8,decimal:K8,match:$8,reverse:PE};var Zy=(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:zy(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 CE(s,8n*i,!!r),s}})};var ME=Zy(32,!1);var Gc=Zy(8,!0);var KE=Zy(8,!0,!0);var H8=(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}}),ku=(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 H8(t,{write:r.write,read:r.read,validate:e?o:c})},_e=ku(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),$E=ku(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),Eo=ku(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Xy=ku(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var mn=ku(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var qe=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=NE(t),n=Jr(t);return jt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?zy(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?zy(o):o},validate:i=>{if(!Jr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function HE(t,e){if(!Ur(e))throw new Error(`prefix: invalid inner value ${e}`);return gn(qe(t),PE(e))}var nl=(t,e=!1)=>Ft(gn(qe(t,e),kE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var VE=(t,e={isLE:!1,with0x:!1})=>{let r=gn(qe(t,e.isLE),Te),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(!Ur(t))throw new Error(`apply: invalid inner value ${t}`);if(!rl(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 qE=(t,e=!1)=>{if(!Jr(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=jc(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 FE(t,e,r){if(!Ur(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Ur(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 il(t,e,r=!0){if(!Ur(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||Jr(e)&&!jc(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 jE(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(!Wc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Ur(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return jt({size:jE(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 WE(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(!Ur(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return jt({size:jE(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(!Ur(e))throw new Error(`array: invalid inner value ${e}`);let r=NE(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=>{Jr(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),Jr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(jc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Jr(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(Jr(t))for(let s=0;;s++){if(jc(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 cl=xo.ProjectivePoint,sl=xo.CURVE.n,Ce=tl.isBytes,Fn=tl.concatBytes,st=tl.equalBytes;var zc=t=>SE(De(t)),Ri=(...t)=>De(De(Fn(...t))),eM=Rr.utils.randomPrivateKey,al=Rr.getPublicKey,Qy=xo.getPublicKey,GE=t=>t.r<sl/2n;function zE(t,e,r=!1){let n=xo.sign(t,e);if(r&&!GE(n)){let i=new Uint8Array(32),o=0;for(;!GE(n);)if(i.set(_e.encode(o++)),n=xo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var e0=Rr.sign,Nu=Rr.utils.taggedHash,xt;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(xt||(xt={}));function vo(t,e){let r=t.length;if(e===xt.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return cl.fromHex(t),t}else if(e===xt.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Rr.utils.lift_x(Rr.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function YE(t,e){let r=Rr.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=sl)throw new Error("tweak higher than curve order");return i}function JE(t,e=Uint8Array.of()){let r=Rr.utils,n=r.bytesToNumberBE(t),i=cl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,sl),s=r.pointToBytes(i),c=YE(s,e);return r.numberToBytesBE(r.mod(o+c,sl),32)}function Cu(t,e){let r=Rr.utils,n=YE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(cl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var ul=De(cl.BASE.toRawBytes(!1)),Zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},t0={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function Lu(t,e){if(!Ce(t)||!Ce(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 r0(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 QE(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=r0(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Xe=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=r0().encode(BigInt(r))),!Ce(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(Xy.encode(n))):(t.byte(gt.PUSHDATA4),t.bytes(_e.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=Xy.decodeStream(t);else if(r===gt.PUSHDATA4)n=_e.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}}),XE={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Yc=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(XE))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]=XE[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}}),Or=gn(Yc,Ii.numberBigint),fr=qe(Yc),Jc=Wt(Or,fr),dl=t=>Wt(Yc,t),ev=bt({txid:qe(32,!0),index:_e,finalScriptSig:fr,sequence:_e}),Ui=bt({amount:Gc,script:fr}),V8=bt({version:Eo,segwitFlag:qE(new Uint8Array([0,1])),inputs:dl(ev),outputs:dl(Ui),witnesses:FE("segwitFlag",Wt("inputs/length",Jc)),lockTime:_e});function q8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Oi=Ft(V8,q8),Es=bt({version:Eo,inputs:dl(ev),outputs:dl(Ui),lockTime:_e});var i0=Ft(qe(null),t=>vo(t,xt.ecdsa)),fl=Ft(qe(32),t=>vo(t,xt.schnorr)),tv=Ft(qe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),ll=bt({fingerprint:$E,path:Wt(null,_e)}),iv=bt({hashes:Wt(Or,qe(32)),der:ll}),F8=qe(78),j8=bt({pubKey:fl,leafHash:qe(32)}),W8=bt({version:mn,internalKey:qe(32),merklePath:Wt(null,qe(32))}),Di=Ft(W8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),G8=Wt(null,bt({depth:mn,version:mn,script:fr})),Et=qe(null),rv=qe(20),Pu=qe(32),hl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,F8,ll,[],[0,2],!1],txVersion:[2,!1,_e,[2],[2],!1],fallbackLocktime:[3,!1,_e,[],[2],!1],inputCount:[4,!1,Or,[2],[2],!1],outputCount:[5,!1,Or,[2],[2],!1],txModifiable:[6,!1,mn,[],[2],!1],version:[251,!1,_e,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},Mu={nonWitnessUtxo:[0,!1,Oi,[],[0,2],!1],witnessUtxo:[1,!1,Ui,[],[0,2],!1],partialSig:[2,i0,Et,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,Et,[],[0,2],!1],witnessScript:[5,!1,Et,[],[0,2],!1],bip32Derivation:[6,i0,ll,[],[0,2],!1],finalScriptSig:[7,!1,Et,[],[0,2],!1],finalScriptWitness:[8,!1,Jc,[],[0,2],!1],porCommitment:[9,!1,Et,[],[0,2],!1],ripemd160:[10,rv,Et,[],[0,2],!1],sha256:[11,Pu,Et,[],[0,2],!1],hash160:[12,rv,Et,[],[0,2],!1],hash256:[13,Pu,Et,[],[0,2],!1],txid:[14,!1,Pu,[2],[2],!0],index:[15,!1,_e,[2],[2],!0],sequence:[16,!1,_e,[],[2],!0],requiredTimeLocktime:[17,!1,_e,[],[2],!1],requiredHeightLocktime:[18,!1,_e,[],[2],!1],tapKeySig:[19,!1,tv,[],[0,2],!1],tapScriptSig:[20,j8,tv,[],[0,2],!1],tapLeafScript:[21,Di,Et,[],[0,2],!1],tapBip32Derivation:[22,Pu,iv,[],[0,2],!1],tapInternalKey:[23,!1,fl,[],[0,2],!1],tapMerkleRoot:[24,!1,Pu,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},ov=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],sv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Ku={redeemScript:[0,!1,Et,[],[0,2],!1],witnessScript:[1,!1,Et,[],[0,2],!1],bip32Derivation:[2,i0,ll,[],[0,2],!1],amount:[3,!1,KE,[2],[2],!0],script:[4,!1,Et,[2],[2],!0],tapInternalKey:[5,!1,fl,[],[0,2],!1],tapTree:[6,!1,G8,[],[0,2],!1],tapBip32Derivation:[7,fl,iv,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},cv=[],nv=Wt(Yy,bt({key:HE(Or,bt({type:Or,key:qe(null)})),value:qe(Or)}));function o0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var aM=bt({type:Or,key:qe(null)});function s0(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:He},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>Lu(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)=>Lu(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}nv.encodeStream(r,i)},decodeStream:r=>{let n=nv.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=${Te.encode(a)} value=${Te.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 pl=Ft(s0(Mu),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)vo(e,xt.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(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}),yl=Ft(s0(Ku),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,xt.ecdsa);return t}),av=Ft(s0(hl),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}),z8=bt({magic:il(nl(new Uint8Array([255])),"psbt"),global:av,inputs:Wt("global/unsignedTx/inputs/length",pl),outputs:Wt(null,yl)}),Y8=bt({magic:il(nl(new Uint8Array([255])),"psbt"),global:av,inputs:Wt("global/inputCount",pl),outputs:Wt("global/outputCount",yl)}),uM=bt({magic:il(nl(new Uint8Array([255])),"psbt"),items:Wt(null,gn(Wt(Yy,WE([VE(Or),qe(Yc)])),Ii.dict()))});function n0(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=o0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=o0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function c0(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}=o0(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 uv(t){let e=t&&t.global&&t.global.version||0;n0(e,hl,t.global);for(let s of t.inputs)n0(e,Mu,s);for(let s of t.outputs)n0(e,Ku,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 gl(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(Te.decode(E[0])):E[0],typeof E[1]=="string"?d.decode(Te.decode(E[1])):E[1]]});let g={},y=(E,S,I)=>{if(g[E]===void 0){g[E]=[S,I];return}let A=Te.encode(d.encode(g[E][1])),O=Te.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=Te.encode(u.encode(E));y(I,E,S)}for(let[E,S]of p){let I=Te.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(Te.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 a0=Ft(z8,uv),u0=Ft(Y8,uv);var Z8={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||Te.encode(t[1])!=="4e73"))return{type:"p2a",script:Xe.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,Te.decode("4e73")]}};function So(t,e){try{return vo(t,e),!0}catch{return!1}}var X8={encode(t){if(!(t.length!==2||!Ce(t[0])||!So(t[0],xt.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},Q8={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!Ce(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},eR={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!Ce(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},tR={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},rR={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},nR={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(!Ce(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},iR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},oR={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(!Ce(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}},sR={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=QE(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(!Ce(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}},cR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},aR=[Z8,X8,Q8,eR,tR,rR,nR,iR,oR,sR,cR],uR=gn(Xe,Ii.match(aR)),Qe=Ft(uR,t=>{if(t.type==="pk"&&!So(t.pubkey,xt.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!Ce(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!Ce(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!Ce(t.pubkey)||!So(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(!So(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(!So(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 dv(t,e){if(!st(t.hash,De(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Qe.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 y0(t,e,r){if(t){let n=Qe.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,zc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Qe.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&&dv(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&dv(n,r)}}var ki=(t,e=Zr)=>{if(!So(t,xt.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=zc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Xr(e).encode({type:"pkh",hash:r}),hash:r}};var vs=(t,e=Zr)=>{if(!So(t,xt.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=zc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Xr(e).encode({type:"wpkh",hash:r}),hash:r}};function dR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=gn(Xe,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,ul))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 lv(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 f0(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:f0(t.left,[t.right.hash,...e]),right:f0(t.right,[t.left.hash,...e])}}function l0(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[...l0(t.left),...l0(t.right)]}function h0(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,He))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?Te.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return dR(d,e,r,n),{type:"leaf",version:a,script:d,hash:$u(d,a)}}if(t.length!==2&&(t=lv(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=h0(t[0],e,r,n),o=h0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return Lu(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Nu("TapBranch",s,c)}}var p0=192,$u=(t,e=p0)=>Nu("TapLeaf",new Uint8Array([e]),fr.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"?Te.decode(t):t||ul;if(!So(o,xt.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=f0(h0(e,o,n,i)),c=s.hash,[a,u]=Cu(o,c),d=l0(s).map(f=>({...f,controlBlock:Di.encode({version:(f.version||p0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Xr(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||p0]))]),tapMerkleRoot:c}}else{let s=Cu(o,He)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Xr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var hv=OE(De);function pv(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 d0(t,e,r=Zr){pv(t,e);let n=t===0?el:Fc;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function fv(t,e){return hv.encode(Fn(Uint8Array.from(e),t))}function Xr(t=Zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return d0(0,e.hash,t);if(r==="wsh")return d0(0,e.hash,t);if(r==="tr")return d0(1,e.pubkey,t);if(r==="pkh")return fv(e.hash,[t.pubKeyHash]);if(r==="sh")return fv(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=el.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Fc.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=el.fromWords(o);if(pv(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=hv.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 ml=new Uint8Array(32),fR={amount:0xffffffffffffffffn,script:He},lR=t=>Math.ceil(t/4),hR=8,pR=2,As=0,b0=4294967295,yR=Ii.decimal(hR),Vu=(t,e)=>t===void 0?e:t;function bl(t){if(Array.isArray(t))return t.map(e=>bl(e));if(Ce(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,bl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var Fe;(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"})(Fe||(Fe={}));var Ao;(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"})(Ao||(Ao={}));function gR(t,e,r,n=He){return st(r,e)&&(t=JE(t,n),e=al(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 Hu(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:Vu(t.sequence,b0),finalScriptSig:Vu(t.finalScriptSig,He)}}function g0(t){for(let e in t){let r=e;ov.includes(r)||delete t[r]}}var m0=bt({txid:qe(32,!0),index:_e});function mR(t){if(typeof t!="number"||typeof Ao[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function yv(t){let e=t&31;return{isAny:!!(t&Fe.ANYONECANPAY),isNone:e===Fe.NONE,isSingle:e===Fe.SINGLE}}function wR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Vu(t.version,pR),lockTime:Vu(t.lockTime,0),PSBTVersion:Vu(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(_e.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 gv(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=Te.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function wl(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 mv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=Te.decode(o)),Ce(o)&&(o=Oi.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=Te.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=b0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=gl(Mu,c,e,r,i),pl.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&y0(a&&a.script,c.redeemScript,c.witnessScript),c}function w0(t,e=!1){let r="legacy",n=Fe.ALL,i=wl(t),o=Qe.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=Fe.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=Qe.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=Qe.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=Qe.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=wR(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=a0.decode(e)}catch(f){try{n=u0.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)=>gv({finalScriptSig:He,...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=>gv(c0(e,Mu,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=>c0(e,Ku,o)),i={...this.global};return e===0?(i.unsignedTx=Es.decode(Es.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Hu).map(o=>({...o,finalScriptSig:He})),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?a0:u0).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?Fe.DEFAULT:r,i=n===Fe.DEFAULT?Fe.ALL:n&3;return{sigInputs:n&Fe.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===Fe.ANYONECANPAY?n.push(o):e=!1,a===Fe.ALL)r=!1;else if(a===Fe.SINGLE)i.push(o);else if(a!==Fe.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*Or.encode(this.outputs.length).length;for(let n of r)e+=32+4*fr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Or.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*fr.encode(n.finalScriptSig||He).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Jc.encode(n.finalScriptWitness).length);return e}get vsize(){return lR(this.weight)}toBytes(e=!1,r=!1){return Oi.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Hu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||He})),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 Te.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Ri(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.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),bl(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(mv(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=sv)}this.inputs[e]=mv(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),bl(this.outputs[e])}getOutputAddress(e,r=Zr){let n=this.getOutput(e);if(n.script)return Xr(r).encode(Qe.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=Te.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=gl(Ku,s,r,n,this.opts.allowUnknown),yl.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Qe.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||y0(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=cv)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=Zr){return this.addOutput({script:Qe.encode(Xr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=wl(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}=yv(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 ME.encode(1n);r=Xe.encode(Xe.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Hu).map((d,f)=>({...d,finalScriptSig:f===e?r:He}));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(fR).concat([a[e]]));let u=Oi.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ri(u,Eo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=yv(n),a=ml,u=ml,d=ml,f=this.inputs.map(Hu),h=this.outputs.map(Ts);o||(a=Ri(...f.map(m0.encode))),!o&&!c&&!s&&(u=Ri(...f.map(g=>_e.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(Eo.encode(this.version),a,u,qe(32,!0).encode(p.txid),_e.encode(p.index),fr.encode(r),Gc.encode(i),_e.encode(p.sequence),d,_e.encode(this.lockTime),_e.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),Eo.encode(this.version),_e.encode(this.lockTime)],d=n===Fe.DEFAULT?Fe.ALL:n&3,f=n&Fe.ANYONECANPAY,h=this.inputs.map(Hu),p=this.outputs.map(Ts);f!==Fe.ANYONECANPAY&&u.push(...[h.map(m0.encode),i.map(Gc.encode),r.map(fr.encode),h.map(y=>_e.encode(y.sequence))].map(y=>De(Fn(...y)))),d===Fe.ALL&&u.push(De(Fn(...p.map(Ui.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===Fe.ANYONECANPAY){let y=h[e];u.push(m0.encode(y),Gc.encode(i[e]),fr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(De(fr.encode(a||He))),d===Fe.SINGLE&&u.push(e<p.length?De(Ui.encode(p[e])):ml),s&&u.push($u(s,c),mn.encode(0),Eo.encode(o)),Nu("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=w0(o,this.opts.allowLegacyWitnessUtxo);if(!Ce(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(mR):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===Fe.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=wl(o);if(s.txType==="taproot"){let d=this.inputs.map(wl),f=d.map(E=>E.script),h=d.map(E=>E.amount),p=!1,g=al(e),y=o.tapMerkleRoot||He;if(o.tapInternalKey){let{pubKey:E,privKey:S}=gR(e,g,o.tapInternalKey,y),[I,A]=Cu(o.tapInternalKey,y);if(st(I,E)){let O=this.preimageWitnessV1(r,f,c,h),T=Fn(e0(O,S,i),c!==Fe.DEFAULT?new Uint8Array([c]):He);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=Xe.decode(I),O=S[S.length-1],T=$u(I,O);if(A.findIndex($=>Ce($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Fn(e0(q,e,i),c!==Fe.DEFAULT?new Uint8Array([c]):He);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=Qy(e),f=!1,h=zc(d);for(let y of Xe.decode(s.lastScript))Ce(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=Qe.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=zE(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=w0(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=Qe.decode(f),g=$u(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(He);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=Xe.decode(f);if(E=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>Ce(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=Xe.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=He,g0(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=He,g0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=He,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=Xe.encode([0,...d])}else if(n.last.type==="pk")i=Xe.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Xe.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=He,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=Xe.decode(i).map(a=>{if(a===0)return He;if(Ce(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=Xe.encode([Xe.encode([0,De(n.lastScript)])]):n.type.startsWith("sh-")?s=Xe.encode([...Xe.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),g0(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):He,n=e.global.unsignedTx?Es.encode(e.global.unsignedTx):He;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=gl(hl,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 wv(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 bv(t,e){return wv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var x0;(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"})(x0||(x0={}));var{INVALID_DID:Lt,METHOD_NOT_SUPPORTED:xl,INTERNAL_ERROR:xv,INVALID_DID_DOCUMENT:Oe,INVALID_DID_UPDATE:ke,INVALID_DID_URL:XM,INVALID_PREVIOUS_DID_PROOF:QM,INVALID_PUBLIC_KEY:eK,INVALID_PUBLIC_KEY_MULTIBASE:tK,INVALID_PUBLIC_KEY_LENGTH:rK,INVALID_PUBLIC_KEY_TYPE:nK,INVALID_SIGNATURE:iK,PROOF_VERIFICATION_ERROR:Wn,PROOF_GENERATION_ERROR:_o,PROOF_SERIALIZATION_ERROR:Ev,PROOF_PARSING_ERROR:oK,VERIFICATION_METHOD_ERROR:El,LATE_PUBLISHING_ERROR:vl,INVALID_SIDECAR_DATA:sK,MISSING_UPDATE_DATA:cK,MISSING_RESOLUTION_OPTIONS:aK}=x0,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)}},xe=class extends Gt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var 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})}},je=class extends Gt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var Ve=class extends Gt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},To=class extends Gt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},Qr=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 bR=new Set(["jcs"]),xR=new Set(["hex","base58","base64urlnopad"]);function E0(t){let e=t.toLowerCase();if(!bR.has(e))throw new Zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function v0(t){let e=t.toLowerCase();if(!xR.has(e))throw new Zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function rr(t,e="jcs"){switch(E0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return bv(n)}default:throw new Zc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function Bo(t){return De(t)}function en(t,e="base64urlnopad"){switch(v0(e)){case"hex":return Te.encode(t);case"base58":return Qf.encode(t);case"base64urlnopad":return qc.encode(t)}}function Is(t,e="base64urlnopad"){switch(v0(e)){case"hex":return Te.decode(t);case"base58":return Qf.decode(t);case"base64urlnopad":return qc.decode(t)}}function Xc(t,e="jcs"){return Bo(rr(t,E0(e)))}function Gn(t,e){let r=E0(e?.algorithm??"jcs"),n=v0(e?.encoding??"base64urlnopad");return en(Bo(rr(t,r)),n)}l();l();var S0={};bu(S0,{JsonPatchError:()=>ct,_areEquals:()=>ju,applyOperation:()=>Rs,applyPatch:()=>Rl,applyReducer:()=>TR,deepClone:()=>SR,getValueByPointer:()=>Bl,validate:()=>Sv,validator:()=>Il});l();l();var ER=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)}}(),vR=Object.prototype.hasOwnProperty;function Al(t,e){return vR.call(t,e)}function Tl(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)Al(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 _l(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 qu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Sl(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Sl(t[e]))return!0}else if(typeof t=="object"){for(var n=Tl(t),i=n.length,o=0;o<i;o++)if(Sl(t[n[o]]))return!0}}return!1}function vv(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 Fu=function(t){ER(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,vv(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=vv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=Fu,SR=Pt,Qc={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=Bl(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=Bl(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:ju(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},AR={add:function(t,e,r){return _l(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:Qc.move,copy:Qc.copy,test:Qc.test,_get:Qc._get};function Bl(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):Il(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=Bl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=ju(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=Il;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=qu(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&&!_l(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);_l(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=AR[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=Qc[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 Rl(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 TR(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 Il(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(Qc[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")&&Sl(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=Sv([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 Sv(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Rl(Pt(e),Pt(t),r||!0);else{r=r||Il;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 ju(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(!ju(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],!ju(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var B0={};bu(B0,{compare:()=>kR,generate:()=>A0,observe:()=>DR,unobserve:()=>OR});l();var T0=new WeakMap,_R=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),BR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function IR(t){return T0.get(t)}function RR(t,e){return t.observers.get(e)}function UR(t,e){t.observers.delete(e.callback)}function OR(t,e){e.unobserve()}function DR(t,e){var r=[],n,i=IR(t);if(!i)i=new _R(t),T0.set(t,i);else{var o=RR(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(){A0(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(){A0(n),clearTimeout(n.next),UR(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 BR(e,n)),n}function A0(t,e){e===void 0&&(e=!1);var r=T0.get(t.object);_0(r.value,t.object,t.patches,"",e),t.patches.length&&Rl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function _0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Tl(e),s=Tl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(Al(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)?_0(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];!Al(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+zn(d),value:Pt(e[d])})}}}function kR(t,e,r){r===void 0&&(r=!1);var n=[];return _0(t,e,n,"",r),n}var Av=Object.assign({},S0,B0,{JsonPatchError:Fu,deepClone:Pt,escapePathComponent:zn,unescapePathComponent:qu});var{applyPatch:NR,compare:CR,deepClone:LR}=Av,ea=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??LR,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new xe("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=NR(s,r,!1,i);if(a.newDocument===void 0)throw new xe("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new xe("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=CR(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 xe("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let r of e){if(!r||typeof r!="object")return new xe("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof r.op!="string")return new xe("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof r.path!="string")return new xe("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new xe(`Operation.from must be a string for op=${r.op}`,"JSON_PATCH_VALIDATION_ERROR")}return null}};l();var Io;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(Io||(Io={}));var Ul;(function(t){t.k="k",t.x="x"})(Ul||(Ul={}));var Wu;(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"})(Wu||(Wu={}));l();var Ro=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new xe(`Invalid date: ${e}`,"INVALID_DATE");return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new xe(`Invalid date: ${e}`,"INVALID_DATE");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 xe("Maximum comparison depth exceeded","MAX_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 xe("Maximum clone depth exceeded","MAX_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 xe("Cannot clone circular structure","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 zt=class extends xe{constructor(e,r="BeaconError",n){super(e,r,n)}},I0=class extends xe{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},R0=class extends xe{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},U0=class extends xe{constructor(e,r="CASBeaconError",n){super(e,r,n)}},ta=class extends xe{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 WR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Uo(t){switch(t){case"bitcoin":return Zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return t0;case"regtest":return WR;default:throw new Error(`Unknown network "${t}"`)}}l();var ra=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 D0="0000000000000000000000000000000000000000000000000000000000000000",k0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var N0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(N0||(N0={}));var Ol=new ra(5);var _v=160,Bv=155,Iv=240,Rv={p2pkh:Iv,p2wpkh:Bv,p2tr:_v},C0={p2pkh:34,p2wpkh:31,p2tr:43},L0={p2pkh:546,p2wpkh:294,p2tr:330};function P0(t,e){return Rv[t]-C0[t]+C0[e]}function M0(t,e){let r=Xr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new zt(`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 Uv(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 K0(t,e,r){if(!r||r===t)return t;try{Xr(e).decode(r)}catch{throw new zt(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Ov(t,e){try{return M0(t,e)}catch{return"p2tr"}}function $0(t){return Xe.encode(["RETURN",t])}var Dl=546;function YR(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 Dv(t,e){if(!t.length)throw new zt("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>Dl);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 ${Dl}-sat dust limit`;throw new zt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:Dl})}return[...n].sort(YR)[0]}async function kv(t,e){let r=await e.rest.address.getUtxos(t),n=Dv(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Tr(i)}}async function JR(t){let e=t.feeEstimator??Ol,{utxo:r,prevTxBytes:n}=await kv(t.beaconAddress,t.bitcoin),i=K0(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Xr(t.network).decode(t.beaconAddress)),s=Ov(i,t.network),c=await e.estimateFee(P0("p2tr",s));if(BigInt(r.value)<=c)throw new zt(`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(L0[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:$0(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 ZR(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=Ao.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=Qe.decode(i);if(u.type!=="wpkh")throw new zt(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Qe.encode({type:"pkh",hash:u.hash}),f=Ao.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],Ao.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ni=class{service;constructor(e){this.service=e}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??Ol,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await kv(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=M0(e.beaconAddress,r),o=K0(e.beaconAddress,r,e.changeAddress),s=Uv(i,n,r);if(s!==e.beaconAddress)throw new zt(`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=Ov(o,r),a=await e.feeEstimator.estimateFee(P0(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new zt(`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(L0[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:$0(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 ZR(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Gu=class extends Ni{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=en(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=Bo(rr(c));i?.casPublish&&await i.casPublish(c);let u=await this.buildSignAndBroadcast(a,r,n,i);return{signedUpdate:e,txid:u,announcement:c}}};l();l();var zu=class extends Ni{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=Bo(rr(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var XR=new Uint8Array(32),H0=1n<<BigInt(256),Nv=(()=>{let t=new Array(257),e=H0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Yu(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 Se(t,e,r=""){let n=Yu(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 kl(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 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 Lv(t,e){Se(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 Nl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function xn(t,e){return t<<32-e|t>>>e}var Pv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",QR=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ds(t){if(Se(t),Pv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=QR[t[r]];return e}var Ci={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cv(t){if(t>=Ci._0&&t<=Ci._9)return t-Ci._0;if(t>=Ci.A&&t<=Ci.F)return t-(Ci.A-10);if(t>=Ci.a&&t<=Ci.f)return t-(Ci.a-10)}function ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Pv)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=Cv(t.charCodeAt(o)),c=Cv(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 lr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Se(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 Mv(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 Kv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var q0=BigInt(0),V0=BigInt(1);function Ju(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function $v(t){if(typeof t=="bigint"){if(!Cl(t))throw new Error("positive bigint expected, got "+t)}else Yn(t);return t}function Zu(t){let e=$v(t).toString(16);return e.length&1?"0"+e:e}function Hv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?q0:BigInt("0x"+t)}function Oo(t){return Hv(Ds(t))}function F0(t){return Hv(Ds(e6(Se(t)).reverse()))}function Ll(t,e){Yn(e),t=$v(t);let r=ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function j0(t,e){return Ll(t,e).reverse()}function ia(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 e6(t){return Uint8Array.from(t)}function Vv(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 Cl=t=>typeof t=="bigint"&&q0<=t;function t6(t,e,r){return Cl(t)&&Cl(e)&&Cl(r)&&e<=t&&t<r}function qv(t,e,r,n){if(!t6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function W0(t){let e;for(e=0;t>q0;t>>=V0,e+=1);return e}var Xu=t=>(V0<<BigInt(t))-V0;function Fv(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,lr(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 lr(...S)};return(E,S)=>{f(),p(E);let I;for(;!(I=S(g()));)p();return f(),I}}function Qu(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 G0(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 z0(t){return t.length===32}function Pl(t){if(!z0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function dt(...t){return De(ut(...t))}function ed(t){Pl(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function Y0(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 J0(t){Pl(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function Z0(t,e){return!z0(t)||!z0(e)?!1:ia(t,e)}function oa(t){return Pl(t),qc.encode(t)}function Jn(t){let e=qc.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var jv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(jv||(jv={}));l();l();var Do=256;function sa(t,e){return Number(t>>BigInt(e)&1n)}var Wv=(()=>{let t=new Array(Do+1),e=new Uint8Array(32);for(let r=0;r<=Do;r++)e=dt(e,e),t[r]=e;return t})();function Ml(t,e){if(t.length===0)return Wv[e];if(e===0)return t[0].leaf;let r=Do-e,n=[],i=[];for(let o of t)(sa(o.index,r)===0?n:i).push(o);return dt(Ml(n,e-1),Ml(i,e-1))}function Gv(t){return Ml(t,Do)}function zv(t,e){let r=0n,n=[];for(let i=1;i<=Do;i++){let o=Do-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(sa(c.index,u)!==sa(e,u)){a=!1;break}a&&sa(c.index,o)!==sa(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Ml(s,i-1))}return{collapsed:r,hashes:n}}function Yv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Do;c++){let a=Do-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Wv[c];else{if(s>=e.length)return!1;u=e[s++]}o=sa(r,a)===1?dt(u,o):dt(o,u)}return s===e.length&&Z0(o,i)}l();var r6=new TextEncoder;function Kl(t){return ed(dt(r6.encode(t)))}function Jv(t,e){return dt(dt(t),dt(e))}function Zv(t){return dt(dt(t))}l();function Xv(t,e,r){let n={id:oa(t),collapsed:oa(Y0(e.collapsed)),hashes:e.hashes.map(i=>oa(i))};return r?.nonce&&(n.nonce=oa(r.nonce)),r?.updateId&&(n.updateId=oa(r.updateId)),n}function n6(t){let e={rootHash:Jn(t.id),collapsed:ed(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}=n6(t);return Yv(i,o,e,r,n)}l();var $l=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=Kl(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?Jv(n.nonce,n.signedUpdate):Zv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=Gv(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=zv(this.#n,r),o=n.signedUpdate!==void 0?dt(n.signedUpdate):void 0;return Xv(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var td=class extends Ni{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 ta("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=Kl(o),u=Jn(c.nonce),d=c.updateId?dt(dt(u),Jn(c.updateId)):dt(dt(u));if(!Qv(c,a,d))throw new ta("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=J0(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(rr(e)),c=_r(32),a=new $l;a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize();let u=a.proof(o),d=await this.buildSignAndBroadcast(a.rootHash,r,n,i);return{signedUpdate:e,txid:d,proof:u}}};var Cs=class{static establish(e){switch(e.type){case"SingletonBeacon":return new zu(e);case"CASBeacon":return new Gu(e);case"SMTBeacon":return new td(e);default:throw new xe("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Pi;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Pi||(Pi={}));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 s6=Pn(t1(),1);l();l();l();l();var BH=new Uint8Array(0);function r1(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 ca(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 a6(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 u6=a6,d6=u6,n1=d6;var tg=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")}},rg=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 i1(this,e)}},ng=class{decoders;constructor(e){this.decoders=e}or(e){return i1(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 i1(t,e){return new ng({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var ig=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 tg(e,r,n),this.decoder=new rg(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function o1({name:t,prefix:e,encode:r,decode:n}){return new ig(t,e,r,n)}function og({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=n1(r,t);return o1({prefix:e,name:t,encode:n,decode:o=>ca(i(o))})}function f6(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 l6(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 o1({prefix:e,name:t,encode(i){return l6(i,n,r)},decode(i){return f6(i,n,r,t)}})}var rd=nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LH=nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),PH=nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MH=nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),KH=nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$H=nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),HH=nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),VH=nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sg=nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var hr=og({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),WH=og({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var JH=nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ZH=nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),XH=nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function s1(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function c1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function aa(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var nd=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())})},a1=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)}},Vl=new TextEncoder,Ls=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(!c1(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 hr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(aa(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return s1(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 nd(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 sg.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 hr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return hr.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=Vl.encode(e);return Zn.baseEncode(r)}case"String":{let e=Vl.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 nd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=a1(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=Ls.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Ls.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return nd(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 Ls.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Ls.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Ls.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return nd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=a1(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+=Ls.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+=Ls.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 sg.baseDecode(this.data);case"Base58Btc":return hr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=aa(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 Vl.encode(e)}case"String":return Vl.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return nd(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 id;(function(t){t.Debug="debug",t.Silent="silent"})(id||(id={}));var cg=class{constructor(){this.logLevel=id.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==id.Silent&&console.info(e)}error(e){this.logLevel!==id.Silent&&console.error(e)}},h6=new cg;typeof window<"u"&&(window.web5logger=h6);l();l();l();l();var Mi={};bu(Mi,{decode:()=>ua,encodeTo:()=>Ps,encodingLength:()=>Ms});l();l();var p6=f1,u1=128,y6=127,g6=~y6,m6=Math.pow(2,31);function f1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=m6;)e[r++]=t&255|u1,t/=128;for(;t&g6;)e[r++]=t&255|u1,t>>>=7;return e[r]=t|0,f1.bytes=r-n+1,e}var w6=ag,b6=128,d1=127;function ag(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw ag.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&d1)<<i:(s&d1)*Math.pow(2,i),i+=7}while(s>=b6);return ag.bytes=o-n,r}var x6=Math.pow(2,7),E6=Math.pow(2,14),v6=Math.pow(2,21),S6=Math.pow(2,28),A6=Math.pow(2,35),T6=Math.pow(2,42),_6=Math.pow(2,49),B6=Math.pow(2,56),I6=Math.pow(2,63),R6=function(t){return t<x6?1:t<E6?2:t<v6?3:t<S6?4:t<A6?5:t<T6?6:t<_6?7:t<B6?8:t<I6?9:10},U6={encode:p6,decode:w6,encodingLength:R6},O6=U6,od=O6;function ua(t,e=0){return[od.decode(t,e),od.decode.bytes]}function Ps(t,e,r=0){return od.encode(t,e,r),e}function Ms(t){return od.encodingLength(t)}function ug(t,e){let r=e.byteLength,n=Ms(t),i=n+Ms(r),o=new Uint8Array(i+r);return Ps(t,o,0),Ps(r,o,n),o.set(e,i),new da(t,r,e,o)}function l1(t){let e=ca(t),[r,n]=ua(e),[i,o]=ua(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new da(r,i,s,e)}function h1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&r1(t.bytes,r.bytes)}}var da=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function p1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return k6(r,fg(t),e??hr.encoder);default:return N6(r,fg(t),e??rd.encoder)}}var y1=new WeakMap;function fg(t){let e=y1.get(t);if(e==null){let r=new Map;return y1.set(t,r),r}return e}var lg=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!==sd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==C6)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=ug(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&&h1(e.multihash,n.multihash)}toString(e){return p1(this,e)}toJSON(){return{"/":p1(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??g1(n,i,o.bytes))}else if(r[L6]===!0){let{version:n,multihash:i,code:o}=r,s=l1(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!==sd)throw new Error(`Version 0 CID must use dag-pb (code: ${sd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=g1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,sd,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=ca(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 da(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]=ua(e.subarray(r));return r+=h,f},i=n(),o=sd;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]=D6(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 fg(o).set(n,e),o}};function D6(t,e){switch(t[0]){case"Q":{let r=e??hr;return[hr.prefix,r.decode(`${hr.prefix}${t}`)]}case hr.prefix:{let r=e??hr;return[hr.prefix,r.decode(t)]}case rd.prefix:{let r=e??rd;return[rd.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 k6(t,e,r){let{prefix:n}=r;if(n!==hr.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 N6(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 sd=112,C6=18;function g1(t,e,r){let n=Ms(t),i=n+Ms(e),o=new Uint8Array(i+r.byteLength);return Ps(t,o,0),Ps(e,o,n),o.set(r,i),o}var L6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Yt=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=Mi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Mi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Mi.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]=Mi.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}}};Yt.codeToName=new Map;Yt.nameToCode=new Map;Yt.registerCodec({code:237,name:"ed25519-pub"});Yt.registerCodec({code:4864,name:"ed25519-priv"});Yt.registerCodec({code:236,name:"x25519-pub"});Yt.registerCodec({code:4866,name:"x25519-priv"});Yt.registerCodec({code:231,name:"secp256k1-pub"});Yt.registerCodec({code:4865,name:"secp256k1-priv"});l();function hg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&hg(t[e])})}l();var qU=Pn(om(),1),Qs=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 gh=class{constructor(){this.store=new Map}clear(){return Qs(this,void 0,void 0,function*(){this.store.clear()})}close(){return Qs(this,void 0,void 0,function*(){})}delete(e){return Qs(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return Qs(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return Qs(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return Qs(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return Qs(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var sk=Pn(mw(),1);var ck=Pn(mw(),1);l();l();l();l();l();function ak(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function ww(t,...e){if(!ak(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 bw(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 ST(t,e){ww(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var La=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),_n=(t,e)=>t<<32-e|t>>>e;var Aj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function uk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function xw(t){return typeof t=="string"&&(t=uk(t)),ww(t),t}var zh=class{clone(){return this._cloneInto()}},Tj={}.toString;function AT(t){let e=n=>t().update(xw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function TT(t=32){if(La&&typeof La.getRandomValues=="function")return La.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 _T=(t,e,r)=>t&e^~t&r,BT=(t,e,r)=>t&e^t&r^e&r,Jh=class extends zh{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=Yh(this.buffer)}update(e){bw(this);let{view:r,buffer:n,blockLen:i}=this;e=xw(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=Yh(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){bw(this),ST(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=Yh(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=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]),jo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Wo=new Uint32Array(64),Ew=class extends Jh{constructor(){super(64,32,8,!1),this.A=jo[0]|0,this.B=jo[1]|0,this.C=jo[2]|0,this.D=jo[3]|0,this.E=jo[4]|0,this.F=jo[5]|0,this.G=jo[6]|0,this.H=jo[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)Wo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Wo[f-15],p=Wo[f-2],g=_n(h,7)^_n(h,18)^h>>>3,y=_n(p,17)^_n(p,19)^p>>>10;Wo[f]=y+Wo[f-7]+g+Wo[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+_T(c,a,u)+fk[f]+Wo[f]|0,y=(_n(n,2)^_n(n,13)^_n(n,22))+BT(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(){Wo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Go=AT(()=>new Ew);var lk=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())})},Pa=class{static digest(e){return lk(this,arguments,void 0,function*({data:r}){return Go(r)})}};l();var ci=class{};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())})},Zh=class extends ci{digest(e){return hk(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Pa.digest({data:n})}})}};l();l();l();l();l();l();function IT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function pk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function vw(t,...e){if(!pk(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 RT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");IT(t.outputLen),IT(t.blockLen)}function Ma(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 UT(t,e){vw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Xh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function OT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Qh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,yk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!yk)throw new Error("Non little-endian hardware is not supported");function Sw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Kd(t){if(typeof t=="string"&&(t=Sw(t)),!OT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function ep(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!OT(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 Ka=class{clone(){return this._cloneInto()}},Jj={}.toString;function tp(t){let e=n=>t().update(Kd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function $d(t=32){if(Xh&&typeof Xh.getRandomValues=="function")return Xh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function gk(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 $a=class extends Ka{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){Ma(this);let{view:r,buffer:n,blockLen:i}=this;e=Kd(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){Ma(this),UT(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;gk(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 mk=(t,e,r)=>t&e^~t&r,wk=(t,e,r)=>t&e^t&r^e&r,bk=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]),zo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yo=new Uint32Array(64),Aw=class extends $a{constructor(){super(64,32,8,!1),this.A=zo[0]|0,this.B=zo[1]|0,this.C=zo[2]|0,this.D=zo[3]|0,this.E=zo[4]|0,this.F=zo[5]|0,this.G=zo[6]|0,this.H=zo[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)Yo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Yo[f-15],p=Yo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;Yo[f]=y+Yo[f-7]+g+Yo[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+mk(c,a,u)+bk[f]+Yo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+wk(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(){Yo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var rp=tp(()=>new Aw);l();var ip={};bu(ip,{bitGet:()=>_k,bitLen:()=>Tk,bitMask:()=>Hd,bitSet:()=>Bk,bytesToHex:()=>Zi,bytesToNumberBE:()=>Xi,bytesToNumberLE:()=>Rn,concatBytes:()=>eo,createHmacDrbg:()=>Bw,ensureBytes:()=>Ge,equalBytes:()=>Sk,hexToBytes:()=>fc,hexToNumber:()=>_w,isBytes:()=>In,numberToBytesBE:()=>yr,numberToBytesLE:()=>Qi,numberToHexUnpadded:()=>CT,numberToVarBytesBE:()=>vk,utf8ToBytes:()=>Ak,validateObject:()=>sn});l();var NT=BigInt(0),np=BigInt(1),xk=BigInt(2);function In(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Ek=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zi(t){if(!In(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Ek[t[r]];return e}function CT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function _w(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Ji={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function DT(t){if(t>=Ji._0&&t<=Ji._9)return t-Ji._0;if(t>=Ji._A&&t<=Ji._F)return t-(Ji._A-10);if(t>=Ji._a&&t<=Ji._f)return t-(Ji._a-10)}function fc(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=DT(t.charCodeAt(o)),c=DT(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 Xi(t){return _w(Zi(t))}function Rn(t){if(!In(t))throw new Error("Uint8Array expected");return _w(Zi(Uint8Array.from(t).reverse()))}function yr(t,e){return fc(t.toString(16).padStart(e*2,"0"))}function Qi(t,e){return yr(t,e).reverse()}function vk(t){return fc(CT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=fc(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 eo(...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 Sk(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 Ak(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Tk(t){let e;for(e=0;t>NT;t>>=np,e+=1);return e}function _k(t,e){return t>>BigInt(e)&np}var Bk=(t,e,r)=>t|(r?np:NT)<<BigInt(e),Hd=t=>(xk<<BigInt(t-1))-np,Tw=t=>new Uint8Array(t),kT=t=>Uint8Array.from(t);function Bw(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=Tw(t),i=Tw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=Tw())=>{i=c(kT([0]),f),n=c(),f.length!==0&&(i=c(kT([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 eo(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var Ik={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 sn(t,e,r={}){let n=(i,o,s)=>{let c=Ik[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),et=BigInt(1),lc=BigInt(2),Rk=BigInt(3),Iw=BigInt(4),LT=BigInt(5),PT=BigInt(8),Uk=BigInt(9),Ok=BigInt(16);function Be(t,e){let r=t%e;return r>=Tt?r:e+r}function Rw(t,e,r){if(r<=Tt||e<Tt)throw new Error("Expected power/modulo > 0");if(r===et)return Tt;let n=et;for(;e>Tt;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >Tt;)n*=n,n%=r;return n}function op(t,e){if(t===Tt||e<=Tt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Be(t,e),n=e,i=Tt,o=et,s=et,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!==et)throw new Error("invert: does not exist");return Be(i,e)}function Dk(t){let e=(t-et)/lc,r,n,i;for(r=t-et,n=0;r%lc===Tt;r/=lc,n++);for(i=lc;i<t&&Rw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/Iw;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+et)/lc;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,et<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function kk(t){if(t%Iw===Rk){let e=(t+et)/Iw;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%PT===LT){let e=(t-LT)/PT;return function(n,i){let o=n.mul(i,lc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,lc),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%Ok,Dk(t)}var MT=(t,e)=>(Be(t,e)&et)===et,Nk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Uw(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Nk.reduce((n,i)=>(n[i]="function",n),e);return sn(t,r)}function Ck(t,e,r){if(r<Tt)throw new Error("Expected power > 0");if(r===Tt)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>Tt;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function Lk(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 Ow(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ha(t,e,r=!1,n={}){if(t<=Tt)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=Ow(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=kk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Hd(i),ZERO:Tt,ONE:et,create:a=>Be(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&et)===et,neg:a=>Be(-a,t),eql:(a,u)=>a===u,sqr:a=>Be(a*a,t),add:(a,u)=>Be(a+u,t),sub:(a,u)=>Be(a-u,t),mul:(a,u)=>Be(a*u,t),pow:(a,u)=>Ck(c,a,u),div:(a,u)=>Be(a*op(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>op(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Lk(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Qi(a,o):yr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Rn(a):Xi(a)}});return Object.freeze(c)}function KT(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 $T(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 Dw(t){let e=$T(t);return e+Math.ceil(e/2)}function HT(t,e,r=!1){let n=t.length,i=$T(e),o=Dw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Xi(t):Rn(t),c=Be(s,e-et)+et;return r?Qi(c,i):yr(c,i)}l();l();var Mk=BigInt(0),kw=BigInt(1);function sp(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>Mk;)o&kw&&(s=s.add(c)),c=c.double(),o>>=kw;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+=kw);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 Vd(t){return Uw(t.Fp),sn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ow(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Kk(t){let e=Vd(t);sn(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:$k,hexToBytes:Hk}=ip,hc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=hc;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:$k(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=hc,r=typeof t=="string"?Hk(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}=hc._parseInt(r.subarray(2)),{d:s,l:c}=hc._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}`}},to=BigInt(0),cn=BigInt(1),mW=BigInt(2),VT=BigInt(3),wW=BigInt(4);function Vk(t){let e=Kk(t),{Fp:r}=e,n=e.toBytes||((g,y,E)=>{let S=y.toAffine();return eo(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"&&to<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=Zi(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:Xi(Ge("private key",g,E))}catch{throw new Error(`private key must be ${E} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Be(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(Ge("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,VT),{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,VT),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===to)return E;if(c(y),y===cn)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>to||T>to;)A&cn&&(M=M.add(j)),T&cn&&(q=q.add(j)),j=j.double(),A>>=cn,T>>=cn;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===to||M===cn||!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===cn)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===cn?this:E?E(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Zi(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=sp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function qk(t){let e=Vd(t);return sn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qT(t){let e=qk(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(x){return to<x&&x<r.ORDER}function c(x){return Be(x,n)}function a(x){return op(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Vk({...e,toBytes(x,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=eo;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=Xi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&cn)===cn;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=>Zi(yr(x,e.nByteLength));function g(x){let U=n>>cn;return x>U}function y(x){return g(x)?c(-x):x}let E=(x,U,L)=>Xi(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=Ge("compactSignature",U,L*2),new S(E(U,0,L),E(U,L,2*L))}static fromDER(U){let{r:L,s:N}=hc.toSig(Ge("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(Ge("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 fc(this.toDERHex())}toDERHex(){return hc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fc(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=Dw(e.n);return HT(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=Xi(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=Hd(e.nBitLength);function $(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(to<=x&&x<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return yr(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=Ge("msgHash",x),P&&(x=Ge("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(Ge("extraEntropy",ee))}let Y=eo(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Re=a(ce),Me=u.BASE.multiply(ce).toAffine(),Je=c(Me.x);if(Je===to)return;let wt=c(Re*c(Z+Je*z));if(wt===to)return;let pi=(Me.x===Je?0:2)|Number(Me.y&cn),lo=wt;return C&&g(wt)&&(lo=y(wt),pi^=1),new S(Je,lo,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 Bw(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=Ge("msgHash",U),L=Ge("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(Me){if(!(Me instanceof hc.Err))throw Me;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Me,s:Je}=R;V=new S(Me,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Me){if(Me.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 cp=class extends Ka{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,RT(e);let n=Kd(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 Ma(this),this.iHash.update(e),this}digestInto(e){Ma(this),vw(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()}},Nw=(t,e,r)=>new cp(t,e).update(r).digest();Nw.create=(t,e)=>new cp(t,e);function Fk(t){return{hash:t,hmac:(e,...r)=>Nw(t,e,ep(...r)),randomBytes:$d}}function ap(t,e){let r=n=>qT({...t,...Fk(n)});return Object.freeze({...r(e),create:r})}var WT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),FT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),jk=BigInt(1),Cw=BigInt(2),jT=(t,e)=>(t+e/Cw)/e;function Wk(t){let e=WT,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=ze(d,r,e)*d%e,h=ze(f,r,e)*d%e,p=ze(h,Cw,e)*u%e,g=ze(p,i,e)*p%e,y=ze(g,o,e)*g%e,E=ze(y,c,e)*y%e,S=ze(E,a,e)*E%e,I=ze(S,c,e)*y%e,A=ze(I,r,e)*d%e,O=ze(A,s,e)*g%e,T=ze(O,n,e)*u%e,M=ze(T,Cw,e);if(!Lw.eql(Lw.sqr(M),t))throw new Error("Cannot find square root");return M}var Lw=Ha(WT,void 0,void 0,{sqrt:Wk}),gr=ap({a:BigInt(0),b:BigInt(7),Fp:Lw,n:FT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=FT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-jk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=jT(o*t,e),a=jT(-n*t,e),u=Be(t-c*r-a*i,e),d=Be(-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}}}},rp),kW=BigInt(0);var NW=gr.ProjectivePoint;l();l();function GT(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 Gk=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())})},Pw="urn:jwk:";function ge(t){return Gk(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}`);hg(n);let i=GT(n),o=ne.string(i).toUint8Array(),s=yield Pa.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 Va(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 qa(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 zT(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())})},zk=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=gr.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 gr.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 gr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return gr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Kt(this,void 0,void 0,function*(){let e=gr.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=zk(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(!(Va(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 gr.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=Go(r);return gr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){return gr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){try{gr.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=Go(i);return gr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Kt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=gr.getPublicKey(r));let n=gr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y:o}})}};l();l();var YT=Ha(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Yk=YT.create(BigInt("-3")),Jk=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Zk=ap({a:Yk,b:Jk,Fp:YT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},rp),Cr=Zk;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())})},Xk=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=Cr.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 Cr.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 Cr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=Cr.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=Xk(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(!(Va(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 Cr.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=Go(r);return Cr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return Cr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{Cr.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=Go(i);return Cr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Cr.getPublicKey(r));let n=Cr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y:o}})}};var qd=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())})},Fd=class extends ci{computePublicKey(e){return qd(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 qd(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 qd(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 qd(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 qd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Va(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 up=BigInt(4294967295),Mw=BigInt(32);function JT(t,e=!1){return e?{h:Number(t&up),l:Number(t>>Mw&up)}:{h:Number(t>>Mw&up)|0,l:Number(t&up)|0}}function Qk(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}=JT(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var eN=(t,e)=>BigInt(t>>>0)<<Mw|BigInt(e>>>0),tN=(t,e,r)=>t>>>r,rN=(t,e,r)=>t<<32-r|e>>>r,nN=(t,e,r)=>t>>>r|e<<32-r,iN=(t,e,r)=>t<<32-r|e>>>r,oN=(t,e,r)=>t<<64-r|e>>>r-32,sN=(t,e,r)=>t>>>r-32|e<<64-r,cN=(t,e)=>e,aN=(t,e)=>t,uN=(t,e,r)=>t<<r|e>>>32-r,dN=(t,e,r)=>e<<r|t>>>32-r,fN=(t,e,r)=>e<<r-32|t>>>64-r,lN=(t,e,r)=>t<<r-32|e>>>64-r;function hN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var pN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),yN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,gN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),mN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,wN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),bN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var xN={fromBig:JT,split:Qk,toBig:eN,shrSH:tN,shrSL:rN,rotrSH:nN,rotrSL:iN,rotrBH:oN,rotrBL:sN,rotr32H:cN,rotr32L:aN,rotlSH:uN,rotlSL:dN,rotlBH:fN,rotlBL:lN,add:hN,add3L:pN,add3H:yN,add4L:gN,add4H:mN,add5H:bN,add5L:wN},le=xN;var[EN,vN]=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))),Jo=new Uint32Array(80),Zo=new Uint32Array(80),Kw=class extends $a{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)Jo[A]=e.getUint32(r),Zo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Jo[A-15]|0,T=Zo[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=Jo[A-2]|0,$=Zo[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,Zo[A-7],Zo[A-16]),_=le.add4H(G,M,X,Jo[A-7],Jo[A-16]);Jo[A]=_|0,Zo[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,vN[A],Zo[A]),$=le.add5H(j,S,O,M,EN[A],Jo[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(){Jo.fill(0),Zo.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 $w=tp(()=>new Kw);l();var Un=BigInt(0),Lr=BigInt(1),dp=BigInt(2),SN=BigInt(8),AN={zip215:!0};function TN(t){let e=Vd(t);return sn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function fp(t){let e=TN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=dp<<BigInt(c*8)-Lr,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,Lr,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)),Re=d(ue+d(C*d(W*Y)));if(ce!==Re)throw new Error("bad point: equation left != right (1)");let Me=d(P*V),Je=d(J*z);if(Me!==Je)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(dp*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Re=Y-z,Me=d(ue*ce),Je=d(ee*Re),wt=d(ue*Re),pi=d(ce*ee);return new T(Me,Je,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 fu=d((J-V)*(Z+Y)),Ef=d((J+V)*(Z-Y)),lu=d(Ef-fu);if(lu===Un)return this.double();let vf=d(z*dp*ee),Sf=d(W*dp*ue),Wr=Sf+vf,po=Ef+fu,hu=Sf-vf,Af=d(Wr*lu),us=d(po*hu),Tf=d(Wr*hu),ry=d(lu*po);return new T(Af,us,ry,Tf)}let ce=d(V*Y),Re=d(J*Z),Me=d(W*P*ee),Je=d(z*ue),wt=d((V+J)*(Y+Z)-ce-Re),pi=Je-Me,lo=Je+Me,du=d(Re-C*ce),xf=d(wt*pi),ty=d(lo*du),ho=d(wt*du),jr=d(pi*lo);return new T(xf,ty,jr,ho)}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===Lr?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?SN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Un,y:Lr};if(Y!==Lr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Lr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Ge("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-Lr),ee=d(P*Z-V),{isValid:ce,value:Re}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Re&Lr)===Lr,Je=(W&128)!==0;if(!C&&Re===Un&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Me&&(Re=d(-Re)),T.fromAffine({x:Re,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Qi(C,r.BYTES);return P[P.length-1]|=R&Lr?128:0,P}toHex(){return Zi(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Lr,d(e.Gx*e.Gy)),T.ZERO=new T(Un,Lr,Lr,Un);let{BASE:M,ZERO:q}=T,j=sp(T,c*8);function $(N){return Be(N,n)}function X(N){return $(Rn(N))}function Q(N){let R=c;N=Ge("private key",N,R);let C=Ge("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=eo(...R);return X(o(p(C,Ge("context",N),!!i)))}function D(N,R,C={}){N=Ge("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=eo(W,Qi(Z,r.BYTES));return Ge("result",ue,c*2)}let x=AN;function U(N,R,C,P=x){let{context:V,zip215:J}=P,z=r.BYTES;N=Ge("signature",N,2*z),R=Ge("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 jd=BigInt(0),Hw=BigInt(1);function _N(t){return sn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function ZT(t){let e=_N(t),{P:r}=e,n=A=>Be(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>Rw(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"&&jd<=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=Hw,$=jd,X=T,Q=Hw,G=jd,_;for(let x=BigInt(i-1);x>=jd;x--){let U=M>>x&Hw;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 Qi(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),Rn(O)}function y(A){let O=Ge("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===jd)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 Wd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),XT=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),LG=BigInt(0),BN=BigInt(1),Vw=BigInt(2),IN=BigInt(5),QT=BigInt(10),RN=BigInt(20),UN=BigInt(40),e_=BigInt(80);function t_(t){let e=Wd,n=t*t%e*t%e,i=ze(n,Vw,e)*n%e,o=ze(i,BN,e)*t%e,s=ze(o,IN,e)*o%e,c=ze(s,QT,e)*s%e,a=ze(c,RN,e)*c%e,u=ze(a,UN,e)*a%e,d=ze(u,e_,e)*u%e,f=ze(d,e_,e)*u%e,h=ze(f,QT,e)*s%e;return{pow_p_5_8:ze(h,Vw,e)*t%e,b2:n}}function r_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ON(t,e){let r=Wd,n=Be(e*e*e,r),i=Be(n*n*e,r),o=t_(t*i).pow_p_5_8,s=Be(t*n*o,r),c=Be(e*s*s,r),a=s,u=Be(s*XT,r),d=c===t,f=c===Be(-t,r),h=c===Be(-t*XT,r);return d&&(s=a),(f||h)&&(s=u),MT(s,r)&&(s=Be(-s,r)),{isValid:d||f,value:s}}var an=Ha(Wd,void 0,!0),Gd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:an,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:$w,randomBytes:$d,adjustScalarBytes:r_,uvRatio:ON},Xo=fp(Gd);function n_(t,e,r){if(e.length>255)throw new Error("Context is too big");return ep(Sw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var PG=fp({...Gd,domain:n_}),MG=fp({...Gd,domain:n_,prehash:$w}),pc=ZT({P:Wd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Wd,{pow_p_5_8:r,b2:n}=t_(t);return Be(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:r_,randomBytes:$d});function i_(t){let{y:e}=Xo.ExtendedPoint.fromHex(t),r=BigInt(1);return an.toBytes(an.create((r+e)*an.inv(r-e)))}function o_(t){let e=Gd.hash(t.subarray(0,32));return Gd.adjustScalarBytes(e).subarray(0,32)}var DN=(an.ORDER+BigInt(3))/BigInt(8),KG=an.pow(Vw,DN),$G=an.sqrt(an.neg(an.ONE)),HG=(an.ORDER-BigInt(5))/BigInt(8),VG=BigInt(486662);var qG=KT(an,an.neg(BigInt(486664)));var FG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),jG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),WG=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),GG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var zG=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var un=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())})},kN=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 un(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Xo.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 un(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 un(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Xo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return un(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=o_(n),o=pc.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 un(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=i_(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return un(this,void 0,void 0,function*(){let e=Xo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return un(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=kN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return un(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 un(this,arguments,void 0,function*({publicKey:r}){if(!qa(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 un(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Xo.sign(n,i)})}static validatePublicKey(e){return un(this,arguments,void 0,function*({publicKeyBytes:r}){try{Xo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return un(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Xo.verify(n,i,o)})}};var zd=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())})},lp=class extends ci{computePublicKey(e){return zd(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 zd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield _t.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return zd(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 zd(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 zd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!qa(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 ro=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())})},qw={Ed25519:{implementation:lp,names:["Ed25519"]},secp256k1:{implementation:Fd,names:["ES256K","secp256k1"]},secp256r1:{implementation:Fd,names:["ES256","secp256r1"]},"SHA-256":{implementation:Zh,names:["SHA-256"]}},Qt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new gh}digest(e){return ro(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return ro(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return ro(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=`${Pw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return ro(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Pw}${n}`})}getPublicKey(e){return ro(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 ro(this,arguments,void 0,function*({key:r}){var n;if(!zT(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 ro(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 ro(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=qw[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 qw){let o=qw[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 ro(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 hp=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 TT(e)}static randomUuid(){return La.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 Qo=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())})},NN=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},Fa=class t{static bytesToPrivateKey(e){return Qo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=pc.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 Qo(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 Qo(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=pc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return Qo(this,void 0,void 0,function*(){let e=pc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Qo(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=NN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Qo(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 Qo(this,arguments,void 0,function*({publicKey:r}){if(!qa(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 Qo(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 pc.getSharedSecret(i,o)})}};l();l();l();function Pr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Ww({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(jw))!==null&&r!==void 0?r:[]),Object.keys(Pi).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(jw))!==null&&s!==void 0?s:[])}),n}function s_({didDocument:t}){let r=Ww({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function c_({didDocument:t,methodId:e}){let r=[];return Object.keys(Pi).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Pr(e);i.some(c=>{let a=Pr(c)===o,u=jw(c)&&Pr(c.id)===o;return a||u})&&r.push(n)}}),r}function a_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function jw(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 Gw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Yt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function zw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=Yt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var Yd=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())})},mr=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 Yd(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 Yd(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 Pr(a.id)===((u=Pr(e?.methodId))!==null&&u!==void 0?u:Pr((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:hp.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return Yd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return Yd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return Yd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=Ww({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 Yw="0123456789abcdef",d_=[],u_=[];for(let t=0;t<256;t++)d_[t]=Yw[t>>4&15]+Yw[t&15],t<16&&(t<10?u_[48+t]=t:u_[87+t]=t);var Jw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=d_[t[n++]];return r};var f_=(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 l_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",LN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Jd=0;Jd<l_.length;Jd++)LN[l_.charCodeAt(Jd)]=Jd;var Jd;var PN=new TextDecoder,Zw=(t,e)=>e?new TextDecoder(e).decode(t):PN.decode(t),MN=new TextEncoder,dn=t=>MN.encode(t);var h_=typeof window<"u"?window:self,p_=h_.crypto||h_.msCrypto||{},zY=p_.subtle||p_.webkitSubtle;l();function ja(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function pp(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 Ie(t,e,r){let n=[],i=null;return Ie._encode(n,t),i=f_(n),Ie.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Ie.bytes=-1;Ie._floatConversionDetected=!1;Ie._encode=function(t,e){if(e!=null)switch(pp(e)){case"object":Ie.dict(t,e);break;case"map":Ie.dictMap(t,e);break;case"array":Ie.list(t,e);break;case"set":Ie.listSet(t,e);break;case"string":Ie.string(t,e);break;case"number":Ie.number(t,e);break;case"boolean":Ie.number(t,e);break;case"arraybufferview":Ie.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Ie.buffer(t,new Uint8Array(e));break}};var yp=new Uint8Array([101]),y_=new Uint8Array([100]),g_=new Uint8Array([108]);Ie.buffer=function(t,e){t.push(dn(e.length+":"),e)};Ie.string=function(t,e){t.push(dn(dn(e).byteLength+":"+e))};Ie.number=function(t,e){if(Number.isInteger(e))return t.push(dn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(dn("i"+o+"e")),o!==e&&!Ie._floatConversionDetected&&(Ie._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())};Ie.dict=function(t,e){t.push(y_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Ie.string(t,n),Ie._encode(t,e[n]));t.push(yp)};Ie.dictMap=function(t,e){t.push(y_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Ie._encode(t,n):Ie.string(t,String(n)),Ie._encode(t,e.get(n)));t.push(yp)};Ie.list=function(t,e){let r=0,n=e.length;for(t.push(g_);r<n;r++)e[r]!=null&&Ie._encode(t,e[r]);t.push(yp)};Ie.listSet=function(t,e){t.push(g_);for(let r of e)r!=null&&Ie._encode(t,r);t.push(yp)};var m_=Ie;l();var KN=105,$N=58,HN=100,VN=108,Xw=101;function w_(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)):dn(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 HN:return de.dictionary();case VN: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]!==Xw;){let e=de.buffer(),r=Zw(e);r.includes("\uFFFD")&&(r=Jw(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==Xw;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(Xw),e=w_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find($N),e=w_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?Zw(de.data.slice(t,r)):de.data.slice(t,r)};var b_=de;l();function qN(t){let e=2;for(let r of t)e+=gp(r);return e}function FN(t){let e=2;for(let[r,n]of t){let i=dn(r).byteLength;e+=ja(i)+1+i,e+=gp(n)}return e}function jN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=dn(r[n]).byteLength;e+=ja(i)+1+i,e+=gp(t[r[n]])}return e}function WN(t){let e=dn(t).byteLength;return ja(e)+1+e}function GN(t){let e=t.byteLength-t.byteOffset;return ja(e)+1+e}function gp(t){if(t==null)return 0;let r=pp(t);switch(r){case"arraybufferview":return GN(t);case"string":return WN(t);case"array":case"set":return qN(t);case"number":return 1+ja(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return jN(t);case"map":return FN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var Qw=gp;var zN=Qw,eb={encode:m_,decode:b_,byteLength:Qw,encodingLength:zN};l();l();var YN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var JN=/^(::)?(((\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=>YN.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]}`}},no={name:"v6",size:16,isFormat:t=>t.length>0&&JN.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 x_(t){if(On.isFormat(t))return On.size;if(no.isFormat(t))return no.size;throw Error(`Invalid ip address: ${t}`)}function E_(t){return x_(t)===On.size?1:2}function v_(t,e,r){r=~~r;let n=x_(t);return typeof e=="function"&&(e=e(r+n)),n===On.size?On.encode(t,e,r):no.encode(t,e,r)}function S_(t,e,r){if(e=~~e,r=r||t.length-e,r===On.size)return On.decode(t,e,r);if(r===no.size)return no.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${On.size} for v4 or ${no.size} for v6.`)}l();function Zd(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 Wa(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 A_(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 T_(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 tb(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 rb(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 __(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 nb(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 ib(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 Ga(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(ib(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 Ga.bytes=i-r,e}Ga.bytes=0;function za(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 za.bytes=r-e,n}za.bytes=0;var es=t=>t instanceof Uint8Array;function io(t){return typeof t=="string"?ib(t):t.byteLength}function mp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Ga(t)}function wp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Ga(e,t,r),Ga.bytes}var Xd={},B_=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}`;B_[s]=c,Xd[c]=s,Xd[`${r}${i}`]=s,Xd[`${e}${o}`]=s,Xd[`${r}${o}`]=s}}function I_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=B_[o]}return n}function ob(t){return t.length>>>1}function R_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=Xd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var iC=Math.pow(2,24),oC=Math.pow(2,16),sC=Math.pow(2,8),di=(t,e)=>t[e]*iC+t[e+1]*oC+t[e+2]*sC+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 wr(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:cC(t,e,r,n,i)}function cC(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 uC=0,U_=32768,cb=32768,dC=~cb,D_=32768,fC=~D_;function $e({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=$e({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=wp(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(za(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:io(t.replace(/^\.|\.$/gm,""))+2}}),Bt=$e({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=wp(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=za(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return io(t)+1}}),Ya=$e({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Ya.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?U_:uC;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&U_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:T_(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:A_(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}}),xp=$e({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),wr(t,e,r+2,0,n),xp.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 xp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),Ep=$e({encode(t,e,r){return e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Ep.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 Ep.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),vp=$e({encode(t,e,r){e||(e=new Uint8Array(vp.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),vp.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,vp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),Sp=$e({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=mp(t[i])),!es(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(Sp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,wr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),Sp.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 Sp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=io(r)+1:e+=r.length+1}),e}}),Ap=$e({encode(t,e,r){e||(e=new Uint8Array(Ap.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=mp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return wr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),Ap.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,Ap.decode.bytes=e-r,i},encodingLength(t){return t?(es(t)?t.length:io(t))+2:2}}),Tp=$e({encode(t,e,r){e||(e=new Uint8Array(Tp.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),Tp.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,Tp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),Xa=$e({encode(t,e,r){return e||(e=new Uint8Array(Xa.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Xa.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return Xa.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),_p=$e({encode(t,e,r){e||(e=new Uint8Array(_p.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),_p.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),_p.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),ts=$e({encode(t,e,r){let n=ts.encodingLength(t);return e||(e=new Uint8Array(ts.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=ts.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,wp(e,t.value,r),r+=io(t.value),ts.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=za(t,e,n+r),i.issuerCritical=!!(i.flags&ts.ISSUER_CRITICAL),ts.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});ts.ISSUER_CRITICAL=128;var Bp=$e({encode(t,e,r){e||(e=new Uint8Array(Bp.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),Bp.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,Bp.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),k_=$e({encode(t,e,r){return e||(e=new Uint8Array(k_.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}),Ip=$e({encode(t,e,r){return e||(e=new Uint8Array(Ip.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,no.encode(t,e,r),Ip.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=no.decode(t,e);return Ip.decode.bytes=18,r},bytes:18}),O_=t=>new Uint8Array(t),oo=$e({encode(t,e,r){e||(e=new Uint8Array(oo.encodingLength(t))),r||(r=0);let n=r,i=nb(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,wr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||E_(t.ip,O_),c=v_(t.ip,O_),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,wr(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 oo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=__(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);wr(t,i,0,e,e+n-4),r.ip=S_(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 oo.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(nb(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}`)}}),rs=$e({encode(t,e,r){e||(e=new Uint8Array(rs.encodingLength(t))),r||(r=0);let n=r,i=Za(t,oo);return ae(e,i,r),r=of(t,oo,e,r+2),rs.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++]=oo.decode(t,e),e+=oo.decode.bytes,i-=oo.decode.bytes;return rs.decode.bytes=e-r,n},encodingLength(t){return 2+Za(t||[],oo)}}),li=$e({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!es(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,wr(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+io(t.key)}});li.PROTOCOL_DNSSEC=3;li.ZONE_KEY=128;li.SECURE_ENTRYPOINT=32768;var Qd=$e({encode(t,e,r){e||(e=new Uint8Array(Qd.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!es(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Wa(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,wr(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.typeCovered=Zd(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,Qd.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+io(t.signature)}}),ef=$e({encode(t,e,r){e||(e=new Uint8Array(ef.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,ef.encode.bytes=r-n,ae(e,ef.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,ef.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Mr=$e({encode(t,e,r){e||(e=new Uint8Array(Mr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Wa(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=mp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,wr(s,e,r,0,s.length),r+=s.length}return Mr.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=Zd(o<<8|c<<3|u);i.push(d)}}e+=s}return Mr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Wa(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}}),tf=$e({encode(t,e,r){e||(e=new Uint8Array(tf.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,tf.encode.bytes=r-n,ae(e,tf.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=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,tf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Mr.encodingLength(t.rrtypes)}}),rf=$e({encode(t,e,r){e||(e=new Uint8Array(rf.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!es(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!es(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,wr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,wr(o,e,r,0,o.length),r+=o.length,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,rf.encode.bytes=r-n,ae(e,rf.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=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,rf.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Mr.encodingLength(t.rrtypes)}}),nf=$e({encode(t,e,r){e||(e=new Uint8Array(nf.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!es(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,wr(i,e,r,0,i.length),r+=i.length,nf.encode.bytes=r-n,ae(e,nf.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,nf.decode.bytes=e-r,n},encodingLength(t){return 6+io(t.digest)}}),Ja=$e({encode(t,e,r){e||(e=new Uint8Array(Ja.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=ob(t.fingerprint),o=ab(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return R_(e,t.fingerprint,r,r+=i),Ja.encode.bytes=r-n,ae(e,Ja.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=ab(n.hash);return n.fingerprint=I_(t,e,e+i),e+=i,Ja.decode.bytes=e-r,n},encodingLength(t){return 4+ob(t.fingerprint)}});function ab(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Ja.getFingerprintLengthForHashType=ab;function sb(t){switch(t.toUpperCase()){case"A":return k_;case"PTR":return Xa;case"CNAME":return Xa;case"DNAME":return Xa;case"TXT":return Sp;case"NULL":return Ap;case"AAAA":return Ip;case"SRV":return _p;case"HINFO":return Tp;case"CAA":return ts;case"NS":return Ep;case"SOA":return vp;case"MX":return Bp;case"OPT":return rs;case"DNSKEY":return li;case"RRSIG":return Qd;case"RP":return ef;case"NSEC":return tf;case"NSEC3":return rf;case"SSHFP":return Ja;case"DS":return nf}return xp}var fn=$e({encode(t,e,r){e||(e=new Uint8Array(fn.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Wa(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,rs.encode(t.options||[],e,r),r+=rs.encode.bytes}else{let i=rb(t.class===void 0?"IN":t.class);t.flush&&(i|=cb),ae(e,i,r+2),fi(e,t.ttl||0,r+4),r+=8;let o=sb(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return fn.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=Zd(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=rs.decode(t,e+8),e+=8+rs.decode.bytes;else{let i=he(t,e+2);r.ttl=di(t,e+4),r.class=tb(i&dC),r.flush=!!(i&cb);let o=sb(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return fn.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+sb(t.type).encodingLength(e)}}),Qa=$e({encode(t,e,r){e||(e=new Uint8Array(Qa.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Wa(t.type),r),r+=2,ae(e,rb(t.class===void 0?"IN":t.class),r),r+=2,Qa.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=Zd(he(t,e)),e+=2,n.class=tb(he(t,e)),e+=2,!!(n.class&D_)&&(n.class&=fC),Qa.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var N_=1024;var Vt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(lC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Ya.encode(t,e,r),r+=Ya.encode.bytes,r=of(t.questions,Qa,e,r),r=of(t.answers,fn,e,r),r=of(t.authorities,fn,e,r),r=of(t.additionals,fn,e,r),Vt.encode.bytes=r-i,n&&sf.bytes!==e.length?e.slice(0,sf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Ya.decode(t,e);return e+=Ya.decode.bytes,e=bp(n.questions,Qa,t,e),e=bp(n.answers,fn,t,e),e=bp(n.authorities,fn,t,e),e=bp(n.additionals,fn,t,e),Vt.decode.bytes=e-r,n},encodingLength:function(t){return Ya.encodingLength(t)+Za(t.questions||[],Qa)+Za(t.answers||[],fn)+Za(t.authorities||[],fn)+Za(t.additionals||[],fn)}};Vt.encode.bytes=0;Vt.decode.bytes=0;function Rp(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 Up={encode:function(t,e,r){return e=Vt.encode(Rp(t,"query"),e,r),Up.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Up.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Rp(t,"query"))}};Up.encode.bytes=0;Up.decode.bytes=0;var Op={encode:function(t,e,r){return e=Vt.encode(Rp(t,"response"),e,r),Op.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Op.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Rp(t,"response"))}};Op.encode.bytes=0;Op.decode.bytes=0;var sf=Vt.encode,Dp=Vt.decode,lC=Vt.encodingLength;function C_(t){let e=sf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),wr(e,r,2,0,e.length),C_.bytes=r.byteLength,r}C_.bytes=0;function L_(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=Dp(t.slice(2));return L_.bytes=Dp.bytes,r}L_.bytes=0;function Za(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function of(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 bp(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 P_=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())})},ln=class{static getSigningMethod(e){return P_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return P_(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())})},M_=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},K_="https://diddht.tbddev.org",hC=0,ns=7200,kp=";",or=",",ub;(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"})(ub||(ub={}));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 db;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(db||(db={}));var H_={Ed25519:sr.Ed25519,ES256K:sr.secp256k1,ES256:sr.secp256r1,"P-256":sr.secp256r1,secp256k1:sr.secp256k1,secp256r1:sr.secp256r1,X25519:sr.X25519},$_={[sr.Ed25519]:"EdDSA",[sr.secp256k1]:"ES256K",[sr.secp256r1]:"ES256",[sr.X25519]:"ECDH-ES+A256KW"},cf=class t extends ln{static create(){return kt(this,arguments,void 0,function*({keyManager:e=new Qt,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 H_)))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}#${Pr(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 mr({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 Qt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield mr.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 Pr(c.id)===((a=Pr(n))!==null&&a!==void 0?a:Pr((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=K_}){return yield Np.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:K_;try{yield Dt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Np.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})})}})}};cf.methodName="dht";var Np=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||$_[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=M_(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:ns,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:ns,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:ns,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 H_))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!==$_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:ns,data:X.join(kp)})}(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=M_(I,["id","type","serviceEndpoint"]);T=Pr(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(kp),Q=Dt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:ns,data:Q})});let E=[`v=${hC}`];if(y.length&&E.push(`vm=${y.join(or)}`),Object.keys(Pi).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=db[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"?ub[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:ns,data:`id=${A.join(or)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:ns,data:E.join(kp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:ns,data:I+"."});return{id:0,type:"response",flags:N_,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=sf(r),c=eb.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!==cf.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:${cf.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:Fa}[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=eb.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 Dp(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(kp).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 Ye={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 Pe=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var zJ=new Uint8Array(0);var fb=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 lb=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")}},hb=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 V_(this,e)}},pb=class{constructor(e){this.decoders=e}or(e){return V_(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`)}},V_=(t,e)=>new pb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),yb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new lb(e,r,n),this.decoder=new hb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pC=({name:t,prefix:e,encode:r,decode:n})=>new yb(t,e,r,n);var yC=(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},gC=(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},af=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>pC({prefix:e,name:t,encode(i){return gC(i,n,r)},decode(i){return yC(i,n,r,t)}});var oZ=af({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sZ=af({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uf=af({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cZ=af({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var br=class t{static encode(e){return uf.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Pe(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return uf.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(F_(),1);l();l();var gb;(function(t){t.Public="public",t.Private="private"})(gb||(gb={}));var Kr=gb;var It=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Kr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Pe(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Pe(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Pe(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Kr.Private&&(e.d===void 0||e.d.length!==43))throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Pe(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!br.isBase64UrlString(e))throw new Pe(Ye.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 Pe(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var df=class{};df.hashAlgorithmInMultihashCode=18;df.maxCanonicalizedDeltaSizeInBytes=1e3;var cr=df;l();var G_=Pn(W_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=G_.default(r);return br.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 mC=J_,z_=128,wC=127,bC=~wC,xC=Math.pow(2,31);function J_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xC;)e[r++]=t&255|z_,t/=128;for(;t&bC;)e[r++]=t&255|z_,t>>>=7;return e[r]=t|0,J_.bytes=r-n+1,e}var EC=mb,vC=128,Y_=127;function mb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw mb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&Y_)<<i:(s&Y_)*Math.pow(2,i),i+=7}while(s>=vC);return mb.bytes=o-n,r}var SC=Math.pow(2,7),AC=Math.pow(2,14),TC=Math.pow(2,21),_C=Math.pow(2,28),BC=Math.pow(2,35),IC=Math.pow(2,42),RC=Math.pow(2,49),UC=Math.pow(2,56),OC=Math.pow(2,63),DC=function(t){return t<SC?1:t<AC?2:t<TC?3:t<_C?4:t<BC?5:t<IC?6:t<RC?7:t<UC?8:t<OC?9:10},kC={encode:mC,decode:EC,encodingLength:DC},NC=kC,ff=NC;var wb=(t,e=0)=>[ff.decode(t,e),ff.decode.bytes],bb=(t,e,r=0)=>(ff.encode(t,e,r),e),xb=t=>ff.encodingLength(t);var Eb=(t,e)=>{let r=e.byteLength,n=xb(t),i=n+xb(r),o=new Uint8Array(i+r);return bb(t,o,0),bb(r,o,n),o.set(e,i),new Lp(t,r,e,o)},Z_=t=>{let e=fb(t),[r,n]=wb(e),[i,o]=wb(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Lp(r,i,s,e)};var Lp=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var Sb=({name:t,code:e,encode:r})=>new vb(t,e,r),vb=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?Eb(this.code,r):r.then(n=>Eb(this.code,n))}else throw Error("Unknown type, must be binary type")}};var X_=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pp=Sb({name:"sha2-256",code:18,encode:X_("SHA-256")}),HZ=Sb({name:"sha2-512",code:19,encode:X_("SHA-512")});var lf=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 lf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Pp.digest(e)).bytes;break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return lf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Pp.encode(e);break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return lf(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return lf(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 lf(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return br.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=br.decodeAsBytes(e,r);try{n=Z_(i)}catch{throw new Pe(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=cr.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var Ab;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(Ab||(Ab={}));var hf=Ab;l();var Tb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(Tb||(Tb={}));var yc=Tb;var Mp=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())})},is=class t{static createCreateRequest(e){return Mp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;It.validateEs256kOperationKey(r,Kr.Public),It.validateEs256kOperationKey(n,Kr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=cr.hashAlgorithmInMultihashCode,c=[{action:yc.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:hf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Mp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Kr.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:hf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Mp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextRecoveryPublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:yc.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:hf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Mp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.updatePublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.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:yc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:yc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:yc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:yc.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:hf.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 Pe(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(It.validateId(n.id),r.has(n.id))throw new Pe(Ye.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 Pe(Ye.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 Pe(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Pe(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Q_.parse(e.serviceEndpoint).error!==void 0)throw new Pe(Ye.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 Pe(Ye.DeltaExceedsMaximumSize,n)}}};var eB=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())})},eu=class t{static createLongFormDid(e){return eB(this,void 0,void 0,function*(){let r=yield is.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=br.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return eB(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Nt.hash(r,cr.hashAlgorithmInMultihashCode);return br.encode(n)})}};l();l();var tB;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(tB||(tB={}));l();var rB;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(rB||(rB={}));l();var os=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 PC={Ed25519:hi.Ed25519,ES256K:hi.secp256k1,ES256:hi.secp256r1,"P-256":hi.secp256r1,secp256k1:hi.secp256k1,secp256r1:hi.secp256r1},nB="https://ion.tbd.engineering",_b=class t extends ln{static create(){return os(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in PC)))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 gc.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 mr({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 os(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 os(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield mr.import({portableDid:r,keyManager:n})})}static publish(e){return os(this,arguments,void 0,function*({did:r,gatewayUri:n=nB}){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:c_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield gc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield gc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=gc.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 os(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:nB;try{let a=gc.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})})}})}};_b.methodName="ion";var gc=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 os(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 eu.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return os(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield is.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return os(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())})},Bb=class t extends ln{static create(){return Kp(this,arguments,void 0,function*({keyManager:e=new Qt,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 mr({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 Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.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})})}};Bb.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())})},so;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(so||(so={}));var Ib={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"},MC={Ed25519:so.Ed25519,ES256K:so.secp256k1,ES256:so.secp256r1,"P-256":so.secp256r1,secp256k1:so.secp256k1,secp256r1:so.secp256r1,X25519:so.X25519},Rb=class t extends ln{static create(){return kn(this,arguments,void 0,function*({keyManager:e=new Qt,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 xr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new mr({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 Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.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 s_({didDocument:a}).forEach(g=>{let y=Ib[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=xr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Gw({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 Ib))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 xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.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}=zw({multibaseKeyId:n}),f=a.byteLength,h=xr.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 Ib))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 xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.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}=zw({multibaseKeyId:r});if(o===237){let s=yield xr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield _t.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield xr.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&&aa(n)==="String"&&n.startsWith("z")}};Rb.methodName="key";var xr=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:Yt.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:Fa}[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?Yt.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 MC))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 Gw({keyBytes:i,multicodecName:o})})}};xr.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"};xr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};xr.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())})},Ub=class t extends ln{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"}})}})}};Ub.methodName="web";l();var jC=Pn(oB(),1),WC=Pn(om(),1);l();l();var Er=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 Ve("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Pi).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 sB(t,e,r){return t&e^~t&r}function cB(t,e,r){return t&e^t&r^e&r}var Hp=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=Nl(this.buffer)}update(e){na(this),Se(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=Nl(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),Lv(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=Nl(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()}},co=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var GC=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]),ss=new Uint32Array(64),Ob=class extends Hp{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)ss[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ss[f-15],p=ss[f-2],g=xn(h,7)^xn(h,18)^h>>>3,y=xn(p,17)^xn(p,19)^p>>>10;ss[f]=y+ss[f-7]+g+ss[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+sB(c,a,u)+GC[f]+ss[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+cB(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(ss)}destroy(){this.set(0,0,0,0,0,0,0,0),Os(this.buffer)}},Db=class extends Ob{A=co[0]|0;B=co[1]|0;C=co[2]|0;D=co[3]|0;E=co[4]|0;F=co[5]|0;G=co[6]|0;H=co[7]|0;constructor(){super(32)}};var Vp=Mv(()=>new Db,Kv(1));l();l();var ar=BigInt(0),er=BigInt(1),wc=BigInt(2),dB=BigInt(3),fB=BigInt(4),lB=BigInt(5),zC=BigInt(7),hB=BigInt(8),YC=BigInt(9),pB=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 aB(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=er,s=er,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!==er)throw new Error("invert: does not exist");return Nn(i,e)}function Nb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function yB(t,e){let r=(t.ORDER+er)/fB,n=t.pow(e,r);return Nb(t,n,e),n}function JC(t,e){let r=(t.ORDER-lB)/hB,n=t.mul(e,wc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,wc),i),c=t.mul(o,t.sub(s,t.ONE));return Nb(t,c,e),c}function ZC(t){let e=iu(t),r=gB(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+zC)/pB;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 Nb(c,E,a),E}}function gB(t){if(t<dB)throw new Error("sqrt is not defined for small field");let e=t-er,r=0;for(;e%wc===ar;)e/=wc,r++;let n=wc,i=iu(t);for(;uB(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return yB;let o=i.pow(n,e),s=(e+er)/wc;return function(a,u){if(a.is0(u))return u;if(uB(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=er<<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 XC(t){return t%fB===dB?yB:t%hB===lB?JC:t%pB===YC?ZC(t):gB(t)}var QC=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cb(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=QC.reduce((n,i)=>(n[i]="function",n),e);return Qu(t,r),t}function eL(t,e,r){if(r<ar)throw new Error("invalid exponent, negatives unsupported");if(r===ar)return t.ONE;if(r===er)return e;let n=t.ONE,i=e;for(;r>ar;)r&er&&(n=t.mul(n,i)),i=t.sqr(i),r>>=er;return n}function qp(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 uB(t,e){let r=(t.ORDER-er)/wc,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 tL(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 kb=class{ORDER;BITS;BYTES;isLE;ZERO=ar;ONE=er;_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}=tL(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&er)===er}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 eL(this,e,r)}div(e,r){return Nn(e*aB(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 aB(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=XC(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?j0(e,this.BYTES):Ll(e,this.BYTES)}fromBytes(e,r=!1){Se(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?F0(e):Oo(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 qp(this,e)}cmov(e,r,n){return n?r:e}};function iu(t,e={}){return new kb(t,e)}function mB(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 Lb(t){let e=mB(t);return e+Math.ceil(e/2)}function Fp(t,e,r=!1){Se(t);let n=t.length,i=mB(e),o=Lb(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?F0(t):Oo(t),c=Nn(s,e-er)+er;return r?j0(c,i):Ll(c,i)}var ou=BigInt(0),bc=BigInt(1);function pf(t,e){let r=e.negate();return t?r:e}function $b(t,e){let r=qp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function EB(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pb(t,e){EB(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Xu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function wB(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+=bc);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 Mb=new WeakMap,vB=new WeakMap;function Kb(t){return vB.get(t)||1}function bB(t){if(t!==ou)throw new Error("invalid wNAF")}var jp=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>ou;)r&bc&&(n=n.add(i)),i=i.double(),r>>=bc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Pb(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=Pb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=wB(n,c,s);n=a,d?o=o.add(pf(h,r[p])):i=i.add(pf(f,r[u]))}return bB(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Pb(e,this.bits);for(let s=0;s<o.windows&&n!==ou;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=wB(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return bB(n),i}getPrecomputes(e,r,n){let i=Mb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Mb.set(r,i))),i}cached(e,r,n){let i=Kb(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Kb(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){EB(r,this.bits),vB.set(e,r),Mb.delete(e)}hasCache(e){return Kb(e)!==1}};function SB(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>ou||n>ou;)r&bc&&(o=o.add(i)),n&bc&&(s=s.add(i)),i=i.double(),r>>=bc,n>>=bc;return{p1:o,p2:s}}function xB(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cb(e),e}else return iu(t,{isLE:r})}function AB(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>ou))throw new Error(`CURVE.${a} must be positive bigint`)}let i=xB(e.p,r.Fp,n),o=xB(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 Wp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Gp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(kl(e),Se(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 na(this),this.iHash.update(e),this}digestInto(e){na(this),Se(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()}},Hb=(t,e,r)=>new Gp(t,e).update(r).digest();Hb.create=(t,e)=>new Gp(t,e);var TB=(t,e)=>(t+(t>=0?e:-e)/_B)/e;function rL(t,e,r){let[[n,i],[o,s]]=e,c=TB(s*t,r),a=TB(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<ao,h=d<ao;f&&(u=-u),h&&(d=-d);let p=Xu(Math.ceil(W0(r)/2))+su;if(u<ao||u>=p||d<ao||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function qb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Vb(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ju(r.lowS,"lowS"),Ju(r.prehash,"prehash"),r.format!==void 0&&qb(r.format),r}var Fb=class extends Error{constructor(e=""){super(e)}},cs={Err:Fb,_tlv:{encode:(t,e)=>{let{Err:r}=cs;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}=cs,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}=cs;if(t<ao)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}=cs;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 Oo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=cs,i=Se(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}=cs,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},ao=BigInt(0),su=BigInt(1),_B=BigInt(2),zp=BigInt(3),nL=BigInt(4);function BB(t,e={}){let r=AB("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Qu(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=RB(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(Ju(D,"isCompressed"),D){d();let N=!n.isOdd(U);return lr(IB(N),L)}else return lr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){Se(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,zp),nL),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 rL(G,a.basises,i.ORDER)}let M=G0((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=G0(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),_=pf(x,_),D=pf(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(Se(_,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(zp),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,zp),{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,zp),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=>$b($,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 $b($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===ao||x.is0())return $.ZERO;if(_===su)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}=SB($,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===su?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===su?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Ju(_,"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 jp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function IB(t){return Uint8Array.of(t?2:3)}function RB(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function iL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(RB(t.Fp,r),{seed:Lb(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 Fp(Se(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(!Yu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=Se(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=Wp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function UB(t,e,r={}){kl(e),Qu(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)=>Hb(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=iL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*_B<o.ORDER;function E(D){let x=c>>su;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){qb(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return Se(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}=cs.toSig(Se(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(lr(IB((N&1)===0),C)),V=s.inv(R),J=M(Se(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(qb(x),x==="der")return ks(cs.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return x==="recovered"?(I(),lr(Uint8Array.of(this.assertRecovery()),N,R)):lr(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=Oo(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=Xu(a);function j(D){return qv("num < 2^"+a,D,ao,q),s.toBytes(D)}function $(D,x){return Se(D,void 0,"message"),x?Se(e(D),void 0,"prehashed message"):D}function X(D,x,U){let{lowS:L,prehash:N,extraEntropy:R}=Vb(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(Se(Y,void 0,"extraEntropy"))}let J=lr(...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===ao)return;let Re=s.create(ue*s.create(z+ce*P));if(Re===ao)return;let Me=(ee.x===ce?0:2)|Number(ee.y&su),Je=Re;return L&&E(Re)&&(Je=s.neg(Re),Me^=1),new O(ce,Je,y?void 0:Me)}return{seed:J,k2sig:W}}function Q(D,x,U={}){let{seed:L,k2sig:N}=X(D,x,U);return Fv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Vb(L,g);if(U=Se(U,void 0,"publicKey"),x=$(x,R),!Yu(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}=Vb(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 Zp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},sL=BigInt(0),jb=BigInt(2);function cL(t){let e=Zp.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,jb,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,jb,e);if(!Yp.eql(Yp.sqr(M),t))throw new Error("Cannot find square root");return M}var Yp=iu(Zp.p,{sqrt:cL}),xc=BB(Zp,{Fp:Yp,endo:oL}),hn=UB(xc,Vp),OB={};function Jp(t,...e){let r=OB[t];if(r===void 0){let n=Vp(Vv(t));r=lr(n,n),OB[t]=r}return Vp(lr(r,...e))}var Gb=t=>t.toBytes(!0).slice(1),zb=t=>t%jb===sL;function Wb(t){let{Fn:e,BASE:r}=xc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:zb(i.y)?n:e.neg(n),bytes:Gb(i)}}function kB(t){let e=Yp;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);zb(i)||(i=e.neg(i));let o=xc.fromAffine({x:t,y:i});return o.assertValidity(),o}var yf=Oo;function NB(...t){return xc.Fn.create(yf(Jp("BIP0340/challenge",...t)))}function DB(t){return Wb(t).bytes}function aL(t,e,r=Ns(32)){let{Fn:n}=xc,i=Se(t,void 0,"message"),{bytes:o,scalar:s}=Wb(e),c=Se(r,32,"auxRand"),a=n.toBytes(s^yf(Jp("BIP0340/aux",c))),u=Jp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Wb(u),h=NB(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!CB(p,i,o))throw new Error("sign: Invalid signature produced");return p}function CB(t,e,r){let{Fp:n,Fn:i,BASE:o}=xc,s=Se(t,64,"signature"),c=Se(e,void 0,"message"),a=Se(r,32,"publicKey");try{let u=kB(yf(a)),d=yf(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=yf(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=NB(i.toBytes(d),Gb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!zb(y)||g!==d)}catch{return!1}}var Xp=(()=>{let r=(n=Ns(48))=>Fp(n,Zp.n);return{keygen:Wp(r,DB),getPublicKey:DB,sign:aL,verify:CB,Point:xc,utils:{randomSecretKey:r,taggedHash:Jp,lift_x:kB,pointToBytes:Gb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function uL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function PB(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 Yb(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function MB(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Jb(t){if(!Array.isArray(t))throw new Error("array expected")}function KB(t,e){if(!PB(!0,e))throw new Error(`${t}: array of strings expected`)}function dL(t,e){if(!PB(!1,e))throw new Error(`${t}: array of numbers expected`)}function fL(...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 lL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;KB("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Jb(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=>(Jb(i),i.map(o=>{Yb("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function hL(t=""){return Yb("join",t),{encode:e=>(KB("join.decode",e),e.join(t)),decode:e=>(Yb("join.decode",e),e.split(t))}}function LB(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(Jb(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(MB(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 pL(t){MB(t);let e=2**8;return{encode:r=>{if(!uL(r))throw new Error("radix.encode input should be Uint8Array");return LB(Array.from(r),e,t)},decode:r=>(dL("radix.decode",r),Uint8Array.from(LB(r,t,e)))}}var yL=t=>fL(pL(58),lL(t),hL("")),cu=yL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var $B=new Uint8Array([231,1]),ht=class t{#e;#t={prefix:$B,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Tr(e);if(!r||r.length!==33)throw new Bs("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!hn.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 hn.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 cu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from($B);return r.push(...e),"z"+cu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return hn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return Xp.verify(e,r,this.x);throw new Bs(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return ia(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 HB=new Uint8Array([129,38]),gL=Ct(De(HB)),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<hn.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>=hn.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(HB);return r.push(...e),"z"+cu.encode(Uint8Array.from(r))}equals(e){return ia(this.bytes,e.bytes)}computePublicKey(){return new ht(hn.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 hn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return hn.sign(e,this.bytes);if(r.scheme==="schnorr")return Xp.sign(e,this.bytes);throw new jn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=cu.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(De(n))!==gL)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(!hn.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=_r(32);while(!hn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var uo=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"?Tr(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 ur=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in Io))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=Wu[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:${Fc.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}`,xl,{identifier:e});if(!o)throw new mt(`Invalid method-specific id: ${e}`,Lt,{identifier:e});let{prefix:s,bytes:c}=Fc.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=Wu[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=uo.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 Vr=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new xe("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!Er.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 zt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=ur.decode(e),o=Uo(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 zt("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 zt("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 Zb(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 Xb=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(Vr.parseBitcoinAddress(o.serviceEndpoint));if(!(!s||!s.length))for(let c of s){let a=c.vout.slice(-1)[0];if(!a)continue;let u=Zb(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 je("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=Vr.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!==k0)for(let d of u.vin){if(d.coinbase||d.txinwitness&&d.txinwitness.length===1&&d.txinwitness[0]===D0||!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=Zb(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 Yte=new Uint8Array(0);function VB(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 mL(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 wL=mL,bL=wL,qB=bL;var Qb=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")}},ex=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 FB(this,e)}},tx=class{decoders;constructor(e){this.decoders=e}or(e){return FB(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 FB(t,e){return new tx({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var rx=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 Qb(e,r,n),this.decoder=new ex(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xL({name:t,prefix:e,encode:r,decode:n}){return new rx(t,e,r,n)}function nx({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=qB(r,t);return xL({prefix:e,name:t,encode:n,decode:o=>VB(i(o))})}var gf=nx({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ore=nx({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var au=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 Qr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",_o,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new Qr("Domain mismatch: proof.domain !== config.domain",_o,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new Qr("Challenge mismatch options and challenge passed",_o,{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 Qr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Wn,s);if(r&&r!==c.proofPurpose)throw new Qr("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Wn,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new Qr("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 Qr("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 Qr("Domain mismatch: expectedDomain and proof.domain do not match",Wn,{proof:c,expectedDomain:i})}else if(c.domain!==i)throw new Qr("Domain mismatch: proof.domain !== expectedDomain",Wn,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var uu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new au(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=gf.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=gf.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 xe("Type mismatch: config.type !== this.type",Wn,{config:r,this:this});if(r.cryptosuite!==this.cryptosuite)throw new xe("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Wn,{config:r,this:this});return rr(e)}generateHash(e,r){let n=De(ws(e)),i=De(ws(r)),o=ut(n,i);return De(o)}proofConfiguration(e){if(e.type!==this.type)throw new To("Type mismatch: config.type !== this.type",_o,{config:e,this:this});if(e.cryptosuite!==this.cryptosuite)throw new To("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",_o,{config:e,this:this});if(e.created&&!Ro.isValidXsdDateTime(e.created))throw new To('Invalid config: "created" must be a valid XMLSchema DateTime string',_o,e);return rr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Ev,{config:r,this:this});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Wn,{config:n,this:this});return this.multikey.verify(r,e)}};l();l();l();var as=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 uu(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 Rr.sign(e,this.secretKey.bytes,_r(32))}verify(e,r){return Rr.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 uo({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 uo({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 uo({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",El,{publicKeyMultibase:n});let i=gf.decode(n);if(i.length!==35)throw new bn(`Invalid publicKeyMultibase length: ${i.length}`,El,{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)??"??"}]`,El,{publicKeyMultibase:n});let o=i.slice(2),s=new uo({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();l();var jB=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Ec="Multikey",vc="zQ3s",qr="did:btcr2:_",EL="",WB=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function GB(t){if(!Er.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===Ec&&typeof r=="string"&&r.startsWith(vc)}var Qp=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==Ec)throw new Ve(`Invalid verification method: type must be "${Ec}"`,Oe,{id:e,type:r});if(typeof i!="string"||!i.startsWith(vc))throw new Ve(`Invalid verification method: publicKeyMultibase must start with "${vc}"`,Oe,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},Fr=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 Ve("DID Document must have an id",Oe,e);let r=e.id.includes("k1")?Io.KEY:Io.EXTERNAL,n=e.id===qr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new Ve(`Invalid id: ${i}`,Oe,e);if(!t.isValidVerificationMethods(o))throw new Ve("Invalid verificationMethod: "+o,Oe,e);if(!t.isValidServices(s))throw new Ve("Invalid service: "+s,Oe,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===Io.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 Qp({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 Ve('Invalid "@context"',Oe,e);if(!this.isValidId(e?.id))throw new Ve('Invalid "id"',Oe,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new Ve('Invalid "verificationMethod"',Oe,e);if(!this.isValidServices(e?.service))throw new Ve('Invalid "service"',Oe,e);if(!this.isValidVerificationRelationships(e))throw new Ve("Invalid verification relationships",Oe,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:jB.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return ur.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(GB)}static isValidServices(e){return Array.isArray(e)&&e.every(a_)}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"||Er.isDidVerificationMethod(c))})}static validate(e){return e.id===qr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==qr)throw new Ve("Invalid GenesisDocument ID",Oe,this);if(!this.verificationMethod.every(e=>e.id.includes(qr)&&e.controller===qr))throw new Ve("Invalid GenesisDocument verificationMethod",Oe,this);if(!this.service.every(e=>e.id.includes(qr)))throw new Ve("Invalid GenesisDocument service",Oe,this);if(!t.isValidVerificationRelationships(this))throw new Ve("Invalid GenesisDocument assertionMethod",Oe,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new Ve("Cannot convert a key identifier to an intermediate document",Oe,this);return new ey(this)}},ey=class t extends Fr{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(qr,e),n=JSON.parse(r);return new Fr(n)}static fromDidDocument(e){let r=Us.cloneReplace(e,WB,qr);return new t(r)}static create(e,r,n){return new t({id:qr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ht(e),i=qr,o=ki(n.compressed,Uo(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 Bo(rr(e))}};var mf=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=ea.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}").`,ke,{sourceId:e.id,targetId:o.id});try{Fr.isValid(o)}catch(s){throw new vt("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),ke,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}".`,ke,{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}".`,ke,{verificationMethodId:n.id});let c=n.id.slice(s),a=as.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.`,ke,{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,o){return Cs.establish(e).broadcastSignal(r,n,i,o)}#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.`,ke,{phase:this.#e.phase});if(!r)throw new vt("NeedSigningKey requires a Signer.",ke);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.`,ke,{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)}.`,ke,{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.`,ke,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var wf=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new xe("idType is required for creating a did:btcr2 identifier",Oe,r);return ur.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=ur.decode(e),i=fo.sidecarData(r.sidecar),o=n.hrp===Ul.k?fo.deterministic(n):null;return new fo(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",Oe,e);let s=this.getSigningMethod(e,i);if(!s)throw new vt("Invalid verificationMethod: not found in source document",Oe,{sourceDocument:e,verificationMethodId:i});if(s.type!==Ec)throw new vt(`Invalid verificationMethod: verificationMethod.type must be "${Ec}"`,Oe,s);if(!s.publicKeyMultibase?.startsWith(vc))throw new vt(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${vc}"`,Oe,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",ke,{sourceDocument:e,beaconId:o});return new mf({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 xe(`Method not supported: ${n.method}`,xl,{identifier:e.id});let i=e.verificationMethod?.find(o=>Er.extractDidFragment(o.id)===(Er.extractDidFragment(r)??Er.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 bf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vL(t){return bf(t)&&Object.values(t).every(e=>typeof e=="string")}function SL(t){return bf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&bf(t.proof):!1}function AL(t){return bf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}var fo=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=ur.encode(r,e),{multibase:i}=new ht(r),o=Vr.generateBeaconServices({id:n,publicKey:r,network:Uo(e.network),beaconType:"SingletonBeacon"});return new Fr({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Xc(r);if(!Tu(e.genesisBytes,n))throw new je("Initial document mismatch: genesisBytes !== genesisDocumentHash",Oe,{genesisBytes:en(e.genesisBytes,"hex"),genesisDocumentHash:en(n,"hex")});let i=ur.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(qr,i));return new Fr(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(en(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=Xc(u.didDocument),p=Ro.blocktimeToTimestamp(f.time);if(u.metadata.updated=Ro.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(n&&p>Ro.dateStringToTimestamp(n))return u;if(d.targetVersionId===s+1){let y=Is(d.sourceHash,"base64urlnopad");if(!Tu(y,h))throw new je("Hash mismatch: update.sourceHash !== currentDocumentHash",ke,{sourceHash:d.sourceHash,currentDocumentHash:en(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let E=Us.deleteKeys(d,["proof"]);c.push(Xc(E))}else throw new je("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",vl,{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){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new je("Invalid duplicate: targetVersionId must be an integer >= 2",ke,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=Xc(i),s=r[e.targetVersionId-2];if(s===void 0)throw new je("Invalid duplicate: no applied update in history for targetVersionId",vl,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!Tu(s,o))throw new je("Invalid duplicate: unsigned update hash does not match historical hash",vl,{unsignedUpdateHash:en(o,"hex"),historicalHash:en(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new je("No root capability found in update",ke,r);let i=Er.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(S=>S===e.id))throw new je("Invalid root capability",ke,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new je("No verificationMethod found in update",ke,r);let a=wf.getSigningMethod(e,c),u=as.fromVerificationMethod(a),d=new uu(u),f=rr(r),p=new au(d).verifyProof(f,"capabilityInvocation");if(!p.verified)throw new je("Invalid update: proof not verified",ke,p);let g=ea.apply(e,r.patch);Fr.validate(g);let y=Xc(g),E=Is(r.targetHash);if(!Tu(E,y))throw new je("Invalid update: update.targetHash !== currentDocumentHash",ke,{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:en(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=Vr.getBeaconServices(this.#i).filter(n=>{let i=Vr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=Vr.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=Cs.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=[],Vr.getBeaconServices(this.#i).some(n=>{let i=Vr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new je(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,xv,{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(!bf(r))throw new je("Provided data for NeedGenesisDocument must be a document object.",ke,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new je("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",ke,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!vL(r))throw new je("Provided data for NeedCASAnnouncement is not a CAS announcement.",ke,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new je(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,ke,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!SL(r))throw new je("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",ke,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.updateHash)throw new je(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,ke,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!AL(r))throw new je("Provided data for NeedSMTProof is not an SMT proof.",ke,{kind:e.kind});let n=en(Is(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new je(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,ke,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function zB(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new Ve("Cannot derive aggregation communication key: capabilityInvocation is absent",Oe,{id:t.id});let r=typeof e=="string"?t.verificationMethod?.find(n=>n.id===e):e;if(!r)throw new Ve(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,Oe,{id:t.id,invocation:e});return as.fromVerificationMethod(r).publicKey}function TL(t,e){try{let r=ur.decode(t);if(r.idType==="KEY")return new ht(r.genesisBytes);if(e?.genesisDocument){let n=fo.external(r,e.genesisDocument);return zB(n)}}catch{}}l();l();l();var ix=class{document={};constructor(e){if(!e.id)throw new Ve('Missing required "id" property',Oe,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 Fr(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};return bI(_L);})();
1
+ "use strict";var BTCR2=(()=>{var mI=Object.create;var Rf=Object.defineProperty;var wI=Object.getOwnPropertyDescriptor;var bI=Object.getOwnPropertyNames;var xI=Object.getPrototypeOf,EI=Object.prototype.hasOwnProperty;var vI=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),xu=(t,e)=>{for(var r in e)Rf(t,r,{get:e[r],enumerable:!0})},yx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bI(e))!EI.call(t,i)&&i!==r&&Rf(t,i,{get:()=>e[i],enumerable:!(n=wI(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?mI(xI(t)):{},yx(e||!t||!t.__esModule?Rf(r,"default",{value:t,enumerable:!0}):r,t)),SI=t=>yx(Rf({},"__esModule",{value:!0}),t);var wx=oe(Uf=>{"use strict";l();Uf.byteLength=TI;Uf.toByteArray=BI;Uf.fromByteArray=UI;var Mn=[],Yr=[],AI=typeof Uint8Array<"u"?Uint8Array:Array,sy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hs=0,gx=sy.length;hs<gx;++hs)Mn[hs]=sy[hs],Yr[sy.charCodeAt(hs)]=hs;var hs,gx;Yr[45]=62;Yr[95]=63;function mx(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 TI(t){var e=mx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function _I(t,e,r){return(e+r)*3/4-r}function BI(t){var e,r=mx(t),n=r[0],i=r[1],o=new AI(_I(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Yr[t.charCodeAt(a)]<<18|Yr[t.charCodeAt(a+1)]<<12|Yr[t.charCodeAt(a+2)]<<6|Yr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Yr[t.charCodeAt(a)]<<2|Yr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Yr[t.charCodeAt(a)]<<10|Yr[t.charCodeAt(a+1)]<<4|Yr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function II(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function RI(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(II(n));return i.join("")}function UI(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(RI(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 bx=oe(cy=>{l();cy.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)};cy.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 Ar=oe(Oc=>{"use strict";l();var ay=wx(),Uc=bx(),xx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Oc.Buffer=F;Oc.SlowBuffer=LI;Oc.INSPECT_MAX_BYTES=50;var Of=2147483647;Oc.kMaxLength=Of;F.TYPED_ARRAY_SUPPORT=OI();!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 OI(){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 mi(t){if(t>Of)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 ly(t)}return Sx(t,e,r)}F.poolSize=8192;function Sx(t,e,r){if(typeof t=="string")return kI(t,e);if(ArrayBuffer.isView(t))return NI(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 dy(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=CI(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 Sx(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function Ax(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 DI(t,e,r){return Ax(t),t<=0?mi(t):e!==void 0?typeof r=="string"?mi(t).fill(e,r):mi(t).fill(e):mi(t)}F.alloc=function(t,e,r){return DI(t,e,r)};function ly(t){return Ax(t),mi(t<0?0:hy(t)|0)}F.allocUnsafe=function(t){return ly(t)};F.allocUnsafeSlow=function(t){return ly(t)};function kI(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=Tx(t,e)|0,n=mi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function uy(t){for(var e=t.length<0?0:hy(t.length)|0,r=mi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function NI(t){if(Kn(t,Uint8Array)){var e=new Uint8Array(t);return dy(e.buffer,e.byteOffset,e.byteLength)}return uy(t)}function dy(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 CI(t){if(F.isBuffer(t)){var e=hy(t.length)|0,r=mi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||py(t.length)?mi(0):uy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return uy(t.data)}function hy(t){if(t>=Of)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Of.toString(16)+" bytes");return t|0}function LI(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 Tx(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 fy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Ox(t).length;default:if(i)return n?-1:fy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Tx;function PI(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 GI(this,e,r);case"utf8":case"utf-8":return Bx(this,e,r);case"ascii":return jI(this,e,r);case"latin1":case"binary":return WI(this,e,r);case"base64":return qI(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return zI(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?Bx(this,0,e):PI.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=Oc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};xx&&(F.prototype[xx]=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 _x(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,py(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:Ex(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):Ex(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Ex(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 _x(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return _x(this,e,r,n,!1)};function MI(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(py(c))return s;t[r+s]=c}return s}function KI(t,e,r,n){return Df(fy(e,t.length-r),t,r,n)}function $I(t,e,r,n){return Df(ZI(e),t,r,n)}function HI(t,e,r,n){return Df(Ox(e),t,r,n)}function VI(t,e,r,n){return Df(XI(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 MI(this,e,r,n);case"utf8":case"utf-8":return KI(this,e,r,n);case"ascii":case"latin1":case"binary":return $I(this,e,r,n);case"base64":return HI(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return VI(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 qI(t,e,r){return e===0&&r===t.length?ay.fromByteArray(t):ay.fromByteArray(t.slice(e,r))}function Bx(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 FI(n)}var vx=4096;function FI(t){var e=t.length;if(e<=vx)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=vx));return r}function jI(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 WI(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 GI(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+=QI[t[o]];return i}function zI(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),Uc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Uc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Uc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Uc.read(this,e,!1,52,8)};function dr(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;dr(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;dr(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||dr(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||dr(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||dr(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||dr(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||dr(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);dr(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);dr(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||dr(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||dr(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||dr(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||dr(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||dr(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 Ix(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 Rx(t,e,r,n,i){return e=+e,r=r>>>0,i||Ix(t,e,r,4,34028234663852886e22,-34028234663852886e22),Uc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Rx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Rx(this,e,r,!1,n)};function Ux(t,e,r,n,i){return e=+e,r=r>>>0,i||Ix(t,e,r,8,17976931348623157e292,-17976931348623157e292),Uc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return Ux(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return Ux(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 YI=/[^+/0-9A-Za-z-_]/g;function JI(t){if(t=t.split("=")[0],t=t.trim().replace(YI,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function fy(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 ZI(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function XI(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 Ox(t){return ay.toByteArray(JI(t))}function Df(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 py(t){return t!==t}var QI=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 xi=oe((zL,Cx)=>{l();var at=Cx.exports={},$n,Hn;function yy(){throw new Error("setTimeout has not been defined")}function gy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?$n=setTimeout:$n=yy}catch{$n=yy}try{typeof clearTimeout=="function"?Hn=clearTimeout:Hn=gy}catch{Hn=gy}})();function Dx(t){if($n===setTimeout)return setTimeout(t,0);if(($n===yy||!$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 e8(t){if(Hn===clearTimeout)return clearTimeout(t);if((Hn===gy||!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 wi=[],Dc=!1,ys,kf=-1;function t8(){!Dc||!ys||(Dc=!1,ys.length?wi=ys.concat(wi):kf=-1,wi.length&&kx())}function kx(){if(!Dc){var t=Dx(t8);Dc=!0;for(var e=wi.length;e;){for(ys=wi,wi=[];++kf<e;)ys&&ys[kf].run();kf=-1,e=wi.length}ys=null,Dc=!1,e8(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];wi.push(new Nx(t,e)),wi.length===1&&!Dc&&Dx(kx)};function Nx(t,e){this.fun=t,this.array=e}Nx.prototype.run=function(){this.fun.apply(null,this.array)};at.title="browser";at.browser=!0;at.env={};at.argv=[];at.version="";at.versions={};function bi(){}at.on=bi;at.addListener=bi;at.once=bi;at.off=bi;at.removeListener=bi;at.removeAllListeners=bi;at.emit=bi;at.prependListener=bi;at.prependOnceListener=bi;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,JL,l=vI(()=>{b=Pn(Ar()),w=Pn(xi()),JL=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 n1=oe((RH,r1)=>{l();var u6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Hl=()=>u6.now(),d6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),eg=t=>t===1/0||d6(t),tg=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&&!eg(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!eg(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-Hl());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(Hl()+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(!eg(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-Hl())):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(Hl());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()}};r1.exports=tg});var x1=oe(b1=>{"use strict";l();b1.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((QV,E1)=>{"use strict";l();E1.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 gg=oe((tq,v1)=>{"use strict";l();var yg=null;v1.exports=function(){return yg===null&&(yg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),yg}});var bg=oe(S1=>{"use strict";l();var mg=En(),q6=new Set(["buffer","view","utf8"]),wg=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"||!q6.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 mg(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new mg(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new mg(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};S1.Encoding=wg});var Sg=oe(ql=>{"use strict";l();var{Buffer:Eg}=Ar()||{},{Encoding:vg}=bg(),F6=gg(),ad=class extends vg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new ud({encode:this.encode,decode:e=>this.decode(Eg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},ud=class extends vg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new ad({encode:e=>{let r=this.encode(e);return Eg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},xg=class extends vg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new ad({encode:e=>Eg.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=F6();return new ud({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};ql.BufferFormat=ad;ql.ViewFormat=ud;ql.UTF8Format=xg});var B1=oe(Ks=>{"use strict";l();var{Buffer:Jt}=Ar()||{Buffer:{isBuffer:()=>!1}},{textEncoder:T1,textDecoder:A1}=gg()(),{BufferFormat:dd,ViewFormat:Ag,UTF8Format:_1}=Sg(),Fl=t=>t;Ks.utf8=new _1({encode:function(t){return Jt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?A1.decode(t):String(t)},decode:Fl,name:"utf8",createViewTranscoder(){return new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:T1.encode(t)},decode:function(t){return A1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new dd({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Ks.json=new _1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ks.buffer=new dd({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Fl,name:"buffer",createViewTranscoder(){return new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:Jt.from(String(t),"utf8")},decode:function(t){return Jt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Ks.view=new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:T1.encode(t)},decode:Fl,name:"view",createBufferTranscoder(){return new dd({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Fl,name:`${this.name}+buffer`})}});Ks.hex=new dd({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ks.base64=new dd({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var U1=oe(R1=>{"use strict";l();var I1=En(),Wl=B1(),{Encoding:j6}=bg(),{BufferFormat:W6,ViewFormat:G6,UTF8Format:z6}=Sg(),fd=Symbol("formats"),jl=Symbol("encodings"),Y6=new Set(["buffer","view","utf8"]),Tg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>Y6.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[jl]=new Map,this[fd]=new Set(e);for(let r in Wl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[jl].values()))}encoding(e){let r=this[jl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=Q6[e],!r)throw new I1(`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=J6(e)}let{name:n,format:i}=r;if(!this[fd].has(i))if(this[fd].has("view"))r=r.createViewTranscoder();else if(this[fd].has("buffer"))r=r.createBufferTranscoder();else if(this[fd].has("utf8"))r=r.createUTF8Transcoder();else throw new I1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[jl].set(o,r)}return r}};R1.Transcoder=Tg;function J6(t){if(t instanceof j6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${eU++}`;switch(Z6(t)){case"view":return new G6({...t,name:r});case"utf8":return new z6({...t,name:r});case"buffer":return new W6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function Z6(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 X6={binary:Wl.buffer,"utf-8":Wl.utf8},Q6={...Wl,...X6},eU=0});var la=oe((fq,_g)=>{"use strict";l();var fa=typeof Reflect=="object"?Reflect:null,O1=fa&&typeof fa.apply=="function"?fa.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Gl;fa&&typeof fa.ownKeys=="function"?Gl=fa.ownKeys:Object.getOwnPropertySymbols?Gl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Gl=function(e){return Object.getOwnPropertyNames(e)};function tU(t){console&&console.warn&&console.warn(t)}var k1=Number.isNaN||function(e){return e!==e};function Le(){Le.init.call(this)}_g.exports=Le;_g.exports.once=oU;Le.EventEmitter=Le;Le.prototype._events=void 0;Le.prototype._eventsCount=0;Le.prototype._maxListeners=void 0;var D1=10;function zl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Le,"defaultMaxListeners",{enumerable:!0,get:function(){return D1},set:function(t){if(typeof t!="number"||t<0||k1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");D1=t}});Le.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};Le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||k1(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 N1(t){return t._maxListeners===void 0?Le.defaultMaxListeners:t._maxListeners}Le.prototype.getMaxListeners=function(){return N1(this)};Le.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")O1(a,this,r);else for(var u=a.length,d=K1(a,u),n=0;n<u;++n)O1(d[n],this,r);return!0};function C1(t,e,r,n){var i,o,s;if(zl(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=N1(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,tU(c)}return t}Le.prototype.addListener=function(e,r){return C1(this,e,r,!1)};Le.prototype.on=Le.prototype.addListener;Le.prototype.prependListener=function(e,r){return C1(this,e,r,!0)};function rU(){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 L1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=rU.bind(n);return i.listener=r,n.wrapFn=i,i}Le.prototype.once=function(e,r){return zl(r),this.on(e,L1(this,e,r)),this};Le.prototype.prependOnceListener=function(e,r){return zl(r),this.prependListener(e,L1(this,e,r)),this};Le.prototype.removeListener=function(e,r){var n,i,o,s,c;if(zl(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():nU(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Le.prototype.off=Le.prototype.removeListener;Le.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 P1(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?iU(i):K1(i,i.length)}Le.prototype.listeners=function(e){return P1(this,e,!0)};Le.prototype.rawListeners=function(e){return P1(this,e,!1)};Le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):M1.call(t,e)};Le.prototype.listenerCount=M1;function M1(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}Le.prototype.eventNames=function(){return this._eventsCount>0?Gl(this._events):[]};function K1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function nU(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function iU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function oU(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))}$1(t,e,o,{once:!0}),e!=="error"&&sU(t,i,{once:!0})})}function sU(t,e,r){typeof t.on=="function"&&$1(t,"error",e,r)}function $1(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 V1=oe((hq,H1)=>{l();H1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var ld=oe(Bg=>{"use strict";l();var q1=V1();Bg.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};Bg.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){q1(()=>e(null,r))}).catch(function(r){q1(()=>e(r))})}});var Yl=oe(Ig=>{"use strict";l();Ig.getCallback=function(t,e){return typeof t=="function"?t:e};Ig.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Mo=oe(Ql=>{"use strict";l();var{fromCallback:Rg}=ld(),Dr=En(),{getOptions:Ug,getCallback:F1}=Yl(),$s=Symbol("promise"),ha=Symbol("callback"),Zn=Symbol("working"),Hs=Symbol("handleOne"),Ki=Symbol("handleMany"),Og=Symbol("autoClose"),Lo=Symbol("finishWork"),Xn=Symbol("returnMany"),ko=Symbol("closing"),hd=Symbol("handleClose"),Jl=Symbol("closed"),pd=Symbol("closeCallbacks"),Co=Symbol("keyEncoding"),Vs=Symbol("valueEncoding"),Dg=Symbol("abortOnClose"),Zl=Symbol("legacy"),kg=Symbol("keys"),Ng=Symbol("values"),No=Symbol("limit"),en=Symbol("count"),Xl=Object.freeze({}),cU=()=>{},j1=!1,yd=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[Jl]=!1,this[pd]=[],this[Zn]=!1,this[ko]=!1,this[Og]=!1,this[ha]=null,this[Hs]=this[Hs].bind(this),this[Ki]=this[Ki].bind(this),this[hd]=this[hd].bind(this),this[Co]=r[Co],this[Vs]=r[Vs],this[Zl]=n,this[No]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[en]=0,this[Dg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[en]}get limit(){return this[No]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[Zl]?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[ko]?this.nextTick(e,new Dr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(e,new Dr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Zn]=!0,this[ha]=e,this[en]>=this[No]?this.nextTick(this[Hs],null):this._next(this[Hs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=F1(r,n),n=Rg(n,$s),r=Ug(r,Xl),Number.isInteger(e)?(this[ko]?this.nextTick(n,new Dr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(n,new Dr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[No]<1/0&&(e=Math.min(e,this[No]-this[en])),this[Zn]=!0,this[ha]=n,e<=0?this.nextTick(this[Ki],null,[]):this._nextv(e,r,this[Ki])),n[$s]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[$s])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[Zl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[Zl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=F1(e,r),r=Rg(r,$s),e=Ug(e,Xl),this[ko]?this.nextTick(r,new Dr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(r,new Dr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Zn]=!0,this[ha]=r,this[Og]=!0,this[en]>=this[No]?this.nextTick(this[Ki],null,[]):this._all(e,this[Ki])),r[$s]}_all(e,r){let n=this[en],i=[],o=()=>{let c=this[No]<1/0?Math.min(1e3,this[No]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Xl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Lo](){let e=this[ha];return this[Dg]&&e===null?cU:(this[Zn]=!1,this[ha]=null,this[ko]&&this._close(this[hd]),e)}[Xn](e,r,n){this[Og]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=Ug(r,Xl),!this[ko]){if(this[Zn])throw new Dr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Co]),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 Dr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=Rg(e,$s),this[Jl]?this.nextTick(e):this[ko]?this[pd].push(e):(this[ko]=!0,this[pd].push(e),this[Zn]?this[Dg]&&this[Lo]()(new Dr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[hd])),e[$s]}_close(e){this.nextTick(e)}[hd](){this[Jl]=!0,this.db.detachResource(this);let e=this[pd];this[pd]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[Jl]||await this.close()}}},pa=class extends yd{constructor(e,r){super(e,r,!0),this[kg]=r.keys!==!1,this[Ng]=r.values!==!1}[Hs](e,r,n){let i=this[Lo]();if(e)return i(e);try{r=this[kg]&&r!==void 0?this[Co].decode(r):void 0,n=this[Ng]&&n!==void 0?this[Vs].decode(n):void 0}catch(o){return i(new Po("entry",o))}r===void 0&&n===void 0||this[en]++,i(null,r,n)}[Ki](e,r){let n=this[Lo]();if(e)return this[Xn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[kg]&&o!==void 0?this[Co].decode(o):void 0,i[1]=this[Ng]&&s!==void 0?this[Vs].decode(s):void 0}}catch(i){return this[Xn](n,new Po("entries",i))}this[en]+=r.length,this[Xn](n,null,r)}end(e){return!j1&&typeof console<"u"&&(j1=!0,console.warn(new Dr("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)}},Cg=class extends yd{constructor(e,r){super(e,r,!1)}[Hs](e,r){let n=this[Lo]();if(e)return n(e);try{r=r!==void 0?this[Co].decode(r):void 0}catch(i){return n(new Po("key",i))}r!==void 0&&this[en]++,n(null,r)}[Ki](e,r){let n=this[Lo]();if(e)return this[Xn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Co].decode(o):void 0}}catch(i){return this[Xn](n,new Po("keys",i))}this[en]+=r.length,this[Xn](n,null,r)}},Lg=class extends yd{constructor(e,r){super(e,r,!1)}[Hs](e,r){let n=this[Lo]();if(e)return n(e);try{r=r!==void 0?this[Vs].decode(r):void 0}catch(i){return n(new Po("value",i))}r!==void 0&&this[en]++,n(null,r)}[Ki](e,r){let n=this[Lo]();if(e)return this[Xn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Vs].decode(o):void 0}}catch(i){return this[Xn](n,new Po("values",i))}this[en]+=r.length,this[Xn](n,null,r)}},Po=class extends Dr{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(pa.prototype,t.split(" ")[0],{get(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});pa.keyEncoding=Co;pa.valueEncoding=Vs;Ql.AbstractIterator=pa;Ql.AbstractKeyIterator=Cg;Ql.AbstractValueIterator=Lg});var W1=oe(Pg=>{"use strict";l();var{AbstractKeyIterator:aU,AbstractValueIterator:uU}=Mo(),qs=Symbol("iterator"),gd=Symbol("callback"),ya=Symbol("handleOne"),Fs=Symbol("handleMany"),md=class extends aU{constructor(e,r){super(e,r),this[qs]=e.iterator({...r,keys:!0,values:!1}),this[ya]=this[ya].bind(this),this[Fs]=this[Fs].bind(this)}},eh=class extends uU{constructor(e,r){super(e,r),this[qs]=e.iterator({...r,keys:!1,values:!0}),this[ya]=this[ya].bind(this),this[Fs]=this[Fs].bind(this)}};for(let t of[md,eh]){let e=t===md,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[gd]=n,this[qs].next(this[ya])},t.prototype[ya]=function(n,i,o){let s=this[gd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[gd]=o,this[qs].nextv(n,i,this[Fs])},t.prototype._all=function(n,i){this[gd]=i,this[qs].all(n,this[Fs])},t.prototype[Fs]=function(n,i){let o=this[gd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[qs].seek(n,i)},t.prototype._close=function(n){this[qs].close(n)}}Pg.DefaultKeyIterator=md;Pg.DefaultValueIterator=eh});var G1=oe(sh=>{"use strict";l();var{AbstractIterator:dU,AbstractKeyIterator:fU,AbstractValueIterator:lU}=Mo(),Mg=En(),pr=Symbol("nut"),ih=Symbol("undefer"),oh=Symbol("factory"),th=class extends dU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.iterator(r),this.db.defer(()=>this[ih]())}},rh=class extends fU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.keys(r),this.db.defer(()=>this[ih]())}},nh=class extends lU{constructor(e,r){super(e,r),this[pr]=null,this[oh]=()=>e.values(r),this.db.defer(()=>this[ih]())}};for(let t of[th,rh,nh])t.prototype[ih]=function(){this.db.status==="open"&&(this[pr]=this[oh]())},t.prototype._next=function(e){this[pr]!==null?this[pr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Mg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[pr]!==null?this[pr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Mg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[pr]!==null?this[pr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Mg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[pr]!==null?this[pr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[pr]!==null?this[pr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};sh.DeferredIterator=th;sh.DeferredKeyIterator=rh;sh.DeferredValueIterator=nh});var $g=oe(Y1=>{"use strict";l();var{fromCallback:z1}=ld(),ch=En(),{getCallback:hU,getOptions:pU}=Yl(),ah=Symbol("promise"),tn=Symbol("status"),ga=Symbol("operations"),wd=Symbol("finishClose"),ma=Symbol("closeCallbacks"),Kg=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[ga]=[],this[ma]=[],this[tn]="open",this[wd]=this[wd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[ga].length}put(e,r,n){if(this[tn]!=="open")throw new ch("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[ga].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[tn]!=="open")throw new ch("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[ga].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[tn]!=="open")throw new ch("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[ga]=[],this}_clear(){}write(e,r){return r=hU(e,r),r=z1(r,ah),e=pU(e),this[tn]!=="open"?this.nextTick(r,new ch("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[tn]="writing",this._write(e,n=>{this[tn]="closing",this[ma].push(()=>r(n)),n||this.db.emit("batch",this[ga]),this._close(this[wd])})),r[ah]}_write(e,r){}close(e){return e=z1(e,ah),this[tn]==="closing"?this[ma].push(e):this[tn]==="closed"?this.nextTick(e):(this[ma].push(e),this[tn]!=="writing"&&(this[tn]="closing",this._close(this[wd]))),e[ah]}_close(e){this.nextTick(e)}[wd](){this[tn]="closed",this.db.detachResource(this);let e=this[ma];this[ma]=[];for(let r of e)r()}};Y1.AbstractChainedBatch=Kg});var Z1=oe(J1=>{"use strict";l();var{AbstractChainedBatch:yU}=$g(),gU=En(),wa=Symbol("encoded"),Hg=class extends yU{constructor(e){super(e),this[wa]=[]}_put(e,r,n){this[wa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[wa].push({...r,type:"del",key:e})}_clear(){this[wa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[wa].length===0?this.nextTick(r):this.db._batch(this[wa],e,r):this.nextTick(r,new gU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};J1.DefaultChainedBatch=Hg});var e2=oe((Rq,Q1)=>{"use strict";l();var X1=En(),mU=Object.prototype.hasOwnProperty,wU=new Set(["lt","lte","gt","gte"]);Q1.exports=function(t,e){let r={};for(let n in t)if(mU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new X1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new X1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});wU.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 Vg=oe((Oq,r2)=>{l();var t2;r2.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(t2||(t2=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var o2=oe((kq,i2)=>{"use strict";l();var n2=Vg();i2.exports=function(t,...e){e.length===0?n2(t):n2(()=>t(...e))}});var s2=oe(uh=>{"use strict";l();var{AbstractIterator:bU,AbstractKeyIterator:xU,AbstractValueIterator:EU}=Mo(),ba=Symbol("unfix"),vn=Symbol("iterator"),js=Symbol("handleOne"),Ko=Symbol("handleMany"),$i=Symbol("callback"),bd=class extends bU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ba]=i,this[js]=this[js].bind(this),this[Ko]=this[Ko].bind(this),this[$i]=null}[js](e,r,n){let i=this[$i];if(e)return i(e);r!==void 0&&(r=this[ba](r)),i(e,r,n)}[Ko](e,r){let n=this[$i];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ba](o))}n(e,r)}},xd=class extends xU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ba]=i,this[js]=this[js].bind(this),this[Ko]=this[Ko].bind(this),this[$i]=null}[js](e,r){let n=this[$i];if(e)return n(e);r!==void 0&&(r=this[ba](r)),n(e,r)}[Ko](e,r){let n=this[$i];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ba](o))}n(e,r)}},Ed=class extends EU{constructor(e,r,n){super(e,r),this[vn]=n}};for(let t of[bd,xd])t.prototype._next=function(e){this[$i]=e,this[vn].next(this[js])},t.prototype._nextv=function(e,r,n){this[$i]=n,this[vn].nextv(e,r,this[Ko])},t.prototype._all=function(e,r){this[$i]=r,this[vn].all(e,this[Ko])};for(let t of[Ed])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[bd,xd,Ed])t.prototype._seek=function(e,r){this[vn].seek(e,r)},t.prototype._close=function(e){this[vn].close(e)};uh.AbstractSublevelIterator=bd;uh.AbstractSublevelKeyIterator=xd;uh.AbstractSublevelValueIterator=Ed});var d2=oe((Pq,u2)=>{"use strict";l();var qg=En(),{Buffer:Wg}=Ar()||{},{AbstractSublevelIterator:vU,AbstractSublevelKeyIterator:SU,AbstractSublevelValueIterator:AU}=s2(),Hi=Symbol("prefix"),c2=Symbol("upperBound"),vd=Symbol("prefixRange"),kr=Symbol("parent"),Fg=Symbol("unfix"),a2=new TextEncoder,TU={separator:"!"};u2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new qg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new qg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?TU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=BU(i,s);let u=s.charCodeAt(0)+1,d=n[kr]||n;if(!a2.encode(i).every(p=>p>u&&p<127))throw new qg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(_U(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[kr]=d,this[Hi]=new dh(f),this[c2]=new dh(h),this[Fg]=new Gg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Hi].utf8+n;if(n.byteLength===0)return this[Hi][i];if(i==="view"){let o=this[Hi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Hi].buffer;return Wg.concat([o,n],o.byteLength+n.byteLength)}}[vd](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[Hi][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[c2][i]}get prefix(){return this[Hi].utf8}get db(){return this[kr]}_open(n,i){this[kr].open({passive:!0},i)}_put(n,i,o,s){this[kr].put(n,i,o,s)}_get(n,i,o){this[kr].get(n,i,o)}_getMany(n,i,o){this[kr].getMany(n,i,o)}_del(n,i,o){this[kr].del(n,i,o)}_batch(n,i,o){this[kr].batch(n,i,o)}_clear(n,i){this[vd](n,n.keyEncoding),this[kr].clear(n,i)}_iterator(n){this[vd](n,n.keyEncoding);let i=this[kr].iterator(n),o=this[Fg].get(this[Hi].utf8.length,n.keyEncoding);return new vU(this,n,i,o)}_keys(n){this[vd](n,n.keyEncoding);let i=this[kr].keys(n),o=this[Fg].get(this[Hi].utf8.length,n.keyEncoding);return new SU(this,n,i,o)}_values(n){this[vd](n,n.keyEncoding);let i=this[kr].values(n);return new AU(this,n,i)}}return{AbstractSublevel:e}};var _U=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:jg(t,"utf8"),buffer:jg(t,"buffer"),view:jg(t,"view")}}},jg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},dh=class{constructor(e){this.utf8=e,this.view=a2.encode(e),this.buffer=Wg?Wg.from(this.view.buffer,0,this.view.byteLength):{}}},Gg=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}},BU=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 Xg=oe(Zg=>{"use strict";l();var{supports:IU}=x1(),{Transcoder:RU}=U1(),{EventEmitter:UU}=la(),{fromCallback:$o}=ld(),Sn=En(),{AbstractIterator:Ws}=Mo(),{DefaultKeyIterator:OU,DefaultValueIterator:DU}=W1(),{DeferredIterator:kU,DeferredKeyIterator:NU,DeferredValueIterator:CU}=G1(),{DefaultChainedBatch:f2}=Z1(),{getCallback:Gs,getOptions:Ho}=Yl(),fh=e2(),pe=Symbol("promise"),Vi=Symbol("landed"),zs=Symbol("resources"),zg=Symbol("closeResources"),Sd=Symbol("operations"),Ad=Symbol("undefer"),lh=Symbol("deferOpen"),l2=Symbol("options"),be=Symbol("status"),Ys=Symbol("defaultOptions"),xa=Symbol("transcoder"),hh=Symbol("keyEncoding"),Yg=Symbol("valueEncoding"),LU=()=>{},Td=class extends UU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=Ho(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[zs]=new Set,this[Sd]=[],this[lh]=!0,this[l2]=s,this[be]="opening",this.supports=IU(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[xa]=new RU(PU(this)),this[hh]=this[xa].encoding(n||"utf8"),this[Yg]=this[xa].encoding(i||"utf8");for(let c of this[xa].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Ys]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[hh].commonName,valueEncoding:this[Yg].commonName}),key:Object.freeze({keyEncoding:this[hh].commonName})},this.nextTick(()=>{this[lh]&&this.open({passive:!1},LU)})}get status(){return this[be]}keyEncoding(e){return this[xa].encoding(e??this[hh])}valueEncoding(e){return this[xa].encoding(e??this[Yg])}open(e,r){r=Gs(e,r),r=$o(r,pe),e={...this[l2],...Ho(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[be]==="closing"||this[be]==="opening"?this.once(Vi,i?()=>n(i):n):this[be]!=="open"?r(new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[be]==="opening"?this.once(Vi,n):this.nextTick(n):this[be]==="closed"||this[lh]?(this[lh]=!1,this[be]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[be]="closed",this[zg](()=>{this.emit(Vi),n(i)}),this[Ad]();return}this[be]="open",this[Ad](),this.emit(Vi),this[be]==="open"&&this.emit("open"),this[be]==="open"&&this.emit("ready"),n()})):this[be]==="open"?this.nextTick(n):this.once(Vi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=$o(e,pe);let r=n=>{this[be]==="opening"||this[be]==="closing"?this.once(Vi,n?r(n):r):this[be]!=="closed"?e(new Sn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[be]==="open"){this[be]="closing",this.emit("closing");let n=i=>{this[be]="open",this[Ad](),this.emit(Vi),r(i)};this[zg](()=>{this._close(i=>{if(i)return n(i);this[be]="closed",this[Ad](),this.emit(Vi),this[be]==="closed"&&this.emit("closed"),r()})})}else this[be]==="closed"?this.nextTick(r):this.once(Vi,()=>this.close(e));return e[pe]}[zg](e){if(this[zs].size===0)return this.nextTick(e);let r=this[zs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[zs])o.close(i);n=!1,this[zs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].entry),this[be]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(Ea(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=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].entry),this[be]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(Ea(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=Gs(n,i),i=$o(i,pe),n=Ho(n,this[Ys].entry),this[be]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(Ea(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=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].key),this[be]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(Ea(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[be]==="opening")return new f2(this);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Gs(r,n),n=$o(n,pe),r=Ho(r,this[Ys].empty),this[be]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(Ea(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,Jg.defaults(r))}_sublevel(e,r){return new Jg(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Gs(e,r),r=$o(r,pe),e=Ho(e,this[Ys].empty),this[be]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(Ea(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=fh(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=fh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new kU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Ws(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=fh(e,r),e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new NU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new OU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=fh(e,r),e[Ws.keyEncoding]=r,e[Ws.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new CU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new DU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[Sd].push(e)}[Ad](){if(this[Sd].length===0)return;let e=this[Sd];this[Sd]=[];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[zs].add(e)}detachResource(e){this[zs].delete(e)}_chainedBatch(){return new f2(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"})}};Td.prototype.nextTick=o2();var{AbstractSublevel:Jg}=d2()({AbstractLevel:Td});Zg.AbstractLevel=Td;Zg.AbstractSublevel=Jg;var Ea=function(t,e){return t[be]!=="open"?(t.nextTick(e,new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},PU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var Qg=oe(Js=>{"use strict";l();Js.AbstractLevel=Xg().AbstractLevel;Js.AbstractSublevel=Xg().AbstractSublevel;Js.AbstractIterator=Mo().AbstractIterator;Js.AbstractKeyIterator=Mo().AbstractKeyIterator;Js.AbstractValueIterator=Mo().AbstractValueIterator;Js.AbstractChainedBatch=$g().AbstractChainedBatch});var p2=oe((qq,h2)=>{l();h2.exports=KU;var MU=Vg();function KU(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?MU(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 em=oe((jq,y2)=>{"use strict";l();y2.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 tm=oe((Gq,g2)=>{"use strict";l();var $U=new TextEncoder;g2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):$U.encode(t)}});var E2=oe(x2=>{"use strict";l();var{AbstractIterator:HU}=Qg(),m2=em(),ph=tm(),Qn=Symbol("cache"),qi=Symbol("finished"),Nr=Symbol("options"),Fi=Symbol("currentOptions"),Zs=Symbol("position"),rm=Symbol("location"),va=Symbol("first"),w2={},nm=class extends HU{constructor(e,r,n){super(e,n),this[Qn]=[],this[qi]=this.limit===0,this[Nr]=n,this[Fi]={...n},this[Zs]=void 0,this[rm]=r,this[va]=!0}_nextv(e,r,n){if(this[va]=!1,this[qi])return this.nextTick(n,null,[]);if(this[Qn].length>0)return e=Math.min(e,this[Qn].length),this.nextTick(n,null,this[Qn].splice(0,e));this[Zs]!==void 0&&(this[Nr].reverse?(this[Fi].lt=this[Zs],this[Fi].lte=void 0):(this[Fi].gt=this[Zs],this[Fi].gte=void 0));let i;try{i=m2(this[Fi])}catch{return this[qi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[rm]],"readonly"),s=o.objectStore(this[rm]),c=[];if(this[Nr].reverse){let a=!this[Nr].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[Zs]=f,c.push([this[Nr].keys&&f!==void 0?ph(f):void 0,this[Nr].values&&h!==void 0?ph(h):void 0]),c.length<e?d.continue():b2(o)}else this[qi]=!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[qi]=!0:this[Zs]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Nr].keys&&p!==void 0?ph(p):void 0,this[Nr].values&&g!==void 0?ph(g):void 0]}b2(o)};this[Nr].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[Nr].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[Qn].length>0){let[r,n]=this[Qn].shift();this.nextTick(e,null,r,n)}else if(this[qi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[va]&&(this[va]=!1,r=1),this._nextv(r,w2,(n,i)=>{if(n)return e(n);this[Qn]=i,this._next(e)})}}_all(e,r){this[va]=!1;let n=this[Qn].splice(0,this[Qn].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,w2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[va]=!0,this[Qn]=[],this[qi]=!1,this[Zs]=void 0,this[Fi]={...this[Nr]};let n;try{n=m2(this[Nr])}catch{this[qi]=!0;return}n!==null&&!n.includes(e)?this[qi]=!0:this[Nr].reverse?this[Fi].lte=e:this[Fi].gte=e}};x2.Iterator=nm;function b2(t){typeof t.commit=="function"&&t.commit()}});var S2=oe((Zq,v2)=>{"use strict";l();v2.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 R2=oe(I2=>{"use strict";l();var{AbstractLevel:VU}=Qg(),A2=En(),qU=p2(),{fromCallback:FU}=ld(),{Iterator:jU}=E2(),T2=tm(),WU=S2(),GU=em(),B2="level-js-",_d=Symbol("idb"),im=Symbol("namePrefix"),ji=Symbol("location"),om=Symbol("version"),Xs=Symbol("store"),Bd=Symbol("onComplete"),_2=Symbol("promise"),yh=class extends VU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new A2("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[ji]=e,this[im]=i??B2,this[om]=parseInt(o||1,10),this[_d]=null}get location(){return this[ji]}get namePrefix(){return this[im]}get version(){return this[om]}get db(){return this[_d]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[im]+this[ji],this[om]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[_d]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[ji])||o.createObjectStore(this[ji])}}[Xs](e){return this[_d].transaction([this[ji]],e).objectStore(this[ji])}[Bd](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[Xs]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[Bd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new A2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,T2(c))})}_getMany(e,r,n){let i=this[Xs]("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:T2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});qU(o,16,n)}_del(e,r,n){let i=this[Xs]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[Bd](o,n)}_put(e,r,n,i){let o=this[Xs]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[Bd](s,i)}_iterator(e){return new jU(this,this[ji],e)}_batch(e,r,n){let i=this[Xs]("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=GU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return WU(this,this[ji],n,e,r);try{let o=this[Xs]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[Bd](i,r)}_close(e){this[_d].close(),this.nextTick(e)}};yh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=B2),r=FU(r,_2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[_2]};I2.BrowserLevel=yh});var sm=oe(U2=>{l();U2.Level=R2().BrowserLevel});var nt=oe((aF,O2)=>{"use strict";l();O2.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 Sa=oe((dF,mh)=>{"use strict";l();var{AbortController:D2,AbortSignal:YU}=typeof self<"u"?self:typeof window<"u"?window:void 0;mh.exports=D2;mh.exports.AbortSignal=YU;mh.exports.default=D2});var Zt=oe((lF,am)=>{"use strict";l();var JU=Ar(),{kResistStopPropagation:ZU,SymbolDispose:XU}=nt(),QU=globalThis.AbortSignal||Sa().AbortSignal,e5=globalThis.AbortController||Sa().AbortController,t5=Object.getPrototypeOf(async function(){}).constructor,k2=globalThis.Blob||JU.Blob,r5=typeof k2<"u"?function(e){return e instanceof k2}:function(e){return!1},N2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},n5=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},cm=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}};am.exports={AggregateError:cm,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 t5},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:r5,deprecate(t,e){return t},addAbortListener:la().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);N2(e,"signal"),n5(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[ZU]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[XU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:QU.any||function(e){if(e.length===1)return e[0];let r=new e5,n=()=>r.abort();return e.forEach(i=>{N2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};am.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var ir=oe((pF,P2)=>{"use strict";l();var{format:i5,inspect:wh,AggregateError:o5}=Zt(),s5=globalThis.AggregateError||o5,c5=Symbol("kIsNodeError"),a5=["string","function","number","object","Function","Object","boolean","bigint","symbol"],u5=/^([A-Z][a-z0-9]*)+$/,d5="__node_internal_",bh={};function ec(t,e){if(!t)throw new bh.ERR_INTERNAL_ASSERTION(e)}function C2(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 f5(t,e,r){if(typeof e=="function")return ec(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 ec(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:i5(e,...r)}function Mt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(f5(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[c5]=!0,bh[t]=n}function L2(t){let e=d5+t.name;return Object.defineProperty(t,"name",{value:e}),t}function l5(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new s5([e,t],e.message);return r.code=e.code,r}return t||e}var um=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new bh.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)=>{ec(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)ec(typeof a=="string","All expected entries have to be of type string"),a5.includes(a)?i.push(a.toLowerCase()):u5.test(a)?o.push(a):(ec(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=wh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=wh(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=wh(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)=>{ec(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)=>{ec(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=C2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=C2(n)),n+="n"):n=wh(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);P2.exports={AbortError:um,aggregateTwoErrors:L2(l5),hideStackFrames:L2,codes:bh}});var Ta=oe((gF,G2)=>{"use strict";l();var{ArrayIsArray:fm,ArrayPrototypeIncludes:H2,ArrayPrototypeJoin:V2,ArrayPrototypeMap:h5,NumberIsInteger:lm,NumberIsNaN:p5,NumberMAX_SAFE_INTEGER:y5,NumberMIN_SAFE_INTEGER:g5,NumberParseInt:m5,ObjectPrototypeHasOwnProperty:w5,RegExpPrototypeExec:q2,String:b5,StringPrototypeToUpperCase:x5,StringPrototypeTrim:E5}=nt(),{hideStackFrames:rn,codes:{ERR_SOCKET_BAD_PORT:v5,ERR_INVALID_ARG_TYPE:Xt,ERR_INVALID_ARG_VALUE:Aa,ERR_OUT_OF_RANGE:tc,ERR_UNKNOWN_SIGNAL:M2}}=ir(),{normalizeEncoding:S5}=Zt(),{isAsyncFunction:A5,isArrayBufferView:T5}=Zt().types,K2={};function _5(t){return t===(t|0)}function B5(t){return t===t>>>0}var I5=/^[0-7]+$/,R5="must be a 32-bit unsigned integer or an octal string";function U5(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(q2(I5,t)===null)throw new Aa(e,t,R5);t=m5(t,8)}return F2(t,e),t}var O5=rn((t,e,r=g5,n=y5)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!lm(t))throw new tc(e,"an integer",t);if(t<r||t>n)throw new tc(e,`>= ${r} && <= ${n}`,t)}),D5=rn((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!lm(t))throw new tc(e,"an integer",t);if(t<r||t>n)throw new tc(e,`>= ${r} && <= ${n}`,t)}),F2=rn((t,e,r=!1)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!lm(t))throw new tc(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new tc(e,`>= ${n} && <= ${i}`,t)});function hm(t,e){if(typeof t!="string")throw new Xt(e,"string",t)}function k5(t,e,r=void 0,n){if(typeof t!="number")throw new Xt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&p5(t))throw new tc(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var N5=rn((t,e,r)=>{if(!H2(r,t)){let i="must be one of: "+V2(h5(r,o=>typeof o=="string"?`'${o}'`:b5(o)),", ");throw new Aa(e,t,i)}});function j2(t,e){if(typeof t!="boolean")throw new Xt(e,"boolean",t)}function dm(t,e,r){return t==null||!w5(t,e)?r:t[e]}var C5=rn((t,e,r=null)=>{let n=dm(r,"allowArray",!1),i=dm(r,"allowFunction",!1);if(!dm(r,"nullable",!1)&&t===null||!n&&fm(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Xt(e,"Object",t)}),L5=rn((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Xt(e,"a dictionary",t)}),xh=rn((t,e,r=0)=>{if(!fm(t))throw new Xt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new Aa(e,t,n)}});function P5(t,e){xh(t,e);for(let r=0;r<t.length;r++)hm(t[r],`${e}[${r}]`)}function M5(t,e){xh(t,e);for(let r=0;r<t.length;r++)j2(t[r],`${e}[${r}]`)}function K5(t,e){xh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Xt(i,"AbortSignal",n);W2(n,i)}}function $5(t,e="signal"){if(hm(t,e),K2[t]===void 0)throw K2[x5(t)]!==void 0?new M2(t+" (signals must use all capital letters)"):new M2(t)}var H5=rn((t,e="buffer")=>{if(!T5(t))throw new Xt(e,["Buffer","TypedArray","DataView"],t)});function V5(t,e){let r=S5(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Aa("encoding",e,`is invalid for data of length ${n}`)}function q5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&E5(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new v5(e,t,r);return t|0}var W2=rn((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Xt(e,"AbortSignal",t)}),F5=rn((t,e)=>{if(typeof t!="function")throw new Xt(e,"Function",t)}),j5=rn((t,e)=>{if(typeof t!="function"||A5(t))throw new Xt(e,"Function",t)}),W5=rn((t,e)=>{if(t!==void 0)throw new Xt(e,"undefined",t)});function G5(t,e,r){if(!H2(r,t))throw new Xt(e,`('${V2(r,"|")}')`,t)}var z5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function $2(t,e){if(typeof t>"u"||!q2(z5,t))throw new Aa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function Y5(t){if(typeof t=="string")return $2(t,"hints"),t;if(fm(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];$2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new Aa("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}G2.exports={isInt32:_5,isUint32:B5,parseFileMode:U5,validateArray:xh,validateStringArray:P5,validateBooleanArray:M5,validateAbortSignalArray:K5,validateBoolean:j2,validateBuffer:H5,validateDictionary:L5,validateEncoding:V5,validateFunction:F5,validateInt32:D5,validateInteger:O5,validateNumber:k5,validateObject:C5,validateOneOf:N5,validatePlainFunction:j5,validatePort:q5,validateSignalName:$5,validateString:hm,validateUint32:F2,validateUndefined:W5,validateUnion:G5,validateAbortSignal:W2,validateLinkHeaderValue:Y5}});var ti=oe((wF,aS)=>{"use strict";l();var{SymbolAsyncIterator:z2,SymbolIterator:Y2,SymbolFor:rc}=nt(),J2=rc("nodejs.stream.destroyed"),Z2=rc("nodejs.stream.errored"),pm=rc("nodejs.stream.readable"),ym=rc("nodejs.stream.writable"),X2=rc("nodejs.stream.disturbed"),J5=rc("nodejs.webstream.isClosedPromise"),Z5=rc("nodejs.webstream.controllerErrorFunction");function Eh(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 vh(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 X5(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ei(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function Q2(t){return!!(t&&!ei(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function eS(t){return!!(t&&!ei(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function tS(t){return!!(t&&!ei(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function Q5(t){return Q2(t)||eS(t)||tS(t)}function eO(t,e){return t==null?!1:e===!0?typeof t[z2]=="function":e===!1?typeof t[Y2]=="function":typeof t[z2]=="function"||typeof t[Y2]=="function"}function Sh(t){if(!ei(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[J2]||n!=null&&n.destroyed)}function rS(t){if(!vh(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 tO(t,e){if(!vh(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 rO(t){if(!Eh(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 nS(t,e){if(!Eh(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 iS(t){return t&&t[pm]!=null?t[pm]:typeof t?.readable!="boolean"?null:Sh(t)?!1:Eh(t)&&t.readable&&!nS(t)}function oS(t){return t&&t[ym]!=null?t[ym]:typeof t?.writable!="boolean"?null:Sh(t)?!1:vh(t)&&t.writable&&!rS(t)}function nO(t,e){return ei(t)?Sh(t)?!0:!(e?.readable!==!1&&iS(t)||e?.writable!==!1&&oS(t)):null}function iO(t){var e,r;return ei(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 oO(t){var e,r;return ei(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 sO(t){if(!ei(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"&&sS(t)?t._closed:null}function sS(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function cS(t){return typeof t._sent100=="boolean"&&sS(t)}function cO(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 aO(t){if(!ei(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&cS(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function uO(t){var e;return!!(t&&((e=t[X2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function dO(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[Z2])!==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))}aS.exports={isDestroyed:Sh,kIsDestroyed:J2,isDisturbed:uO,kIsDisturbed:X2,isErrored:dO,kIsErrored:Z2,isReadable:iS,kIsReadable:pm,kIsClosedPromise:J5,kControllerErrorFunction:Z5,kIsWritable:ym,isClosed:sO,isDuplexNodeStream:X5,isFinished:nO,isIterable:eO,isReadableNodeStream:Eh,isReadableStream:Q2,isReadableEnded:rO,isReadableFinished:nS,isReadableErrored:oO,isNodeStream:ei,isWebStream:Q5,isWritable:oS,isWritableNodeStream:vh,isWritableStream:eS,isWritableEnded:rS,isWritableFinished:tO,isWritableErrored:iO,isServerRequest:cO,isServerResponse:cS,willEmitClose:aO,isTransformStream:tS}});var Wi=oe((xF,xm)=>{l();var Vo=xi(),{AbortError:mS,codes:fO}=ir(),{ERR_INVALID_ARG_TYPE:lO,ERR_STREAM_PREMATURE_CLOSE:uS}=fO,{kEmptyObject:mm,once:wm}=Zt(),{validateAbortSignal:hO,validateFunction:pO,validateObject:yO,validateBoolean:gO}=Ta(),{Promise:mO,PromisePrototypeThen:wO,SymbolDispose:wS}=nt(),{isClosed:bO,isReadable:dS,isReadableNodeStream:gm,isReadableStream:xO,isReadableFinished:fS,isReadableErrored:lS,isWritable:hS,isWritableNodeStream:pS,isWritableStream:EO,isWritableFinished:yS,isWritableErrored:gS,isNodeStream:vO,willEmitClose:SO,kIsClosedPromise:AO}=ti(),_a;function TO(t){return t.setHeader&&typeof t.abort=="function"}var bm=()=>{};function bS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=mm):e==null?e=mm:yO(e,"options"),pO(r,"callback"),hO(e.signal,"options.signal"),r=wm(r),xO(t)||EO(t))return _O(t,e,r);if(!vO(t))throw new lO("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:gm(t),s=(i=e.writable)!==null&&i!==void 0?i:pS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=SO(t)&&gm(t)===o&&pS(t)===s,f=yS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=fS(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=bO(t),S=()=>{E=!0;let T=gS(t)||lS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&gm(t,!0)&&!fS(t,!1))return r.call(t,new uS);if(s&&!f&&!yS(t,!1))return r.call(t,new uS);r.call(t)},B=()=>{E=!0;let T=gS(t)||lS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};TO(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?Vo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Vo.nextTick(B):(!o&&(!d||dS(t))&&(f||hS(t)===!1)||!s&&(!d||hS(t))&&(p||dS(t)===!1)||a&&t.req&&t.aborted)&&Vo.nextTick(B);let O=()=>{r=bm,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 mS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Vo.nextTick(T);else{_a=_a||Zt().addAbortListener;let M=_a(e.signal,T),q=r;r=wm((...j)=>{M[wS](),q.apply(t,j)})}}return O}function _O(t,e,r){let n=!1,i=bm;if(e.signal)if(i=()=>{n=!0,r.call(t,new mS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Vo.nextTick(i);else{_a=_a||Zt().addAbortListener;let s=_a(e.signal,i),c=r;r=wm((...a)=>{s[wS](),c.apply(t,a)})}let o=(...s)=>{n||Vo.nextTick(()=>r.apply(t,s))};return wO(t[AO].promise,o,o),bm}function BO(t,e){var r;let n=!1;return e===null&&(e=mm),(r=e)!==null&&r!==void 0&&r.cleanup&&(gO(e.cleanup,"cleanup"),n=e.cleanup),new mO((i,o)=>{let s=bS(t,e,c=>{n&&s(),c?o(c):i()})})}xm.exports=bS;xm.exports.finished=BO});var nc=oe((vF,BS)=>{"use strict";l();var ri=xi(),{aggregateTwoErrors:IO,codes:{ERR_MULTIPLE_CALLBACK:RO},AbortError:UO}=ir(),{Symbol:vS}=nt(),{kIsDestroyed:OO,isDestroyed:DO,isFinished:kO,isServerRequest:NO}=ti(),SS=vS("kDestroy"),Em=vS("kConstruct");function AS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function CO(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):(AS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?xS(this,t,e):this.once(SS,function(o){xS(this,IO(o,t),e)}),this)}function xS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;AS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ri.nextTick(LO,t,o):ri.nextTick(TS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function LO(t,e){vm(t,e),TS(t)}function TS(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 vm(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 PO(){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 Sm(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?ri.nextTick(vm,t,e):vm(t,e))}function MO(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(Em,e),!(t.listenerCount(Em)>1)&&ri.nextTick(KO,t)}function KO(t){let e=!1;function r(n){if(e){Sm(t,n??new RO);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(SS,n):n?Sm(t,n,!0):ri.nextTick($O,t)}try{t._construct(n=>{ri.nextTick(r,n)})}catch(n){ri.nextTick(r,n)}}function $O(t){t.emit(Em)}function ES(t){return t?.setHeader&&typeof t.abort=="function"}function _S(t){t.emit("close")}function HO(t,e){t.emit("error",e),ri.nextTick(_S,t)}function VO(t,e){!t||DO(t)||(!e&&!kO(t)&&(e=new UO),NO(t)?(t.socket=null,t.destroy(e)):ES(t)?t.abort():ES(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ri.nextTick(HO,t,e):ri.nextTick(_S,t),t.destroyed||(t[OO]=!0))}BS.exports={construct:MO,destroyer:VO,destroy:CO,undestroy:PO,errorOrDestroy:Sm}});var _h=oe((AF,RS)=>{"use strict";l();var{ArrayIsArray:qO,ObjectSetPrototypeOf:IS}=nt(),{EventEmitter:Ah}=la();function Th(t){Ah.call(this,t)}IS(Th.prototype,Ah.prototype);IS(Th,Ah);Th.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(),Ah.listenerCount(this,"error")===0&&this.emit("error",d)}Am(r,"error",a),Am(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 Am(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):qO(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}RS.exports={Stream:Th,prependListener:Am}});var Id=oe((_F,Bh)=>{"use strict";l();var{SymbolDispose:FO}=nt(),{AbortError:US,codes:jO}=ir(),{isNodeStream:OS,isWebStream:WO,kControllerErrorFunction:GO}=ti(),zO=Wi(),{ERR_INVALID_ARG_TYPE:DS}=jO,Tm,YO=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new DS(e,"AbortSignal",t)};Bh.exports.addAbortSignal=function(e,r){if(YO(e,"signal"),!OS(r)&&!WO(r))throw new DS("stream",["ReadableStream","WritableStream","Stream"],r);return Bh.exports.addAbortSignalNoValidate(e,r)};Bh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=OS(e)?()=>{e.destroy(new US(void 0,{cause:t.reason}))}:()=>{e[GO](new US(void 0,{cause:t.reason}))};if(t.aborted)r();else{Tm=Tm||Zt().addAbortListener;let n=Tm(t,r);zO(e,n[FO])}return e}});var CS=oe((RF,NS)=>{"use strict";l();var{StringPrototypeSlice:kS,SymbolIterator:JO,TypedArrayPrototypeSet:Ih,Uint8Array:ZO}=nt(),{Buffer:_m}=Ar(),{inspect:XO}=Zt();NS.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 _m.alloc(0);let r=_m.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Ih(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}*[JO](){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+=kS(o,0,e),this.head=n,n.data=kS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=_m.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Ih(r,s,n-e),e-=s.length;else{e===s.length?(Ih(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Ih(r,new ZO(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 XO(this,{...r,depth:0,customInspect:!1})}}});var Rd=oe((OF,KS)=>{"use strict";l();var{MathFloor:QO,NumberIsInteger:e3}=nt(),{validateInteger:t3}=Ta(),{ERR_INVALID_ARG_VALUE:r3}=ir().codes,LS=16*1024,PS=16;function n3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function MS(t){return t?PS:LS}function i3(t,e){t3(e,"value",0),t?PS=e:LS=e}function o3(t,e,r,n){let i=n3(e,n,r);if(i!=null){if(!e3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new r3(o,i)}return QO(i)}return MS(t.objectMode)}KS.exports={getHighWaterMark:o3,getDefaultHighWaterMark:MS,setDefaultHighWaterMark:i3}});var VS=oe((Bm,HS)=>{l();var Rh=Ar(),ni=Rh.Buffer;function $S(t,e){for(var r in t)e[r]=t[r]}ni.from&&ni.alloc&&ni.allocUnsafe&&ni.allocUnsafeSlow?HS.exports=Rh:($S(Rh,Bm),Bm.Buffer=ic);function ic(t,e,r){return ni(t,e,r)}ic.prototype=Object.create(ni.prototype);$S(ni,ic);ic.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ni(t,e,r)};ic.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ni(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};ic.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ni(t)};ic.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Rh.SlowBuffer(t)}});var jS=oe(FS=>{"use strict";l();var Rm=VS().Buffer,qS=Rm.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 s3(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 c3(t){var e=s3(t);if(typeof e!="string"&&(Rm.isEncoding===qS||!qS(t)))throw new Error("Unknown encoding: "+t);return e||t}FS.StringDecoder=Ud;function Ud(t){this.encoding=c3(t);var e;switch(this.encoding){case"utf16le":this.text=h3,this.end=p3,e=4;break;case"utf8":this.fillLast=d3,e=4;break;case"base64":this.text=y3,this.end=g3,e=3;break;default:this.write=m3,this.end=w3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Rm.allocUnsafe(e)}Ud.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||""};Ud.prototype.end=l3;Ud.prototype.text=f3;Ud.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 Im(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function a3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=Im(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=Im(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=Im(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function u3(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 d3(t){var e=this.lastTotal-this.lastNeed,r=u3(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 f3(t,e){var r=a3(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 l3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function h3(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 p3(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 y3(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 g3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function m3(t){return t.toString(this.encoding)}function w3(t){return t&&t.length?this.write(t):""}});var Um=oe((LF,YS)=>{"use strict";l();var WS=xi(),{PromisePrototypeThen:b3,SymbolAsyncIterator:GS,SymbolIterator:zS}=nt(),{Buffer:x3}=Ar(),{ERR_INVALID_ARG_TYPE:E3,ERR_STREAM_NULL_VALUES:v3}=ir().codes;function S3(t,e,r){let n;if(typeof e=="string"||e instanceof x3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[GS])i=!0,n=e[GS]();else if(e&&e[zS])i=!1,n=e[zS]();else throw new E3("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){b3(c(u),()=>WS.nextTick(d,u),f=>WS.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 v3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}YS.exports=S3});var Dd=oe((MF,hA)=>{l();var An=xi(),{ArrayPrototypeIndexOf:A3,NumberIsInteger:T3,NumberIsNaN:_3,NumberParseInt:B3,ObjectDefineProperties:Mm,ObjectKeys:I3,ObjectSetPrototypeOf:XS,Promise:QS,SafeSet:R3,SymbolAsyncDispose:U3,SymbolAsyncIterator:O3,Symbol:D3}=nt();hA.exports=ye;ye.ReadableState=kh;var{EventEmitter:k3}=la(),{Stream:qo,prependListener:N3}=_h(),{Buffer:Om}=Ar(),{addAbortSignal:C3}=Id(),eA=Wi(),xe=Zt().debuglog("stream",t=>{xe=t}),L3=CS(),Ra=nc(),{getHighWaterMark:P3,getDefaultHighWaterMark:M3}=Rd(),{aggregateTwoErrors:JS,codes:{ERR_INVALID_ARG_TYPE:K3,ERR_METHOD_NOT_IMPLEMENTED:$3,ERR_OUT_OF_RANGE:H3,ERR_STREAM_PUSH_AFTER_EOF:V3,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:q3},AbortError:F3}=ir(),{validateObject:j3}=Ta(),oc=D3("kPaused"),{StringDecoder:tA}=jS(),W3=Um();XS(ye.prototype,qo.prototype);XS(ye,qo);var Dm=()=>{},{errorOrDestroy:Ba}=Ra,Ia=1,G3=2,rA=4,Od=8,nA=16,Uh=32,Oh=64,iA=128,z3=256,Y3=512,J3=1024,Lm=2048,Pm=4096,Z3=8192,X3=16384,Q3=32768,oA=65536,eD=1<<17,tD=1<<18;function St(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Mm(kh.prototype,{objectMode:St(Ia),ended:St(G3),endEmitted:St(rA),reading:St(Od),constructed:St(nA),sync:St(Uh),needReadable:St(Oh),emittedReadable:St(iA),readableListening:St(z3),resumeScheduled:St(Y3),errorEmitted:St(J3),emitClose:St(Lm),autoDestroy:St(Pm),destroyed:St(Z3),closed:St(X3),closeEmitted:St(Q3),multiAwaitDrain:St(oA),readingMore:St(eD),dataEmitted:St(tD)});function kh(t,e,r){typeof r!="boolean"&&(r=e instanceof ii()),this.state=Lm|Pm|nA|Uh,t&&t.objectMode&&(this.state|=Ia),r&&t&&t.readableObjectMode&&(this.state|=Ia),this.highWaterMark=t?P3(this,t,"readableHighWaterMark",r):M3(!1),this.buffer=new L3,this.length=0,this.pipes=[],this.flowing=null,this[oc]=null,t&&t.emitClose===!1&&(this.state&=~Lm),t&&t.autoDestroy===!1&&(this.state&=~Pm),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new tA(t.encoding),this.encoding=t.encoding)}function ye(t){if(!(this instanceof ye))return new ye(t);let e=this instanceof ii();this._readableState=new kh(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&&C3(t.signal,this)),qo.call(this,t),Ra.construct(this,()=>{this._readableState.needReadable&&Dh(this,this._readableState)})}ye.prototype.destroy=Ra.destroy;ye.prototype._undestroy=Ra.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[k3.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[U3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new F3,this.destroy(t)),new QS((e,r)=>eA(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return sA(this,t,e,!1)};ye.prototype.unshift=function(t,e){return sA(this,t,e,!0)};function sA(t,e,r,n){xe("readableAddChunk",e);let i=t._readableState,o;if(i.state&Ia||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Om.from(e,r).toString(i.encoding):(e=Om.from(e,r),r=""))):e instanceof Om?r="":qo._isUint8Array(e)?(e=qo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new K3("chunk",["string","Buffer","Uint8Array"],e))),o)Ba(t,o);else if(e===null)i.state&=~Od,iD(t,i);else if(i.state&Ia||e&&e.length>0)if(n)if(i.state&rA)Ba(t,new q3);else{if(i.destroyed||i.errored)return!1;km(t,i,e,!0)}else if(i.ended)Ba(t,new V3);else{if(i.destroyed||i.errored)return!1;i.state&=~Od,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?km(t,i,e,!1):Dh(t,i)):km(t,i,e,!1)}else n||(i.state&=~Od,Dh(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function km(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&oA?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&Oh&&Nh(t)),Dh(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[oc]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new tA(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 rD=1073741824;function nD(t){if(t>rD)throw new H3("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function ZS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Ia?1:_3(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){xe("read",t),t===void 0?t=NaN:T3(t)||(t=B3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=nD(t)),t!==0&&(e.state&=~iA),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return xe("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Nm(this):Nh(this),null;if(t=ZS(t,e),t===0&&e.ended)return e.length===0&&Nm(this),null;let n=(e.state&Oh)!==0;if(xe("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,xe("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,xe("reading, ended or constructing",n);else if(n){xe("do read"),e.state|=Od|Uh,e.length===0&&(e.state|=Oh);try{this._read(e.highWaterMark)}catch(o){Ba(this,o)}e.state&=~Uh,e.reading||(t=ZS(r,e))}let i;return t>0?i=fA(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&&Nm(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function iD(t,e){if(xe("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?Nh(t):(e.needReadable=!1,e.emittedReadable=!0,cA(t))}}function Nh(t){let e=t._readableState;xe("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(xe("emitReadable",e.flowing),e.emittedReadable=!0,An.nextTick(cA,t))}function cA(t){let e=t._readableState;xe("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,uA(t)}function Dh(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,An.nextTick(oD,t,e))}function oD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(xe("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new $3("_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 R3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),xe("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,B){xe("onunpipe"),S===r&&B&&B.hasUnpiped===!1&&(B.hasUnpiped=!0,d())}function c(){xe("onend"),t.end()}let a,u=!1;function d(){xe("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?(xe("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(xe("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=sD(r,t),t.on("drain",a))}r.on("data",h);function h(S){xe("ondata");let B=t.write(S);xe("dest.write",B),B===!1&&f()}function p(S){if(xe("onerror",S),E(),t.removeListener("error",p),t.listenerCount("error")===0){let B=t._writableState||t._readableState;B&&!B.errorEmitted?Ba(t,S):t.emit("error",S)}}N3(t,"error",p);function g(){t.removeListener("finish",y),E()}t.once("close",g);function y(){xe("onfinish"),t.removeListener("close",g),E()}t.once("finish",y);function E(){xe("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(xe("pipe resume"),r.resume()),t};function sD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(xe("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(xe("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=A3(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=qo.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,xe("on readable",n.length,n.reading),n.length?Nh(this):n.reading||An.nextTick(cD,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=qo.prototype.removeListener.call(this,t,e);return t==="readable"&&An.nextTick(aA,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=qo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&An.nextTick(aA,this),e};function aA(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[oc]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function cD(t){xe("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(xe("resume"),t.flowing=!t.readableListening,aD(this,t)),t[oc]=!1,this};function aD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(uD,t,e))}function uD(t,e){xe("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),uA(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return xe("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(xe("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[oc]=!0,this};function uA(t){let e=t._readableState;for(xe("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=>{Ba(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=I3(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[O3]=function(){return dA(this)};ye.prototype.iterator=function(t){return t!==void 0&&j3(t,"options"),dA(this,t)};function dA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=dD(t,e);return r.stream=t,r}async function*dD(t,e){let r=Dm;function n(s){this===t?(r(),r=Dm):r=s}t.on("readable",n);let i,o=eA(t,{writable:!1},s=>{i=s?JS(i,s):null,r(),r=Dm});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 QS(n)}}}catch(s){throw i=JS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ra.destroyer(t,null):(t.off("readable",n),o())}}Mm(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}}});Mm(kh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[oc]!==!1},set(t){this[oc]=!!t}}});ye._fromList=fA;function fA(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 Nm(t){let e=t._readableState;xe("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,An.nextTick(fD,e,t))}function fD(t,e){if(xe("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(lD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function lD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return W3(ye,t,e)};var Cm;function lA(){return Cm===void 0&&(Cm={}),Cm}ye.fromWeb=function(t,e){return lA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return lA().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){Ra.destroyer(t,i),o(i)}}).wrap(t)}});var Kh=oe(($F,TA)=>{l();var sc=xi(),{ArrayPrototypeSlice:gA,Error:hD,FunctionPrototypeSymbolHasInstance:mA,ObjectDefineProperty:wA,ObjectDefineProperties:pD,ObjectSetPrototypeOf:bA,StringPrototypeToLowerCase:yD,Symbol:gD,SymbolHasInstance:mD}=nt();TA.exports=it;it.WritableState=Cd;var{EventEmitter:wD}=la(),kd=_h().Stream,{Buffer:Ch}=Ar(),Mh=nc(),{addAbortSignal:bD}=Id(),{getHighWaterMark:xD,getDefaultHighWaterMark:ED}=Rd(),{ERR_INVALID_ARG_TYPE:vD,ERR_METHOD_NOT_IMPLEMENTED:SD,ERR_MULTIPLE_CALLBACK:xA,ERR_STREAM_CANNOT_PIPE:AD,ERR_STREAM_DESTROYED:Nd,ERR_STREAM_ALREADY_FINISHED:TD,ERR_STREAM_NULL_VALUES:_D,ERR_STREAM_WRITE_AFTER_END:BD,ERR_UNKNOWN_ENCODING:EA}=ir().codes,{errorOrDestroy:Ua}=Mh;bA(it.prototype,kd.prototype);bA(it,kd);function Hm(){}var Oa=gD("kOnFinished");function Cd(t,e,r){typeof r!="boolean"&&(r=e instanceof ii()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?xD(this,t,"writableHighWaterMark",r):ED(!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=RD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Ph(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[Oa]=[]}function Ph(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Cd.prototype.getBuffer=function(){return gA(this.buffered,this.bufferedIndex)};wA(Cd.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof ii();if(!e&&!mA(it,this))return new it(t);this._writableState=new Cd(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&&bD(t.signal,this)),kd.call(this,t),Mh.construct(this,()=>{let r=this._writableState;r.writing||qm(this,r),Fm(this,r)})}wA(it,mD,{__proto__:null,value:function(t){return mA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Cd}});it.prototype.pipe=function(){Ua(this,new AD)};function vA(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"&&!Ch.isEncoding(r))throw new EA(r);typeof n!="function"&&(n=Hm)}if(e===null)throw new _D;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Ch.from(e,r),r="buffer");else if(e instanceof Ch)r="buffer";else if(kd._isUint8Array(e))e=kd._uint8ArrayToBuffer(e),r="buffer";else throw new vD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new BD:i.destroyed&&(o=new Nd("write")),o?(sc.nextTick(n,o),Ua(t,o,!0),o):(i.pendingcb++,ID(t,i,e,r,n))}it.prototype.write=function(t,e,r){return vA(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||qm(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=yD(e)),!Ch.isEncoding(e))throw new EA(e);return this._writableState.defaultEncoding=e,this};function ID(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!==Hm&&(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 pA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Nd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function yA(t,e,r,n){--e.pendingcb,n(r),Vm(e),Ua(t,r)}function RD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Ua(t,new xA);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?sc.nextTick(yA,t,r,e,i):yA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&qm(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},sc.nextTick(UD,r.afterWriteTickInfo)):SA(t,r,1,i))}function UD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,SA(t,e,r,n)}function SA(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&&Vm(e),Fm(t,e)}function Vm(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 Nd("write"))}let r=t[Oa].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Nd("end"))}Ph(t)}function qm(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?Hm:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:gA(r,s);a.allBuffers=e.allBuffers,pA(t,e,!0,e.length,a,"",c),Ph(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;pA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Ph(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 SD("_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=vA(this,t,e);o instanceof hD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Fm(this,n,!0),n.ended=!0):n.finished?i=new TD("end"):n.destroyed&&(i=new Nd("end"))),typeof r=="function"&&(i||n.finished?sc.nextTick(r,i):n[Oa].push(r)),this};function Lh(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 OD(t,e){let r=!1;function n(i){if(r){Ua(t,i??xA());return}if(r=!0,e.pendingcb--,i){let o=e[Oa].splice(0);for(let s=0;s<o.length;s++)o[s](i);Ua(t,i,e.sync)}else Lh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,sc.nextTick($m,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function DD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,OD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Fm(t,e,r){Lh(e)&&(DD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,sc.nextTick((n,i)=>{Lh(i)?$m(n,i):i.pendingcb--},t,e)):Lh(e)&&(e.pendingcb++,$m(t,e))))}function $m(t,e){e.pendingcb--,e.finished=!0;let r=e[Oa].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()}}pD(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 kD=Mh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Oa].length)&&sc.nextTick(Vm,r),kD.call(this,t,e),this};it.prototype._undestroy=Mh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[wD.captureRejectionSymbol]=function(t){this.destroy(t)};var Km;function AA(){return Km===void 0&&(Km={}),Km}it.fromWeb=function(t,e){return AA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return AA().newWritableStreamFromStreamWritable(t)}});var $A=oe((VF,KA)=>{l();var jm=xi(),ND=Ar(),{isReadable:CD,isWritable:LD,isIterable:_A,isNodeStream:PD,isReadableNodeStream:BA,isWritableNodeStream:IA,isDuplexNodeStream:MD,isReadableStream:RA,isWritableStream:UA}=ti(),OA=Wi(),{AbortError:PA,codes:{ERR_INVALID_ARG_TYPE:KD,ERR_INVALID_RETURN_VALUE:DA}}=ir(),{destroyer:ka}=nc(),$D=ii(),MA=Dd(),HD=Kh(),{createDeferredPromise:kA}=Zt(),NA=Um(),CA=globalThis.Blob||ND.Blob,VD=typeof CA<"u"?function(e){return e instanceof CA}:function(e){return!1},qD=globalThis.AbortController||Sa().AbortController,{FunctionPrototypeCall:LA}=nt(),Fo=class extends $D{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)}};KA.exports=function t(e,r){if(MD(e))return e;if(BA(e))return Da({readable:e});if(IA(e))return Da({writable:e});if(PD(e))return Da({writable:!1,readable:!1});if(RA(e))return Da({readable:MA.fromWeb(e)});if(UA(e))return Da({writable:HD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=FD(e);if(_A(i))return NA(Fo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=LA(a,i,f=>{if(f!=null)throw new DA("nully","body",f)},f=>{ka(u,f)});return u=new Fo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,jm.nextTick(f,null)}catch(h){jm.nextTick(f,h)}})},destroy:c})}throw new DA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(VD(e))return t(e.arrayBuffer());if(_A(e))return NA(Fo,e,{objectMode:!0,writable:!1});if(RA(e?.readable)&&UA(e?.writable))return Fo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?BA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?IA(e?.writable)?e?.writable:t(e.writable):void 0;return Da({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return LA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{ka(i,o)}),i=new Fo({objectMode:!0,writable:!1,read(){}})}throw new KD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function FD(t){let{promise:e,resolve:r}=kA(),n=new qD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(jm.nextTick(u),a)return;if(i.aborted)throw new PA(void 0,{cause:i.reason});({promise:e,resolve:r}=kA()),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 Da(t){let e=t.readable&&typeof t.readable.read!="function"?MA.wrap(t.readable):t.readable,r=t.writable,n=!!CD(e),i=!!LD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new Fo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(OA(r,f=>{i=!1,f&&ka(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&&(OA(e,f=>{n=!1,f&&ka(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 PA),c=null,o=null,s=null,a===null?h(f):(a=h,ka(r,f),ka(e,f))},u}});var ii=oe((FF,qA)=>{"use strict";l();var{ObjectDefineProperties:jD,ObjectGetOwnPropertyDescriptor:Gi,ObjectKeys:WD,ObjectSetPrototypeOf:HA}=nt();qA.exports=Tn;var zm=Dd(),nn=Kh();HA(Tn.prototype,zm.prototype);HA(Tn,zm);{let t=WD(nn.prototype);for(let e=0;e<t.length;e++){let r=t[e];Tn.prototype[r]||(Tn.prototype[r]=nn.prototype[r])}}function Tn(t){if(!(this instanceof Tn))return new Tn(t);zm.call(this,t),nn.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}jD(Tn.prototype,{writable:{__proto__:null,...Gi(nn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Gi(nn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Gi(nn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Gi(nn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Gi(nn.prototype,"writableLength")},writableFinished:{__proto__:null,...Gi(nn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Gi(nn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Gi(nn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Gi(nn.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 Wm;function VA(){return Wm===void 0&&(Wm={}),Wm}Tn.fromWeb=function(t,e){return VA().newStreamDuplexFromReadableWritablePair(t,e)};Tn.toWeb=function(t){return VA().newReadableWritablePairFromDuplex(t)};var Gm;Tn.from=function(t){return Gm||(Gm=$A()),Gm(t,"body")}});var Zm=oe((WF,jA)=>{"use strict";l();var{ObjectSetPrototypeOf:FA,Symbol:GD}=nt();jA.exports=zi;var{ERR_METHOD_NOT_IMPLEMENTED:zD}=ir().codes,Jm=ii(),{getHighWaterMark:YD}=Rd();FA(zi.prototype,Jm.prototype);FA(zi,Jm);var Ld=GD("kCallback");function zi(t){if(!(this instanceof zi))return new zi(t);let e=t?YD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),Jm.call(this,t),this._readableState.sync=!1,this[Ld]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",JD)}function Ym(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 JD(){this._final!==Ym&&Ym.call(this)}zi.prototype._final=Ym;zi.prototype._transform=function(t,e,r){throw new zD("_transform()")};zi.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[Ld]=r})};zi.prototype._read=function(){if(this[Ld]){let t=this[Ld];this[Ld]=null,t()}}});var Qm=oe((zF,GA)=>{"use strict";l();var{ObjectSetPrototypeOf:WA}=nt();GA.exports=Na;var Xm=Zm();WA(Na.prototype,Xm.prototype);WA(Na,Xm);function Na(t){if(!(this instanceof Na))return new Na(t);Xm.call(this,t)}Na.prototype._transform=function(t,e,r){r(null,t)}});var qh=oe((JF,XA)=>{l();var Pd=xi(),{ArrayIsArray:ZD,Promise:XD,SymbolAsyncIterator:QD,SymbolDispose:e4}=nt(),Vh=Wi(),{once:t4}=Zt(),r4=nc(),zA=ii(),{aggregateTwoErrors:n4,codes:{ERR_INVALID_ARG_TYPE:aw,ERR_INVALID_RETURN_VALUE:ew,ERR_MISSING_ARGS:i4,ERR_STREAM_DESTROYED:o4,ERR_STREAM_PREMATURE_CLOSE:s4},AbortError:c4}=ir(),{validateFunction:a4,validateAbortSignal:u4}=Ta(),{isIterable:cc,isReadable:tw,isReadableNodeStream:Hh,isNodeStream:YA,isTransformStream:Ca,isWebStream:d4,isReadableStream:rw,isReadableFinished:f4}=ti(),l4=globalThis.AbortController||Sa().AbortController,nw,iw,ow;function JA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Vh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,r4.destroyer(t,o||new o4("pipe")))},cleanup:i}}function h4(t){return a4(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function sw(t){if(cc(t))return t;if(Hh(t))return p4(t);throw new aw("val",["Readable","Iterable","AsyncIterable"],t)}async function*p4(t){iw||(iw=Dd()),yield*iw.prototype[QD].call(t)}async function $h(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new XD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Vh(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?n4(i,u):u)}finally{a(),e.off("drain",s)}}async function cw(t,e,r,{end:n}){Ca(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 y4(...t){return ZA(t,t4(h4(t)))}function ZA(t,e,r){if(t.length===1&&ZD(t[0])&&(t=t[0]),t.length<2)throw new i4("streams");let n=new l4,i=n.signal,o=r?.signal,s=[];u4(o,"options.signal");function c(){g(new c4)}ow=ow||Zt().addAbortListener;let a;o&&(a=ow(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[e4](),n.abort(),O&&(u||s.forEach(M=>M()),Pd.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(YA(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var B=$;if(q){let{destroy:X,cleanup:Q}=JA(O,T,M);f.push(X),tw(O)&&j&&s.push(Q)}O.on("error",$),tw(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!cc(y))throw new ew("Iterable, AsyncIterable or Stream","source",y)}else cc(O)||Hh(O)||Ca(O)?y=O:y=zA.from(O);else if(typeof O=="function"){if(Ca(y)){var E;y=sw((E=y)===null||E===void 0?void 0:E.readable)}else y=sw(y);if(y=O(y,{signal:i}),T){if(!cc(y,!0))throw new ew("AsyncIterable",`transform[${A-1}]`,y)}else{var S;nw||(nw=Qm());let $=new nw({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(),Pd.nextTick(p)},_=>{$.destroy(_),Pd.nextTick(p,_)});else if(cc(y,!0))h++,$h(y,$,p,{end:q});else if(rw(y)||Ca(y)){let _=y.readable||y;h++,$h(_,$,p,{end:q})}else throw new ew("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=JA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(YA(O)){if(Hh(y)){h+=2;let $=g4(y,O,p,{end:q});tw(O)&&j&&s.push($)}else if(Ca(y)||rw(y)){let $=y.readable||y;h++,$h($,O,p,{end:q})}else if(cc(y))h++,$h(y,O,p,{end:q});else throw new aw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(d4(O)){if(Hh(y))h++,cw(sw(y),O,p,{end:q});else if(rw(y)||cc(y))h++,cw(y,O,p,{end:q});else if(Ca(y))h++,cw(y.readable,O,p,{end:q});else throw new aw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=zA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Pd.nextTick(c),y}function g4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new s4)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;f4(t)?Pd.nextTick(s):t.once("end",s)}else r();return Vh(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)}),Vh(e,{readable:!1,writable:!0},r)}XA.exports={pipelineImpl:ZA,pipeline:y4}});var dw=oe((XF,iT)=>{"use strict";l();var{pipeline:m4}=qh(),Fh=ii(),{destroyer:w4}=nc(),{isNodeStream:jh,isReadable:QA,isWritable:eT,isWebStream:uw,isTransformStream:ac,isWritableStream:tT,isReadableStream:rT}=ti(),{AbortError:b4,codes:{ERR_INVALID_ARG_VALUE:nT,ERR_MISSING_ARGS:x4}}=ir(),E4=Wi();iT.exports=function(...e){if(e.length===0)throw new x4("streams");if(e.length===1)return Fh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Fh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Fh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!jh(e[p])&&!uw(e[p]))){if(p<e.length-1&&!(QA(e[p])||rT(e[p])||ac(e[p])))throw new nT(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(eT(e[p])||tT(e[p])||ac(e[p])))throw new nT(`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=m4(e,a),f=!!(eT(u)||tT(u)||ac(u)),h=!!(QA(d)||rT(d)||ac(d));if(c=new Fh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(jh(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(uw(u)){let y=(ac(u)?u.writable:u).getWriter();c._write=async function(E,S,B){try{await y.ready,y.write(E).catch(()=>{}),B()}catch(A){B(A)}},c._final=async function(E){try{await y.ready,y.close().catch(()=>{}),i=E}catch(S){E(S)}}}let p=ac(d)?d.readable:d;E4(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(jh(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(uw(d)){let g=(ac(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 b4),o=null,n=null,i=null,s===null?g(p):(s=g,jh(d)&&w4(d,p))},c}});var pT=oe((ej,hw)=>{"use strict";l();var v4=globalThis.AbortController||Sa().AbortController,{codes:{ERR_INVALID_ARG_VALUE:S4,ERR_INVALID_ARG_TYPE:Md,ERR_MISSING_ARGS:A4,ERR_OUT_OF_RANGE:T4},AbortError:oi}=ir(),{validateAbortSignal:uc,validateInteger:oT,validateObject:dc}=Ta(),_4=nt().Symbol("kWeak"),B4=nt().Symbol("kResistStopPropagation"),{finished:I4}=Wi(),R4=dw(),{addAbortSignalNoValidate:U4}=Id(),{isWritable:O4,isNodeStream:D4}=ti(),{deprecate:k4}=Zt(),{ArrayPrototypePush:N4,Boolean:C4,MathFloor:sT,Number:L4,NumberIsNaN:P4,Promise:cT,PromiseReject:aT,PromiseResolve:M4,PromisePrototypeThen:uT,Symbol:fT}=nt(),Wh=fT("kEmpty"),dT=fT("kEof");function K4(t,e){if(e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),D4(t)&&!O4(t))throw new S4("stream",t,"must be writable");let r=R4(this,t);return e!=null&&e.signal&&U4(e.signal,r),r}function Gh(t,e){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=sT(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=sT(e.highWaterMark)),oT(r,"options.concurrency",1),oT(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Zt().AbortSignalAny([e?.signal].filter(C4)),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 oi;try{if(S=t(S,a),S===Wh)continue;S=M4(S)}catch(B){S=aT(B)}h+=1,uT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new cT(B=>{d=B})}c.push(dT)}catch(S){let B=aT(S);uT(B,g,p),c.push(B)}finally{f=!0,u&&(u(),u=null)}}E();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===dT)return;if(o.aborted)throw new oi;S!==Wh&&(yield S),c.shift(),y()}await new cT(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function $4(t=void 0){return t!=null&&dc(t,"options"),t?.signal!=null&&uc(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 oi({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function lT(t,e=void 0){for await(let r of lw.call(this,t,e))return!0;return!1}async function H4(t,e=void 0){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);return!await lT.call(this,async(...r)=>!await t(...r),e)}async function V4(t,e){for await(let r of lw.call(this,t,e))return r}async function q4(t,e){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Wh}for await(let n of Gh.call(this,r,e));}function lw(t,e){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:Wh}return Gh.call(this,r,e)}var fw=class extends A4{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function F4(t,e,r){var n;if(typeof t!="function")throw new Md("reducer",["Function","AsyncFunction"],t);r!=null&&dc(r,"options"),r?.signal!=null&&uc(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new oi(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await I4(this.destroy(u)),u}let o=new v4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[_4]:this,[B4]:!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 oi;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new fw}finally{o.abort()}return e}async function j4(t){t!=null&&dc(t,"options"),t?.signal!=null&&uc(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 oi(void 0,{cause:t.signal.reason});N4(e,n)}return e}function W4(t,e){let r=Gh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function hT(t){if(t=L4(t),P4(t))return 0;if(t<0)throw new T4("number",">= 0",t);return t}function G4(t,e=void 0){return e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),t=hT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new oi;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new oi;t--<=0&&(yield o)}}).call(this)}function z4(t,e=void 0){return e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),t=hT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new oi;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new oi;if(t-- >0&&(yield o),t<=0)return}}).call(this)}hw.exports.streamReturningOperators={asIndexedPairs:k4($4,"readable.asIndexedPairs will be removed in a future version."),drop:G4,filter:lw,flatMap:W4,map:Gh,take:z4,compose:K4};hw.exports.promiseReturningOperators={every:H4,forEach:q4,reduce:F4,toArray:j4,some:lT,find:V4}});var pw=oe((rj,yT)=>{"use strict";l();var{ArrayPrototypePop:Y4,Promise:J4}=nt(),{isIterable:Z4,isNodeStream:X4,isWebStream:Q4}=ti(),{pipelineImpl:ek}=qh(),{finished:tk}=Wi();yw();function rk(...t){return new J4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!X4(o)&&!Z4(o)&&!Q4(o)){let s=Y4(t);n=s.signal,i=s.end}ek(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}yT.exports={finished:tk,pipeline:rk}});var yw=oe((ij,AT)=>{l();var{Buffer:nk}=Ar(),{ObjectDefineProperty:Yi,ObjectKeys:wT,ReflectApply:bT}=nt(),{promisify:{custom:xT}}=Zt(),{streamReturningOperators:gT,promiseReturningOperators:mT}=pT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:ET}}=ir(),ik=dw(),{setDefaultHighWaterMark:ok,getDefaultHighWaterMark:sk}=Rd(),{pipeline:vT}=qh(),{destroyer:ck}=nc(),ST=Wi(),gw=pw(),Kd=ti(),We=AT.exports=_h().Stream;We.isDestroyed=Kd.isDestroyed;We.isDisturbed=Kd.isDisturbed;We.isErrored=Kd.isErrored;We.isReadable=Kd.isReadable;We.isWritable=Kd.isWritable;We.Readable=Dd();for(let t of wT(gT)){let r=function(...n){if(new.target)throw ET();return We.Readable.from(bT(e,this,n))};mw=r;let e=gT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var mw;for(let t of wT(mT)){let r=function(...i){if(new.target)throw ET();return bT(e,this,i)};mw=r;let e=mT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var mw;We.Writable=Kh();We.Duplex=ii();We.Transform=Zm();We.PassThrough=Qm();We.pipeline=vT;var{addAbortSignal:ak}=Id();We.addAbortSignal=ak;We.finished=ST;We.destroy=ck;We.compose=ik;We.setDefaultHighWaterMark=ok;We.getDefaultHighWaterMark=sk;Yi(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return gw}});Yi(vT,xT,{__proto__:null,enumerable:!0,get(){return gw.pipeline}});Yi(ST,xT,{__proto__:null,enumerable:!0,get(){return gw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return nk.from(e.buffer,e.byteOffset,e.byteLength)}});var ww=oe((sj,lt)=>{"use strict";l();var At=yw(),uk=pw(),dk=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=dk;lt.exports.pipeline=At.pipeline;lt.exports.compose=At.compose;Object.defineProperty(At,"promises",{configurable:!0,enumerable:!0,get(){return uk}});lt.exports.Stream=At.Stream;lt.exports.default=lt.exports});var W_=oe((Cp,j_)=>{l();(function(t,e){typeof Cp=="object"&&typeof j_<"u"?e(Cp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Cp,function(t){"use strict";function e(){for(var I=arguments.length,v=Array(I),k=0;k<I;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(I){return"(?:"+I+")"}function n(I){return I===void 0?"undefined":I===null?"null":Object.prototype.toString.call(I).split(" ").pop().split("]").shift().toLowerCase()}function i(I){return I.toUpperCase()}function o(I){return I!=null?I instanceof Array?I:typeof I.length!="number"||I.split||I.setInterval||I.call?[I]:Array.prototype.slice.call(I):[]}function s(I,v){var k=I;if(v)for(var K in v)k[K]=v[K];return k}function c(I){var v="[A-Za-z]",k="[\\x0D]",K="[0-9]",H="[\\x22]",te=e(K,"[A-Fa-f]"),fe="[\\x0A]",ve="[\\x20]",Ue=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),pt="[\\:\\/\\?\\#\\[\\]\\@]",Ee="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(pt,Ee),yt=I?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=I?"[\\uE000-\\uF8FF]":"[]",Ae=e(v,K,"[\\-\\.\\_\\~]",yt),rt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(Ue+"|"+e(Ae,Ee,"[\\:]"))+"*"),ds=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),vr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Gr=r(vr+"\\."+vr+"\\."+vr+"\\."+vr),Ke=r(te+"{1,4}"),Sr=r(r(Ke+"\\:"+Ke)+"|"+Gr),zr=r(r(Ke+"\\:")+"{6}"+Sr),Ln=r("\\:\\:"+r(Ke+"\\:")+"{5}"+Sr),fs=r(r(Ke)+"?\\:\\:"+r(Ke+"\\:")+"{4}"+Sr),pi=r(r(r(Ke+"\\:")+"{0,1}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{3}"+Sr),yu=r(r(r(Ke+"\\:")+"{0,2}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{2}"+Sr),_f=r(r(r(Ke+"\\:")+"{0,3}"+Ke)+"?\\:\\:"+Ke+"\\:"+Sr),Bf=r(r(r(Ke+"\\:")+"{0,4}"+Ke)+"?\\:\\:"+Sr),Ac=r(r(r(Ke+"\\:")+"{0,5}"+Ke)+"?\\:\\:"+Ke),Tc=r(r(r(Ke+"\\:")+"{0,6}"+Ke)+"?\\:\\:"),yi=r([zr,Ln,fs,pi,yu,_f,Bf,Ac,Tc].join("|")),_c=r(r(Ae+"|"+Ue)+"+"),iy=r(yi+"\\%25"+_c),ls=r(yi+r("\\%25|\\%(?!"+te+"{2})")+_c),dI=r("[vV]"+te+"+\\."+e(Ae,Ee,"[\\:]")+"+"),fI=r("\\["+r(ls+"|"+yi+"|"+dI)+"\\]"),fx=r(r(Ue+"|"+e(Ae,Ee))+"*"),gu=r(fI+"|"+Gr+"(?!"+fx+")|"+fx),mu=r(K+"*"),lx=r(r(Ne+"@")+"?"+gu+r("\\:"+mu)+"?"),wu=r(Ue+"|"+e(Ae,Ee,"[\\:\\@]")),lI=r(wu+"*"),hx=r(wu+"+"),hI=r(r(Ue+"|"+e(Ae,Ee,"[\\@]"))+"+"),gi=r(r("\\/"+lI)+"*"),Bc=r("\\/"+r(hx+gi)+"?"),oy=r(hI+gi),If=r(hx+gi),Ic="(?!"+wu+")",kL=r(gi+"|"+Bc+"|"+oy+"|"+If+"|"+Ic),Rc=r(r(wu+"|"+e("[\\/\\?]",Ze))+"*"),bu=r(r(wu+"|[\\/\\?]")+"*"),px=r(r("\\/\\/"+lx+gi)+"|"+Bc+"|"+If+"|"+Ic),pI=r(rt+"\\:"+px+r("\\?"+Rc)+"?"+r("\\#"+bu)+"?"),yI=r(r("\\/\\/"+lx+gi)+"|"+Bc+"|"+oy+"|"+Ic),gI=r(yI+r("\\?"+Rc)+"?"+r("\\#"+bu)+"?"),NL=r(pI+"|"+gI),CL=r(rt+"\\:"+px+r("\\?"+Rc)+"?"),LL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+gu+")"+r("\\:("+mu+")")+"?)")+"?("+gi+"|"+Bc+"|"+If+"|"+Ic+")")+r("\\?("+Rc+")")+"?"+r("\\#("+bu+")")+"?$",PL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+gu+")"+r("\\:("+mu+")")+"?)")+"?("+gi+"|"+Bc+"|"+oy+"|"+Ic+")")+r("\\?("+Rc+")")+"?"+r("\\#("+bu+")")+"?$",ML="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+gu+")"+r("\\:("+mu+")")+"?)")+"?("+gi+"|"+Bc+"|"+If+"|"+Ic+")")+r("\\?("+Rc+")")+"?$",KL="^"+r("\\#("+bu+")")+"?$",$L="^"+r("("+Ne+")@")+"?("+gu+")"+r("\\:("+mu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ae,Ee),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ae,Ee),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ae,Ee),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ae,Ee),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]",Ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ae,Ee),"g"),UNRESERVED:new RegExp(Ae,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ae,tt),"g"),PCT_ENCODED:new RegExp(Ue,"g"),IPV4ADDRESS:new RegExp("^("+Gr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+yi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+_c+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function I(v,k){var K=[],H=!0,te=!1,fe=void 0;try{for(var ve=v[Symbol.iterator](),Ue;!(H=(Ue=ve.next()).done)&&(K.push(Ue.value),!(k&&K.length===k));H=!0);}catch(pt){te=!0,fe=pt}finally{try{!H&&ve.return&&ve.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 I(v,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(I){if(Array.isArray(I)){for(var v=0,k=Array(I.length);v<I.length;v++)k[v]=I[v];return k}else return Array.from(I)},h=2147483647,p=36,g=1,y=26,E=38,S=700,B=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(I){throw new RangeError(j[I])}function _(I,v){for(var k=[],K=I.length;K--;)k[K]=v(I[K]);return k}function D(I,v){var k=I.split("@"),K="";k.length>1&&(K=k[0]+"@",I=k[1]),I=I.replace(q,".");var H=I.split("."),te=_(H,v).join(".");return K+te}function x(I){for(var v=[],k=0,K=I.length;k<K;){var H=I.charCodeAt(k++);if(H>=55296&&H<=56319&&k<K){var te=I.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=B,ve=v.lastIndexOf(O);ve<0&&(ve=0);for(var Ue=0;Ue<ve;++Ue)v.charCodeAt(Ue)>=128&&G("not-basic"),k.push(v.charCodeAt(Ue));for(var pt=ve>0?ve+1:0;pt<K;){for(var Ee=H,tt=1,yt=p;;yt+=p){pt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(pt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Ae=yt<=fe?g:yt>=fe+y?y:yt-fe;if(Ze<Ae)break;var rt=p-Ae;tt>X(h/rt)&&G("overflow"),tt*=rt}var Ne=k.length+1;fe=R(H-Ee,Ne,Ee==0),X(H/Ne)>h-te&&G("overflow"),te+=X(H/Ne),H%=Ne,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=B,ve=!0,Ue=!1,pt=void 0;try{for(var Ee=v[Symbol.iterator](),tt;!(ve=(tt=Ee.next()).done);ve=!0){var yt=tt.value;yt<128&&k.push(Q(yt))}}catch(ls){Ue=!0,pt=ls}finally{try{!ve&&Ee.return&&Ee.return()}finally{if(Ue)throw pt}}var Ze=k.length,Ae=Ze;for(Ze&&k.push(O);Ae<K;){var rt=h,Ne=!0,ds=!1,vr=void 0;try{for(var Gr=v[Symbol.iterator](),Ke;!(Ne=(Ke=Gr.next()).done);Ne=!0){var Sr=Ke.value;Sr>=H&&Sr<rt&&(rt=Sr)}}catch(ls){ds=!0,vr=ls}finally{try{!Ne&&Gr.return&&Gr.return()}finally{if(ds)throw vr}}var zr=Ae+1;rt-H>X((h-te)/zr)&&G("overflow"),te+=(rt-H)*zr,H=rt;var Ln=!0,fs=!1,pi=void 0;try{for(var yu=v[Symbol.iterator](),_f;!(Ln=(_f=yu.next()).done);Ln=!0){var Bf=_f.value;if(Bf<H&&++te>h&&G("overflow"),Bf==H){for(var Ac=te,Tc=p;;Tc+=p){var yi=Tc<=fe?g:Tc>=fe+y?y:Tc-fe;if(Ac<yi)break;var _c=Ac-yi,iy=p-yi;k.push(Q(N(yi+_c%iy,0))),Ac=X(_c/iy)}k.push(Q(N(Ac,0))),fe=R(te,zr,Ae==Ze),te=0,++Ae}}}catch(ls){fs=!0,pi=ls}finally{try{!Ln&&yu.return&&yu.return()}finally{if(fs)throw pi}}++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(I){var v=I.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(I){for(var v="",k=0,K=I.length;k<K;){var H=parseInt(I.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(I.substr(k+4,2),16);v+=String.fromCharCode((H&31)<<6|te&63)}else v+=I.substr(k,6);k+=6}else if(H>=224){if(K-k>=9){var fe=parseInt(I.substr(k+4,2),16),ve=parseInt(I.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|ve&63)}else v+=I.substr(k,9);k+=9}else v+=I.substr(k,3),k+=3}return v}function ue(I,v){function k(K){var H=Z(K);return H.match(v.UNRESERVED)?H:K}return I.scheme&&(I.scheme=String(I.scheme).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_SCHEME,"")),I.userinfo!==void 0&&(I.userinfo=String(I.userinfo).replace(v.PCT_ENCODED,k).replace(v.NOT_USERINFO,Y).replace(v.PCT_ENCODED,i)),I.host!==void 0&&(I.host=String(I.host).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_HOST,Y).replace(v.PCT_ENCODED,i)),I.path!==void 0&&(I.path=String(I.path).replace(v.PCT_ENCODED,k).replace(I.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Y).replace(v.PCT_ENCODED,i)),I.query!==void 0&&(I.query=String(I.query).replace(v.PCT_ENCODED,k).replace(v.NOT_QUERY,Y).replace(v.PCT_ENCODED,i)),I.fragment!==void 0&&(I.fragment=String(I.fragment).replace(v.PCT_ENCODED,k).replace(v.NOT_FRAGMENT,Y).replace(v.PCT_ENCODED,i)),I}function ee(I){return I.replace(/^0*(.*)/,"$1")||"0"}function ce(I,v){var k=I.match(v.IPV4ADDRESS)||[],K=d(k,2),H=K[1];return H?H.split(".").map(ee).join("."):I}function Re(I,v){var k=I.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var fe=H.toLowerCase().split("::").reverse(),ve=d(fe,2),Ue=ve[0],pt=ve[1],Ee=pt?pt.split(":").map(ee):[],tt=Ue.split(":").map(ee),yt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=yt?7:8,Ae=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=Ee[Ne]||tt[Ae+Ne]||"";yt&&(rt[Ze-1]=ce(rt[Ze-1],v));var ds=rt.reduce(function(zr,Ln,fs){if(!Ln||Ln==="0"){var pi=zr[zr.length-1];pi&&pi.index+pi.length===fs?pi.length++:zr.push({index:fs,length:1})}return zr},[]),vr=ds.sort(function(zr,Ln){return Ln.length-zr.length})[0],Gr=void 0;if(vr&&vr.length>1){var Ke=rt.slice(0,vr.index),Sr=rt.slice(vr.index+vr.length);Gr=Ke.join(":")+"::"+Sr.join(":")}else Gr=rt.join(":");return te&&(Gr+="%"+te),Gr}else return I}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function wt(I){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},K=v.iri!==!1?u:a;v.reference==="suffix"&&(I=(v.scheme?v.scheme+":":"")+"//"+I);var H=I.match(Me);if(H){Je?(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=I.indexOf("@")!==-1?H[3]:void 0,k.host=I.indexOf("//")!==-1?H[4]:void 0,k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=I.indexOf("?")!==-1?H[7]:void 0,k.fragment=I.indexOf("#")!==-1?H[8]:void 0,isNaN(k.port)&&(k.port=I.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?H[4]:void 0)),k.host&&(k.host=Re(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 hi(I,v){var k=v.iri!==!1?u:a,K=[];return I.userinfo!==void 0&&(K.push(I.userinfo),K.push("@")),I.host!==void 0&&K.push(Re(ce(String(I.host),k),k).replace(k.IPV6ADDRESS,function(H,te,fe){return"["+te+(fe?"%25"+fe:"")+"]"})),(typeof I.port=="number"||typeof I.port=="string")&&(K.push(":"),K.push(String(I.port))),K.length?K.join(""):void 0}var lo=/^\.\.?\//,fu=/^\/\.(\/|$)/,xf=/^\/\.\.(\/|$)/,ty=/^\/?(?:.|\n)*?(?=\/|$)/;function ho(I){for(var v=[];I.length;)if(I.match(lo))I=I.replace(lo,"");else if(I.match(fu))I=I.replace(fu,"/");else if(I.match(xf))I=I.replace(xf,"/"),v.pop();else if(I==="."||I==="..")I="";else{var k=I.match(ty);if(k){var K=k[0];I=I.slice(K.length),v.push(K)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function jr(I){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=v.iri?u:a,K=[],H=W[(v.scheme||I.scheme||"").toLowerCase()];if(H&&H.serialize&&H.serialize(I,v),I.host&&!k.IPV6ADDRESS.test(I.host)){if(v.domainHost||H&&H.domainHost)try{I.host=v.iri?z.toUnicode(I.host):z.toASCII(I.host.replace(k.PCT_ENCODED,Z).toLowerCase())}catch(ve){I.error=I.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+ve}}ue(I,k),v.reference!=="suffix"&&I.scheme&&(K.push(I.scheme),K.push(":"));var te=hi(I,v);if(te!==void 0&&(v.reference!=="suffix"&&K.push("//"),K.push(te),I.path&&I.path.charAt(0)!=="/"&&K.push("/")),I.path!==void 0){var fe=I.path;!v.absolutePath&&(!H||!H.absolutePath)&&(fe=ho(fe)),te===void 0&&(fe=fe.replace(/^\/\//,"/%2F")),K.push(fe)}return I.query!==void 0&&(K.push("?"),K.push(I.query)),I.fragment!==void 0&&(K.push("#"),K.push(I.fragment)),K.join("")}function lu(I,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(I=wt(jr(I,k),k),v=wt(jr(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=ho(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=ho(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=ho(v.path):((I.userinfo!==void 0||I.host!==void 0||I.port!==void 0)&&!I.path?H.path="/"+v.path:I.path?H.path=I.path.slice(0,I.path.lastIndexOf("/")+1)+v.path:H.path=v.path,H.path=ho(H.path)),H.query=v.query):(H.path=I.path,v.query!==void 0?H.query=v.query:H.query=I.query),H.userinfo=I.userinfo,H.host=I.host,H.port=I.port),H.scheme=I.scheme),H.fragment=v.fragment,H}function Ef(I,v,k){var K=s({scheme:"null"},k);return jr(lu(wt(I,K),wt(v,K),K,!0),K)}function hu(I,v){return typeof I=="string"?I=jr(wt(I,v),v):n(I)==="object"&&(I=wt(jr(I,v),v)),I}function vf(I,v,k){return typeof I=="string"?I=jr(wt(I,k),k):n(I)==="object"&&(I=jr(I,k)),typeof v=="string"?v=jr(wt(v,k),k):n(v)==="object"&&(v=jr(v,k)),I===v}function Sf(I,v){return I&&I.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function Wr(I,v){return I&&I.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var po={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}},pu={scheme:"https",domainHost:po.domainHost,parse:po.parse,serialize:po.serialize};function Af(I){return typeof I.secure=="boolean"?I.secure:String(I.scheme).toLowerCase()==="wss"}var us={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=Af(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===(Af(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}},Tf={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},ry={},QB=!0,sx="[A-Za-z0-9\\-\\.\\_\\~"+(QB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",eI=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),tI="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",rI="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",nI=e(rI,'[\\"\\\\]'),iI="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",oI=new RegExp(sx,"g"),Sc=new RegExp(eI,"g"),sI=new RegExp(e("[^]",tI,"[\\.]",'[\\"]',nI),"g"),cx=new RegExp(e("[^]",sx,iI),"g"),cI=cx;function ny(I){var v=Z(I);return v.match(oI)?v:I}var ax={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={},ve=K.query.split("&"),Ue=0,pt=ve.length;Ue<pt;++Ue){var Ee=ve[Ue].split("=");switch(Ee[0]){case"to":for(var tt=Ee[1].split(","),yt=0,Ze=tt.length;yt<Ze;++yt)H.push(tt[yt]);break;case"subject":K.subject=Wr(Ee[1],k);break;case"body":K.body=Wr(Ee[1],k);break;default:te=!0,fe[Wr(Ee[0],k)]=Wr(Ee[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Ae=0,rt=H.length;Ae<rt;++Ae){var Ne=H[Ae].split("@");if(Ne[0]=Wr(Ne[0]),k.unicodeSupport)Ne[1]=Wr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(Wr(Ne[1],k).toLowerCase())}catch(ds){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ds}H[Ae]=Ne.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 ve=String(H[te]),Ue=ve.lastIndexOf("@"),pt=ve.slice(0,Ue).replace(Sc,ny).replace(Sc,i).replace(sI,Y),Ee=ve.slice(Ue+1);try{Ee=k.iri?z.toUnicode(Ee):z.toASCII(Wr(Ee,k).toLowerCase())}catch(Ae){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ae}H[te]=pt+"@"+Ee}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var yt=[];for(var Ze in tt)tt[Ze]!==ry[Ze]&&yt.push(Ze.replace(Sc,ny).replace(Sc,i).replace(cx,Y)+"="+tt[Ze].replace(Sc,ny).replace(Sc,i).replace(cI,Y));return yt.length&&(K.query=yt.join("&")),K}},aI=/^([^\:]+)\:(.*)/,ux={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(aI),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),ve=K[2],Ue=te+":"+(k.nid||fe),pt=W[Ue];H.nid=fe,H.nss=ve,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 ve=v,Ue=v.nss;return ve.path=(H||k.nid)+":"+Ue,ve}},uI=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,dx={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(uI))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[po.scheme]=po,W[pu.scheme]=pu,W[us.scheme]=us,W[Tf.scheme]=Tf,W[ax.scheme]=ax,W[ux.scheme]=ux,W[dx.scheme]=dx,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=wt,t.removeDotSegments=ho,t.serialize=jr,t.resolveComponents=lu,t.resolve=Ef,t.normalize=hu,t.equal=vf,t.escapeComponent=Sf,t.unescapeComponent=Wr,Object.defineProperty(t,"__esModule",{value:!0})})});var z_=oe((DZ,G_)=>{"use strict";l();G_.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 cB=oe((CQ,sB)=>{l();var tu=1e3,ru=tu*60,nu=ru*60,mc=nu*24,jC=mc*7,WC=mc*365.25;sB.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return GC(t);if(r==="number"&&isFinite(t))return e.long?YC(t):zC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function GC(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*WC;case"weeks":case"week":case"w":return r*jC;case"days":case"day":case"d":return r*mc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*nu;case"minutes":case"minute":case"mins":case"min":case"m":return r*ru;case"seconds":case"second":case"secs":case"sec":case"s":return r*tu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function zC(t){var e=Math.abs(t);return e>=mc?Math.round(t/mc)+"d":e>=nu?Math.round(t/nu)+"h":e>=ru?Math.round(t/ru)+"m":e>=tu?Math.round(t/tu)+"s":t+"ms"}function YC(t){var e=Math.abs(t);return e>=mc?$p(t,e,mc,"day"):e>=nu?$p(t,e,nu,"hour"):e>=ru?$p(t,e,ru,"minute"):e>=tu?$p(t,e,tu,"second"):t+" ms"}function $p(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var DL={};xu(DL,{AggregateBeaconError:()=>U0,Appendix:()=>Er,BECH32M_CHARS:()=>BL,BTCR2_DID_DOCUMENT_CONTEXT:()=>zB,BeaconError:()=>zt,BeaconFactory:()=>Cs,BeaconSignalDiscovery:()=>Qb,BeaconUtils:()=>Vr,CASBeacon:()=>zu,CASBeaconError:()=>O0,CHANGE_OUTPUT_VBYTES:()=>L0,DEFAULT_FEE_ESTIMATOR:()=>Ol,DID_REGEX:()=>YB,DUST_LIMIT_SATS:()=>P0,DidBtcr2:()=>bf,DidDocument:()=>Fr,DidDocumentBuilder:()=>ox,DidVerificationMethod:()=>Qp,GenesisDocument:()=>ey,ID_PLACEHOLDER_VALUE:()=>qr,Identifier:()=>ur,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>vc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Ec,P2PKH_BEACON_TX_VSIZE:()=>Uv,P2TR_BEACON_TX_VSIZE:()=>Iv,P2WPKH_BEACON_TX_VSIZE:()=>Rv,Resolver:()=>fo,SINGLETON_BEACON_TX_VSIZE:()=>Ov,SMTBeacon:()=>rd,SMTBeaconError:()=>ta,SPENDABLE_DUST_LIMIT_SATS:()=>Dl,SinglePartyBeacon:()=>Ni,SingletonBeacon:()=>Yu,SingletonBeaconError:()=>R0,StaticFeeEstimator:()=>ra,Updater:()=>wf,beaconTxVsize:()=>M0,buildAggregationBeaconTx:()=>t6,deriveSingletonAddress:()=>Dv,detectSingletonScriptKind:()=>K0,extractOpReturnSignalHash:()=>Xb,getAggregationCommunicationKey:()=>XB,isMultikeyVerificationMethod:()=>JB,opReturnScript:()=>H0,resolveBtcr2SenderPk:()=>OL,resolveChangeAddress:()=>$0,selectSpendableUtxo:()=>Nv});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 Eu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hn(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 Nf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Eu(t.outputLen),Eu(t.blockLen)}function Nc(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 Px(t,e){hn(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 Cf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function pn(t,e){return t<<32-e|t>>>e}function vu(t,e){return t<<e|t>>>32-e>>>0}var Mx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",r8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ct(t){if(hn(t),Mx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=r8[t[r]];return e}var Ei={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lx(t){if(t>=Ei._0&&t<=Ei._9)return t-Ei._0;if(t>=Ei.A&&t<=Ei.F)return t-(Ei.A-10);if(t>=Ei.a&&t<=Ei.f)return t-(Ei.a-10)}function Tr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Mx)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=Lx(t.charCodeAt(o)),c=Lx(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 Su(t){return typeof t=="string"&&(t=ws(t)),hn(t),t}function ut(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];hn(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 kc=class{};function Lf(t){let e=n=>t().update(Su(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function _r(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 n8(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 my(t,e,r){return t&e^~t&r}function wy(t,e,r){return t&e^t&r^e&r}var Cc=class extends kc{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=Cf(this.buffer)}update(e){Nc(this),e=Su(e),hn(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=Cf(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){Nc(this),Px(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;n8(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Cf(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()}},vi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var i8=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]),yo=new Uint32Array(64),by=class extends Cc{constructor(e=32){super(64,e,8,!1),this.A=vi[0]|0,this.B=vi[1]|0,this.C=vi[2]|0,this.D=vi[3]|0,this.E=vi[4]|0,this.F=vi[5]|0,this.G=vi[6]|0,this.H=vi[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)yo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=yo[f-15],p=yo[f-2],g=pn(h,7)^pn(h,18)^h>>>3,y=pn(p,17)^pn(p,19)^p>>>10;yo[f]=y+yo[f-7]+g+yo[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=pn(c,6)^pn(c,11)^pn(c,25),p=d+h+my(c,a,u)+i8[f]+yo[f]|0,y=(pn(n,2)^pn(n,13)^pn(n,22))+wy(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(yo)}destroy(){this.set(0,0,0,0,0,0,0,0),Vn(this.buffer)}};var ke=Lf(()=>new by);l();l();l();var Pf=class extends kc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Nf(e);let n=Su(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 Nc(this),this.iHash.update(e),this}digestInto(e){Nc(this),hn(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()}},xy=(t,e,r)=>new Pf(t,e).update(r).digest();xy.create=(t,e)=>new Pf(t,e);l();var Sy=BigInt(0),vy=BigInt(1);function Au(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function go(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 Tu(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Kx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Sy:BigInt("0x"+t)}function Si(t){return Kx(Ct(t))}function Ay(t){return hn(t),Kx(Ct(Uint8Array.from(t).reverse()))}function Lc(t,e){return Tr(t.toString(16).padStart(e*2,"0"))}function Ty(t,e){return Lc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=Tr(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 _u(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 Ey=t=>typeof t=="bigint"&&Sy<=t;function Bu(t,e,r){return Ey(t)&&Ey(e)&&Ey(r)&&e<=t&&t<r}function $x(t,e,r,n){if(!Bu(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mf(t){let e;for(e=0;t>Sy;t>>=vy,e+=1);return e}var mo=t=>(vy<<BigInt(t))-vy;function Hx(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 Iu(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 _y(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 tr=BigInt(0),qt=BigInt(1),bs=BigInt(2),Fx=BigInt(3),jx=BigInt(4),Wx=BigInt(5),o8=BigInt(7),Gx=BigInt(8),s8=BigInt(9),zx=BigInt(16);function Br(t,e){let r=t%e;return r>=tr?r:e+r}function Ir(t,e,r){let n=t;for(;e-- >tr;)n*=n,n%=r;return n}function Vx(t,e){if(t===tr)throw new Error("invert: expected non-zero number");if(e<=tr)throw new Error("invert: expected positive modulus, got "+e);let r=Br(t,e),n=e,i=tr,o=qt,s=qt,c=tr;for(;r!==tr;){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 Br(i,e)}function By(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Yx(t,e){let r=(t.ORDER+qt)/jx,n=t.pow(e,r);return By(t,n,e),n}function c8(t,e){let r=(t.ORDER-Wx)/Gx,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 By(t,c,e),c}function a8(t){let e=wo(t),r=Jx(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+o8)/zx;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 By(c,E,a),E}}function Jx(t){if(t<Fx)throw new Error("sqrt is not defined for small field");let e=t-qt,r=0;for(;e%bs===tr;)e/=bs,r++;let n=bs,i=wo(t);for(;qx(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Yx;let o=i.pow(n,e),s=(e+qt)/bs;return function(a,u){if(a.is0(u))return u;if(qx(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 u8(t){return t%jx===Fx?Yx:t%Gx===Wx?c8:t%zx===s8?a8(t):Jx(t)}var d8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Iy(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=d8.reduce((n,i)=>(n[i]="function",n),e);return Iu(t,r),t}function f8(t,e,r){if(r<tr)throw new Error("invalid exponent, negatives unsupported");if(r===tr)return t.ONE;if(r===qt)return e;let n=t.ONE,i=e;for(;r>tr;)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 qx(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 $f(t,e){e!==void 0&&Eu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function wo(t,e,r=!1,n={}){if(t<=tr)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}=$f(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:mo(a),ZERO:tr,ONE:qt,allowedLengths:c,create:h=>Br(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return tr<=h&&h<t},is0:h=>h===tr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&qt)===qt,neg:h=>Br(-h,t),eql:(h,p)=>h===p,sqr:h=>Br(h*h,t),add:(h,p)=>Br(h+p,t),sub:(h,p)=>Br(h-p,t),mul:(h,p)=>Br(h*p,t),pow:(h,p)=>f8(f,h,p),div:(h,p)=>Br(h*Vx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Vx(h,t),sqrt:o||(h=>(d||(d=u8(t)),d(f,h))),toBytes:h=>r?Ty(h,u):Lc(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?Ay(h):Si(h);if(s&&(g=Br(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 Zx(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 Ry(t){let e=Zx(t);return e+Math.ceil(e/2)}function Hf(t,e,r=!1){let n=t.length,i=Zx(e),o=Ry(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Ay(t):Si(t),c=Br(s,e-qt)+qt;return r?Ty(c,i):Lc(c,i)}var Pc=BigInt(0),xs=BigInt(1);function Ru(t,e){let r=e.negate();return t?r:e}function qf(t,e){let r=Kf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function tE(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Uy(t,e){tE(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=mo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Xx(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 l8(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 h8(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 Oy=new WeakMap,rE=new WeakMap;function Dy(t){return rE.get(t)||1}function Qx(t){if(t!==Pc)throw new Error("invalid wNAF")}var Vf=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>Pc;)r&xs&&(n=n.add(i)),i=i.double(),r>>=xs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Uy(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=Uy(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Xx(n,c,s);n=a,d?o=o.add(Ru(h,r[p])):i=i.add(Ru(f,r[u]))}return Qx(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Uy(e,this.bits);for(let s=0;s<o.windows&&n!==Pc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Xx(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return Qx(n),i}getPrecomputes(e,r,n){let i=Oy.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Oy.set(r,i))),i}cached(e,r,n){let i=Dy(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Dy(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){tE(r,this.bits),rE.set(e,r),Oy.delete(e)}hasCache(e){return Dy(e)!==1}};function nE(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Pc||n>Pc;)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 iE(t,e,r,n){l8(r,t),h8(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=Mf(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=mo(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 eE(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Iy(e),e}else return wo(t,{isLE:r})}function oE(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>Pc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=eE(e.p,r.Fp,n),o=eE(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 sE=(t,e)=>(t+(t>=0?e:-e)/cE)/e;function p8(t,e,r){let[[n,i],[o,s]]=e,c=sE(s*t,r),a=sE(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<Ti,h=d<Ti;f&&(u=-u),h&&(d=-d);let p=mo(Math.ceil(Mf(r)/2))+Mc;if(u<Ti||u>=p||d<Ti||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Ny(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ky(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Au(r.lowS,"lowS"),Au(r.prehash,"prehash"),r.format!==void 0&&Ny(r.format),r}var Cy=class extends Error{constructor(e=""){super(e)}},Ai={Err:Cy,_tlv:{encode:(t,e)=>{let{Err:r}=Ai;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=Tu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Tu(i.length/2|128):"";return Tu(t)+o+i+e},decode(t,e){let{Err:r}=Ai,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}=Ai;if(t<Ti)throw new e("integer: negative integers are not allowed");let r=Tu(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}=Ai;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 Si(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ai,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}=Ai,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},Ti=BigInt(0),Mc=BigInt(1),cE=BigInt(2),Ff=BigInt(3),y8=BigInt(4);function bo(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 g8(t,e={}){let r=oE("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Iu(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=uE(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(Au(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ut(aE(N),L)}else return ut(Uint8Array.of(4),L,n.toBytes(U))}function h(G){go(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,Ff),y8),B=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,B)))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 p8(G,a.basises,i.ORDER)}let M=_y((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=_y(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),_=Ru(x,_),D=Ru(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(go(_,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(Ff),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,Ff),{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,Ff),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=>qf($,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 qf($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ti||x.is0())return $.ZERO;if(_===Mc)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}=nE($,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===Mc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Mc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Au(_,"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 qf($,_)}static msm(_,D){return iE($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(bo(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 Vf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function aE(t){return Uint8Array.of(t?2:3)}function uE(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function m8(t,e={}){let{Fn:r}=t,n=e.randomBytes||_r,i=Object.assign(uE(t.Fp,r),{seed:Ry(r.ORDER)});function o(p){try{return!!bo(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 Hf(go(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(bo(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=bo(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=>bo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function w8(t,e,r={}){Nf(e),Iu(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_r,i=r.hmac||((D,...x)=>xy(e,D,ut(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=m8(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>>Mc;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 B(D,x){Ny(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return go(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){B(x,U);let L;if(U==="der"){let{r:P,s:V}=Ai.toSig(go(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(Tr(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*cE<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(aE((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(Ny(x),x==="der")return Tr(Ai.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=Si(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=mo(a);function q(D){return $x("num < 2^"+a,D,Ti,M),s.toBytes(D)}function j(D,x){return go(D,void 0,"message"),x?go(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}=ky(U,g);D=j(D,N);let C=T(D),P=bo(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===Ti)return;let Re=s.create(ue*s.create(z+ce*P));if(Re===Ti)return;let Me=(ee.x===ce?0:2)|Number(ee.y&Mc),Je=Re;return L&&E(Re)&&(Je=s.neg(Re),Me^=1),new A(ce,Je,Me)}return{seed:J,k2sig:W}}function X(D,x,U={}){D=ot("message",D);let{seed:L,k2sig:N}=$(D,x,U);return Hx(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 Ai.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}=ky(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}=ky(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 b8(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=wo(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 x8(t){let{CURVE:e,curveOpts:r}=b8(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 E8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,$f(r.Fn.ORDER,r.Fn.BITS))})}function dE(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=x8(t),o=g8(e,r),s=w8(o,n,i);return E8(t,s)}function fE(t,e){let r=n=>dE({...t,hash:n});return{...r(e),create:r}}var Kc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},v8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},S8=BigInt(0),lE=BigInt(1),Ly=BigInt(2);function A8(t){let e=Kc.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=Ir(d,r,e)*d%e,h=Ir(f,r,e)*d%e,p=Ir(h,Ly,e)*u%e,g=Ir(p,i,e)*p%e,y=Ir(g,o,e)*g%e,E=Ir(y,c,e)*y%e,S=Ir(E,a,e)*E%e,B=Ir(S,c,e)*y%e,A=Ir(B,r,e)*d%e,O=Ir(A,s,e)*g%e,T=Ir(O,n,e)*u%e,M=Ir(T,Ly,e);if(!jf.eql(jf.sqr(M),t))throw new Error("Cannot find square root");return M}var jf=wo(Kc.p,{sqrt:A8}),xo=fE({...Kc,Fp:jf,lowS:!0,endo:v8},ke),hE={};function Wf(t,...e){let r=hE[t];if(r===void 0){let n=ke(ws(t));r=ut(n,n),hE[t]=r}return ke(ut(r,...e))}var My=t=>t.toBytes(!0).slice(1),$c=xo.Point,Ky=t=>t%Ly===S8;function Py(t){let{Fn:e,BASE:r}=$c,n=bo(e,t),i=r.multiply(n);return{scalar:Ky(i.y)?n:e.neg(n),bytes:My(i)}}function yE(t){let e=jf;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);Ky(i)||(i=e.neg(i));let o=$c.fromAffine({x:t,y:i});return o.assertValidity(),o}var Uu=Si;function gE(...t){return $c.Fn.create(Uu(Wf("BIP0340/challenge",...t)))}function pE(t){return Py(t).bytes}function T8(t,e,r=_r(32)){let{Fn:n}=$c,i=ot("message",t),{bytes:o,scalar:s}=Py(e),c=ot("auxRand",r,32),a=n.toBytes(s^Uu(Wf("BIP0340/aux",c))),u=Wf("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Py(u),h=gE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!mE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function mE(t,e,r){let{Fn:n,BASE:i}=$c,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=yE(Uu(c)),u=Uu(o.subarray(0,32));if(!Bu(u,lE,Kc.p))return!1;let d=Uu(o.subarray(32,64));if(!Bu(d,lE,Kc.n))return!1;let f=gE(n.toBytes(u),My(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Ky(g)||p!==u)}catch{return!1}}var Rr=(()=>{let r=(i=_r(48))=>Hf(i,Kc.n);xo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:pE(o)}}return{keygen:n,getPublicKey:pE,sign:T8,verify:mE,Point:$c,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Wf,lift_x:yE,pointToBytes:My,numberToBytesBE:Lc,bytesToNumberBE:Si,mod:Br},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var _8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),bE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),B8=bE.map(t=>(9*t+5)%16),xE=(()=>{let r=[[bE],[B8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>_8[o]));return r})(),EE=xE[0],vE=xE[1],SE=[[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)),I8=EE.map((t,e)=>t.map(r=>SE[e][r])),R8=vE.map((t,e)=>t.map(r=>SE[e][r])),U8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),O8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function wE(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 Gf=new Uint32Array(16),$y=class extends Cc{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)Gf[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=U8[p],E=O8[p],S=EE[p],B=vE[p],A=I8[p],O=R8[p];for(let T=0;T<16;T++){let M=vu(n+wE(p,o,c,u)+Gf[S[T]]+y,A[T])+f|0;n=f,f=u,u=vu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=vu(i+wE(g,s,a,d)+Gf[B[T]]+E,O[T])+h|0;i=h,h=d,d=vu(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(Gf)}destroy(){this.destroyed=!0,Vn(this.buffer),this.set(0,0,0,0,0)}},AE=Lf(()=>new $y);l();l();function Hc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function D8(t,...e){if(!Hc(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 RE(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 qy(t){if(typeof t!="function")throw new Error("function expected");return!0}function Vc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Du(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Yf(t){if(!Array.isArray(t))throw new Error("array expected")}function UE(t,e){if(!RE(!0,e))throw new Error(`${t}: array of strings expected`)}function Fy(t,e){if(!RE(!1,e))throw new Error(`${t}: array of numbers expected`)}function ku(...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 Zf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;UE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Yf(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=>(Yf(i),i.map(o=>{Vc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Xf(t=""){return Vc("join",t),{encode:e=>(UE("join.decode",e),e.join(t)),decode:e=>(Vc("join.decode",e),e.split(t))}}function k8(t){return qy(t),{encode:e=>e,decode:e=>t(e)}}function TE(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(Yf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Du(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 OE=(t,e)=>e===0?t:OE(e,t%e),Jf=(t,e)=>t+(e-OE(t,e)),zf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Hy(t,e,r,n){if(Yf(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(Jf(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Jf(e,r)}`);let i=0,o=0,s=zf[e],c=zf[r]-1,a=[];for(let u of t){if(Du(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=zf[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 N8(t){Du(t);let e=2**8;return{encode:r=>{if(!Hc(r))throw new Error("radix.encode input should be Uint8Array");return TE(Array.from(r),e,t)},decode:r=>(Fy("radix.decode",r),Uint8Array.from(TE(r,t,e)))}}function jy(t,e=!1){if(Du(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Jf(8,t)>32||Jf(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Hc(r))throw new Error("radix2.encode input should be Uint8Array");return Hy(Array.from(r),8,t,!e)},decode:r=>(Fy("radix2.decode",r),Uint8Array.from(Hy(r,t,8,e)))}}function _E(t){return qy(t),function(...e){try{return t.apply(null,e)}catch{}}}function C8(t,e){return Du(t),qy(e),{encode(r){if(!Hc(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(!Hc(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 qc=ku(jy(6),Zf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Xf("")),L8=t=>ku(N8(58),Zf(t),Xf("")),Qf=L8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var DE=t=>ku(C8(4,e=>t(t(e))),Qf);var Vy=ku(Zf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Xf("")),BE=[996825010,642813549,513874426,1027748829,705979059];function Ou(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<BE.length;n++)(e>>n&1)===1&&(r^=BE[n]);return r}function IE(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=Ou(i)^s>>5}i=Ou(i);for(let o=0;o<n;o++)i=Ou(i)^t.charCodeAt(o)&31;for(let o of e)i=Ou(i)^o;for(let o=0;o<6;o++)i=Ou(i);return i^=r,Vy.encode(Hy([i%zf[30]],30,5,!1))}function kE(t){let e=t==="bech32"?1:734539939,r=jy(5),n=r.decode,i=r.encode,o=_E(n);function s(f,h,p=90){Vc("bech32.encode prefix",f),Hc(h)&&(h=Array.from(h)),Fy("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=IE(E,h,e);return`${E}1${Vy.encode(h)}${S}`}function c(f,h=90){Vc("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 B=Vy.decode(S).slice(0,-6),A=IE(E,B,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:E,words:B}}let a=_E(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 el=kE("bech32"),Fc=kE("bech32m"),NE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},P8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",M8={encode(t){return D8(t),t.toHex()},decode(t){return Vc("hex",t),Uint8Array.fromHex(t)}},Te=P8?M8:ku(jy(4),Zf("0123456789abcdef"),Xf(""),k8(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 He=new Uint8Array,Yy=new Uint8Array([0]);function jc(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 Jr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function K8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Jr(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 Wc(t){return Object.prototype.toString.call(t)==="[object Object]"}function qn(t){return Number.isSafeInteger(t)}var tl={equalBytes:jc,isBytes:Jr,isCoder:Ur,checkBounds:LE,concatBytes:K8,createView:Jy,isPlainObject:Wc},CE=t=>{if(t!==null&&typeof t!="string"&&!Ur(t)&&!Jr(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(Ur(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=_i.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(Ur(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=_i.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))}},_i={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}(${_i.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}},Wy=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 _i.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: ${Te.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})[${Te.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: ${Te.encode(this.data.slice(this.pos))}`)}}err(e){return _i.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(!Jr(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(jc(e,this.data.subarray(n,n+e.length)))return n}}},Gy=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 _i.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 _i.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++)}}},zy=t=>Uint8Array.from(t).reverse();function LE(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 PE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Gy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Wy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function Ft(t,e){if(!Ur(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return PE({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=PE(t);return t.validate?Ft(e,t.validate):e},rl=t=>Wc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Ur(t){return Wc(t)&&rl(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||qn(t.size))}function $8(){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(!Wc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var H8={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 V8(t){if(!Wc(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 q8(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 F8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!rl(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 ME=t=>{if(!rl(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Bi={dict:$8,numberBigint:H8,tsEnum:V8,decimal:q8,match:F8,reverse:ME};var Zy=(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:zy(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 LE(s,8n*i,!!r),s}})};var KE=Zy(32,!1);var Gc=Zy(8,!0);var $E=Zy(8,!0,!0);var j8=(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}}),Nu=(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 j8(t,{write:r.write,read:r.read,validate:e?o:c})},_e=Nu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),HE=Nu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),Eo=Nu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Xy=Nu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var gn=Nu(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var Fe=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=CE(t),n=Jr(t);return jt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?zy(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?zy(o):o},validate:i=>{if(!Jr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function VE(t,e){if(!Ur(e))throw new Error(`prefix: invalid inner value ${e}`);return yn(Fe(t),ME(e))}var nl=(t,e=!1)=>Ft(yn(Fe(t,e),NE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var qE=(t,e={isLE:!1,with0x:!1})=>{let r=yn(Fe(t,e.isLE),Te),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=yn(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 yn(t,e){if(!Ur(t))throw new Error(`apply: invalid inner value ${t}`);if(!rl(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 FE=(t,e=!1)=>{if(!Jr(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=jc(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 jE(t,e,r){if(!Ur(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Ur(e))throw new Error(`flagged: wrong path=${t}`);return jt({encodeStream:(n,i)=>{typeof t=="string"?_i.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=!!_i.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function il(t,e,r=!0){if(!Ur(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||Jr(e)&&!jc(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 WE(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(!Wc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Ur(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return jt({size:WE(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 GE(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(!Ur(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return jt({size:WE(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(!Ur(e))throw new Error(`array: invalid inner value ${e}`);let r=CE(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=>{Jr(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),Jr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(jc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Jr(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(Jr(t))for(let s=0;;s++){if(jc(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 cl=xo.ProjectivePoint,sl=xo.CURVE.n,Ce=tl.isBytes,Fn=tl.concatBytes,st=tl.equalBytes;var zc=t=>AE(ke(t)),Ii=(...t)=>ke(ke(Fn(...t))),sM=Rr.utils.randomPrivateKey,al=Rr.getPublicKey,Qy=xo.getPublicKey,zE=t=>t.r<sl/2n;function YE(t,e,r=!1){let n=xo.sign(t,e);if(r&&!zE(n)){let i=new Uint8Array(32),o=0;for(;!zE(n);)if(i.set(_e.encode(o++)),n=xo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var e0=Rr.sign,Cu=Rr.utils.taggedHash,xt;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(xt||(xt={}));function vo(t,e){let r=t.length;if(e===xt.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return cl.fromHex(t),t}else if(e===xt.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Rr.utils.lift_x(Rr.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function JE(t,e){let r=Rr.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=sl)throw new Error("tweak higher than curve order");return i}function ZE(t,e=Uint8Array.of()){let r=Rr.utils,n=r.bytesToNumberBE(t),i=cl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,sl),s=r.pointToBytes(i),c=JE(s,e);return r.numberToBytesBE(r.mod(o+c,sl),32)}function Lu(t,e){let r=Rr.utils,n=JE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(cl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var ul=ke(cl.BASE.toRawBytes(!1)),Zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},t0={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function Pu(t,e){if(!Ce(t)||!Ce(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 r0(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 ev(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=r0(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Xe=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=r0().encode(BigInt(r))),!Ce(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(Xy.encode(n))):(t.byte(gt.PUSHDATA4),t.bytes(_e.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=gn.decodeStream(t);else if(r===gt.PUSHDATA2)n=Xy.decodeStream(t);else if(r===gt.PUSHDATA4)n=_e.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}}),QE={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Yc=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(QE))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]=QE[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}}),Or=yn(Yc,Bi.numberBigint),fr=Fe(Yc),Jc=Wt(Or,fr),dl=t=>Wt(Yc,t),tv=bt({txid:Fe(32,!0),index:_e,finalScriptSig:fr,sequence:_e}),Ri=bt({amount:Gc,script:fr}),W8=bt({version:Eo,segwitFlag:FE(new Uint8Array([0,1])),inputs:dl(tv),outputs:dl(Ri),witnesses:jE("segwitFlag",Wt("inputs/length",Jc)),lockTime:_e});function G8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Ui=Ft(W8,G8),Es=bt({version:Eo,inputs:dl(tv),outputs:dl(Ri),lockTime:_e});var i0=Ft(Fe(null),t=>vo(t,xt.ecdsa)),fl=Ft(Fe(32),t=>vo(t,xt.schnorr)),rv=Ft(Fe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),ll=bt({fingerprint:HE,path:Wt(null,_e)}),ov=bt({hashes:Wt(Or,Fe(32)),der:ll}),z8=Fe(78),Y8=bt({pubKey:fl,leafHash:Fe(32)}),J8=bt({version:gn,internalKey:Fe(32),merklePath:Wt(null,Fe(32))}),Oi=Ft(J8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),Z8=Wt(null,bt({depth:gn,version:gn,script:fr})),Et=Fe(null),nv=Fe(20),Mu=Fe(32),hl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,z8,ll,[],[0,2],!1],txVersion:[2,!1,_e,[2],[2],!1],fallbackLocktime:[3,!1,_e,[],[2],!1],inputCount:[4,!1,Or,[2],[2],!1],outputCount:[5,!1,Or,[2],[2],!1],txModifiable:[6,!1,gn,[],[2],!1],version:[251,!1,_e,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},Ku={nonWitnessUtxo:[0,!1,Ui,[],[0,2],!1],witnessUtxo:[1,!1,Ri,[],[0,2],!1],partialSig:[2,i0,Et,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,Et,[],[0,2],!1],witnessScript:[5,!1,Et,[],[0,2],!1],bip32Derivation:[6,i0,ll,[],[0,2],!1],finalScriptSig:[7,!1,Et,[],[0,2],!1],finalScriptWitness:[8,!1,Jc,[],[0,2],!1],porCommitment:[9,!1,Et,[],[0,2],!1],ripemd160:[10,nv,Et,[],[0,2],!1],sha256:[11,Mu,Et,[],[0,2],!1],hash160:[12,nv,Et,[],[0,2],!1],hash256:[13,Mu,Et,[],[0,2],!1],txid:[14,!1,Mu,[2],[2],!0],index:[15,!1,_e,[2],[2],!0],sequence:[16,!1,_e,[],[2],!0],requiredTimeLocktime:[17,!1,_e,[],[2],!1],requiredHeightLocktime:[18,!1,_e,[],[2],!1],tapKeySig:[19,!1,rv,[],[0,2],!1],tapScriptSig:[20,Y8,rv,[],[0,2],!1],tapLeafScript:[21,Oi,Et,[],[0,2],!1],tapBip32Derivation:[22,Mu,ov,[],[0,2],!1],tapInternalKey:[23,!1,fl,[],[0,2],!1],tapMerkleRoot:[24,!1,Mu,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},sv=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],cv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],$u={redeemScript:[0,!1,Et,[],[0,2],!1],witnessScript:[1,!1,Et,[],[0,2],!1],bip32Derivation:[2,i0,ll,[],[0,2],!1],amount:[3,!1,$E,[2],[2],!0],script:[4,!1,Et,[2],[2],!0],tapInternalKey:[5,!1,fl,[],[0,2],!1],tapTree:[6,!1,Z8,[],[0,2],!1],tapBip32Derivation:[7,fl,ov,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},av=[],iv=Wt(Yy,bt({key:VE(Or,bt({type:Or,key:Fe(null)})),value:Fe(Or)}));function o0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var pM=bt({type:Or,key:Fe(null)});function s0(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:He},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>Pu(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)=>Pu(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}iv.encodeStream(r,i)},decodeStream:r=>{let n=iv.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=${Te.encode(a)} value=${Te.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 pl=Ft(s0(Ku),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)vo(e,xt.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(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}),yl=Ft(s0($u),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,xt.ecdsa);return t}),uv=Ft(s0(hl),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}),X8=bt({magic:il(nl(new Uint8Array([255])),"psbt"),global:uv,inputs:Wt("global/unsignedTx/inputs/length",pl),outputs:Wt(null,yl)}),Q8=bt({magic:il(nl(new Uint8Array([255])),"psbt"),global:uv,inputs:Wt("global/inputCount",pl),outputs:Wt("global/outputCount",yl)}),yM=bt({magic:il(nl(new Uint8Array([255])),"psbt"),items:Wt(null,yn(Wt(Yy,GE([qE(Or),Fe(Yc)])),Bi.dict()))});function n0(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=o0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=o0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function c0(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}=o0(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 dv(t){let e=t&&t.global&&t.global.version||0;n0(e,hl,t.global);for(let s of t.inputs)n0(e,Ku,s);for(let s of t.outputs)n0(e,$u,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 gl(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(Te.decode(E[0])):E[0],typeof E[1]=="string"?d.decode(Te.decode(E[1])):E[1]]});let g={},y=(E,S,B)=>{if(g[E]===void 0){g[E]=[S,B];return}let A=Te.encode(d.encode(g[E][1])),O=Te.encode(d.encode(B));if(A!==O)throw new Error(`keyMap(${c}): same key=${E} oldVal=${A} newVal=${O}`)};for(let[E,S]of h){let B=Te.encode(u.encode(E));y(B,E,S)}for(let[E,S]of p){let B=Te.encode(u.encode(E));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${E}`);delete g[B]}else y(B,E,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(Te.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 a0=Ft(X8,dv),u0=Ft(Q8,dv);var tR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||Te.encode(t[1])!=="4e73"))return{type:"p2a",script:Xe.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,Te.decode("4e73")]}};function So(t,e){try{return vo(t,e),!0}catch{return!1}}var rR={encode(t){if(!(t.length!==2||!Ce(t[0])||!So(t[0],xt.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},nR={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!Ce(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},iR={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!Ce(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},oR={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},sR={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},cR={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(!Ce(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},aR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},uR={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(!Ce(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}},dR={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=ev(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(!Ce(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}},fR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},lR=[tR,rR,nR,iR,oR,sR,cR,aR,uR,dR,fR],hR=yn(Xe,Bi.match(lR)),Qe=Ft(hR,t=>{if(t.type==="pk"&&!So(t.pubkey,xt.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!Ce(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!Ce(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!Ce(t.pubkey)||!So(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(!So(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(!So(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 fv(t,e){if(!st(t.hash,ke(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Qe.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 y0(t,e,r){if(t){let n=Qe.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,zc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Qe.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&&fv(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&fv(n,r)}}var Di=(t,e=Zr)=>{if(!So(t,xt.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=zc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Xr(e).encode({type:"pkh",hash:r}),hash:r}};var vs=(t,e=Zr)=>{if(!So(t,xt.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=zc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Xr(e).encode({type:"wpkh",hash:r}),hash:r}};function pR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=yn(Xe,Bi.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,ul))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 hv(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 f0(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:f0(t.left,[t.right.hash,...e]),right:f0(t.right,[t.left.hash,...e])}}function l0(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[...l0(t.left),...l0(t.right)]}function h0(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,He))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?Te.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return pR(d,e,r,n),{type:"leaf",version:a,script:d,hash:Hu(d,a)}}if(t.length!==2&&(t=hv(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=h0(t[0],e,r,n),o=h0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return Pu(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Cu("TapBranch",s,c)}}var p0=192,Hu=(t,e=p0)=>Cu("TapLeaf",new Uint8Array([e]),fr.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"?Te.decode(t):t||ul;if(!So(o,xt.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=f0(h0(e,o,n,i)),c=s.hash,[a,u]=Lu(o,c),d=l0(s).map(f=>({...f,controlBlock:Oi.encode({version:(f.version||p0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Xr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Oi.decode(f.controlBlock),Fn(f.script,new Uint8Array([f.version||p0]))]),tapMerkleRoot:c}}else{let s=Lu(o,He)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Xr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var pv=DE(ke);function yv(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 d0(t,e,r=Zr){yv(t,e);let n=t===0?el:Fc;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function lv(t,e){return pv.encode(Fn(Uint8Array.from(e),t))}function Xr(t=Zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return d0(0,e.hash,t);if(r==="wsh")return d0(0,e.hash,t);if(r==="tr")return d0(1,e.pubkey,t);if(r==="pkh")return lv(e.hash,[t.pubKeyHash]);if(r==="sh")return lv(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=el.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Fc.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=el.fromWords(o);if(yv(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=pv.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 ml=new Uint8Array(32),yR={amount:0xffffffffffffffffn,script:He},gR=t=>Math.ceil(t/4),mR=8,wR=2,As=0,b0=4294967295,bR=Bi.decimal(mR),qu=(t,e)=>t===void 0?e:t;function bl(t){if(Array.isArray(t))return t.map(e=>bl(e));if(Ce(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,bl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var je;(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"})(je||(je={}));var Ao;(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"})(Ao||(Ao={}));function xR(t,e,r,n=He){return st(r,e)&&(t=ZE(t,n),e=al(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 Vu(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:qu(t.sequence,b0),finalScriptSig:qu(t.finalScriptSig,He)}}function g0(t){for(let e in t){let r=e;sv.includes(r)||delete t[r]}}var m0=bt({txid:Fe(32,!0),index:_e});function ER(t){if(typeof t!="number"||typeof Ao[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function gv(t){let e=t&31;return{isAny:!!(t&je.ANYONECANPAY),isNone:e===je.NONE,isSingle:e===je.SINGLE}}function vR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:qu(t.version,wR),lockTime:qu(t.lockTime,0),PSBTVersion:qu(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(_e.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 mv(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(Ui.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=Te.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function wl(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 wv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=Te.decode(o)),Ce(o)&&(o=Ui.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=Te.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=b0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=gl(Ku,c,e,r,i),pl.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&y0(a&&a.script,c.redeemScript,c.witnessScript),c}function w0(t,e=!1){let r="legacy",n=je.ALL,i=wl(t),o=Qe.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=je.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=Qe.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=Qe.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=Qe.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=vR(e);r.lockTime!==As&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Ui.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=a0.decode(e)}catch(f){try{n=u0.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)=>mv({finalScriptSig:He,...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=>mv(c0(e,Ku,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=>c0(e,$u,o)),i={...this.global};return e===0?(i.unsignedTx=Es.decode(Es.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Vu).map(o=>({...o,finalScriptSig:He})),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?a0:u0).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?je.DEFAULT:r,i=n===je.DEFAULT?je.ALL:n&3;return{sigInputs:n&je.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===je.ANYONECANPAY?n.push(o):e=!1,a===je.ALL)r=!1;else if(a===je.SINGLE)i.push(o);else if(a!==je.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*Or.encode(this.outputs.length).length;for(let n of r)e+=32+4*fr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Or.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*fr.encode(n.finalScriptSig||He).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Jc.encode(n.finalScriptWitness).length);return e}get vsize(){return gR(this.weight)}toBytes(e=!1,r=!1){return Ui.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Vu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||He})),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 Te.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Ii(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Ii(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),bl(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(wv(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=cv)}this.inputs[e]=wv(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),bl(this.outputs[e])}getOutputAddress(e,r=Zr){let n=this.getOutput(e);if(n.script)return Xr(r).encode(Qe.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=Te.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=gl($u,s,r,n,this.opts.allowUnknown),yl.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Qe.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||y0(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=av)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=Zr){return this.addOutput({script:Qe.encode(Xr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=wl(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}=gv(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 KE.encode(1n);r=Xe.encode(Xe.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Vu).map((d,f)=>({...d,finalScriptSig:f===e?r:He}));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(yR).concat([a[e]]));let u=Ui.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ii(u,Eo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=gv(n),a=ml,u=ml,d=ml,f=this.inputs.map(Vu),h=this.outputs.map(Ts);o||(a=Ii(...f.map(m0.encode))),!o&&!c&&!s&&(u=Ii(...f.map(g=>_e.encode(g.sequence)))),!c&&!s?d=Ii(...h.map(Ri.encode)):c&&e<h.length&&(d=Ii(Ri.encode(h[e])));let p=f[e];return Ii(Eo.encode(this.version),a,u,Fe(32,!0).encode(p.txid),_e.encode(p.index),fr.encode(r),Gc.encode(i),_e.encode(p.sequence),d,_e.encode(this.lockTime),_e.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=[gn.encode(0),gn.encode(n),Eo.encode(this.version),_e.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(Vu),p=this.outputs.map(Ts);f!==je.ANYONECANPAY&&u.push(...[h.map(m0.encode),i.map(Gc.encode),r.map(fr.encode),h.map(y=>_e.encode(y.sequence))].map(y=>ke(Fn(...y)))),d===je.ALL&&u.push(ke(Fn(...p.map(Ri.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===je.ANYONECANPAY){let y=h[e];u.push(m0.encode(y),Gc.encode(i[e]),fr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(ke(fr.encode(a||He))),d===je.SINGLE&&u.push(e<p.length?ke(Ri.encode(p[e])):ml),s&&u.push(Hu(s,c),gn.encode(0),Eo.encode(o)),Cu("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=w0(o,this.opts.allowLegacyWitnessUtxo);if(!Ce(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(ER):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===je.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=wl(o);if(s.txType==="taproot"){let d=this.inputs.map(wl),f=d.map(E=>E.script),h=d.map(E=>E.amount),p=!1,g=al(e),y=o.tapMerkleRoot||He;if(o.tapInternalKey){let{pubKey:E,privKey:S}=xR(e,g,o.tapInternalKey,y),[B,A]=Lu(o.tapInternalKey,y);if(st(B,E)){let O=this.preimageWitnessV1(r,f,c,h),T=Fn(e0(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):He);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[E,S]of o.tapLeafScript){let B=S.subarray(0,-1),A=Xe.decode(B),O=S[S.length-1],T=Hu(B,O);if(A.findIndex($=>Ce($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,B,O),j=Fn(e0(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):He);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=Qy(e),f=!1,h=zc(d);for(let y of Xe.decode(s.lastScript))Ce(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=Qe.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=YE(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=w0(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)=>Oi.encode(u[0]).length-Oi.encode(d[0]).length);for(let[u,d]of a){let f=d.slice(0,-1),h=d[d.length-1],p=Qe.decode(f),g=Hu(f,h),y=r.tapScriptSig.filter(S=>st(S[0].leafHash,g)),E=[];if(p.type==="tr_ms"){let S=p.m,B=p.pubkeys,A=0;for(let O of B){let T=y.findIndex(M=>st(M[0].pubKey,O));if(A===S||T===-1){E.push(He);continue}E.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let B=y.findIndex(A=>st(A[0].pubKey,S));B!==-1&&E.push(y[B][1])}if(E.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Xe.decode(f);if(E=y.map(([{pubKey:B},A])=>{let O=S.findIndex(T=>Ce(T)&&st(T,B));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((B,A)=>B.pos-A.pos).map(B=>B.signature),!E.length)continue}else{let S=this.opts.customScripts;if(S)for(let B of S){if(!B.finalizeTaproot)continue;let A=Xe.decode(f),O=B.encode(A);if(O===void 0)continue;let T=B.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Oi.encode(u)),r.finalScriptSig=He,g0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=E.reverse().concat([f,Oi.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=He,g0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=He,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=Xe.encode([0,...d])}else if(n.last.type==="pk")i=Xe.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Xe.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=He,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=Xe.decode(i).map(a=>{if(a===0)return He;if(Ce(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=Xe.encode([Xe.encode([0,ke(n.lastScript)])]):n.type.startsWith("sh-")?s=Xe.encode([...Xe.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),g0(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):He,n=e.global.unsignedTx?Es.encode(e.global.unsignedTx):He;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=gl(hl,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 bv(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,B){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+B+"]")}),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(B){i&&i.includes(B)||(g&&(r+=","),g=!0,r+=JSON.stringify(B),r+=":",u(d[B],f+"."+B))};if(f===""&&n)n.forEach(function(B){d.hasOwnProperty(B)&&y(B)});else{var E=Object.keys(d);c&&(E=E.filter(function(B){return d[B]!==void 0})),E.sort(),E.forEach(function(B){y(B)})}r+="}"}}}function xv(t,e){return bv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var x0;(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"})(x0||(x0={}));var{INVALID_DID:Lt,METHOD_NOT_SUPPORTED:xl,INTERNAL_ERROR:Ev,INVALID_DID_DOCUMENT:Oe,INVALID_DID_UPDATE:De,INVALID_DID_URL:iK,INVALID_PREVIOUS_DID_PROOF:oK,INVALID_PUBLIC_KEY:sK,INVALID_PUBLIC_KEY_MULTIBASE:cK,INVALID_PUBLIC_KEY_LENGTH:aK,INVALID_PUBLIC_KEY_TYPE:uK,INVALID_SIGNATURE:dK,PROOF_VERIFICATION_ERROR:ki,PROOF_GENERATION_ERROR:_o,PROOF_SERIALIZATION_ERROR:vv,PROOF_PARSING_ERROR:fK,VERIFICATION_METHOD_ERROR:El,LATE_PUBLISHING_ERROR:vl,INVALID_SIDECAR_DATA:lK,MISSING_UPDATE_DATA:hK,MISSING_RESOLUTION_OPTIONS:pK}=x0,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)}},we=class extends Gt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var 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})}},Ve=class extends Gt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var qe=class extends Gt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},To=class extends Gt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},mn=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 SR=new Set(["jcs"]),AR=new Set(["hex","base58","base64urlnopad"]);function E0(t){let e=t.toLowerCase();if(!SR.has(e))throw new Zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function v0(t){let e=t.toLowerCase();if(!AR.has(e))throw new Zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function rr(t,e="jcs"){switch(E0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return xv(n)}default:throw new Zc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function Bo(t){return ke(t)}function Qr(t,e="base64urlnopad"){switch(v0(e)){case"hex":return Te.encode(t);case"base58":return Qf.encode(t);case"base64urlnopad":return qc.encode(t)}}function Is(t,e="base64urlnopad"){switch(v0(e)){case"hex":return Te.decode(t);case"base58":return Qf.decode(t);case"base64urlnopad":return qc.decode(t)}}function Xc(t,e="jcs"){return Bo(rr(t,E0(e)))}function Wn(t,e){let r=E0(e?.algorithm??"jcs"),n=v0(e?.encoding??"base64urlnopad");return Qr(Bo(rr(t,r)),n)}l();l();var S0={};xu(S0,{JsonPatchError:()=>ct,_areEquals:()=>Wu,applyOperation:()=>Rs,applyPatch:()=>Rl,applyReducer:()=>RR,deepClone:()=>BR,getValueByPointer:()=>Bl,validate:()=>Av,validator:()=>Il});l();l();var TR=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)}}(),_R=Object.prototype.hasOwnProperty;function Al(t,e){return _R.call(t,e)}function Tl(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)Al(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 _l(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 Gn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Fu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Sl(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Sl(t[e]))return!0}else if(typeof t=="object"){for(var n=Tl(t),i=n.length,o=0;o<i;o++)if(Sl(t[n[o]]))return!0}}return!1}function Sv(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 ju=function(t){TR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,Sv(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=Sv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=ju,BR=Pt,Qc={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=Bl(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=Bl(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:Wu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},IR={add:function(t,e,r){return _l(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:Qc.move,copy:Qc.copy,test:Qc.test,_get:Qc._get};function Bl(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):Il(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=Bl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Wu(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=Il;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=Fu(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&&!_l(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);_l(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=IR[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=Qc[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 Rl(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 RR(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 Il(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(Qc[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")&&Sl(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=Av([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 Av(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Rl(Pt(e),Pt(t),r||!0);else{r=r||Il;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 Wu(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(!Wu(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],!Wu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var B0={};xu(B0,{compare:()=>PR,generate:()=>A0,observe:()=>LR,unobserve:()=>CR});l();var T0=new WeakMap,UR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),OR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function DR(t){return T0.get(t)}function kR(t,e){return t.observers.get(e)}function NR(t,e){t.observers.delete(e.callback)}function CR(t,e){e.unobserve()}function LR(t,e){var r=[],n,i=DR(t);if(!i)i=new UR(t),T0.set(t,i);else{var o=kR(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(){A0(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(){A0(n),clearTimeout(n.next),NR(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 OR(e,n)),n}function A0(t,e){e===void 0&&(e=!1);var r=T0.get(t.object);_0(r.value,t.object,t.patches,"",e),t.patches.length&&Rl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function _0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Tl(e),s=Tl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(Al(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)?_0(f,h,r,n+"/"+Gn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+Gn(d),value:Pt(f)}),r.push({op:"replace",path:n+"/"+Gn(d),value:Pt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Gn(d),value:Pt(f)}),r.push({op:"remove",path:n+"/"+Gn(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];!Al(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+Gn(d),value:Pt(e[d])})}}}function PR(t,e,r){r===void 0&&(r=!1);var n=[];return _0(t,e,n,"",r),n}var Tv=Object.assign({},S0,B0,{JsonPatchError:ju,deepClone:Pt,escapePathComponent:Gn,unescapePathComponent:Fu});var{applyPatch:MR,compare:KR,deepClone:$R}=Tv,HR=new Set(["__proto__","constructor","prototype"]);function _v(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>HR.has(e))}var ea=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??$R,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new we("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=MR(s,r,!1,i);if(a.newDocument===void 0)throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=KR(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 we("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let r of e){if(!r||typeof r!="object")return new we("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof r.op!="string")return new we("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof r.path!="string")return new we("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");let n=_v(r.path);if(n)return new we(`Operation.path traverses prototype machinery: ${n}`,"JSON_PATCH_VALIDATION_ERROR");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new we(`Operation.from must be a string for op=${r.op}`,"JSON_PATCH_VALIDATION_ERROR");if(typeof r.from=="string"){let i=_v(r.from);if(i)return new we(`Operation.from traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var Io;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(Io||(Io={}));var Ul;(function(t){t.k="k",t.x="x"})(Ul||(Ul={}));var Gu;(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"})(Gu||(Gu={}));l();var Ro=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");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],B=f%4===0&&f%100!==0||f%400===0,A=h===2&&B?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();function I0(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}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 we("Maximum comparison depth exceeded","MAX_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)||I0(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&&I0(i,o,c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new we("Maximum clone depth exceeded","MAX_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 we("Cannot clone circular structure","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))I0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var zt=class extends we{constructor(e,r="BeaconError",n){super(e,r,n)}},R0=class extends we{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},U0=class extends we{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},O0=class extends we{constructor(e,r="CASBeaconError",n){super(e,r,n)}},ta=class extends we{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 ZR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Uo(t){switch(t){case"bitcoin":return Zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return t0;case"regtest":return ZR;default:throw new Error(`Unknown network "${t}"`)}}l();var ra=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 k0="0000000000000000000000000000000000000000000000000000000000000000",N0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var C0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(C0||(C0={}));var Ol=new ra(5);var Iv=160,Rv=155,Uv=240,Ov={p2pkh:Uv,p2wpkh:Rv,p2tr:Iv},L0={p2pkh:34,p2wpkh:31,p2tr:43},P0={p2pkh:546,p2wpkh:294,p2tr:330};function M0(t,e){return Ov[t]-L0[t]+L0[e]}function K0(t,e){let r=Xr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new zt(`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 Dv(t,e,r){return t==="p2pkh"?Di(e,r).address:t==="p2wpkh"?vs(e,r).address:Ss(e.slice(1,33),void 0,r).address}function $0(t,e,r){if(!r||r===t)return t;try{Xr(e).decode(r)}catch{throw new zt(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function kv(t,e){try{return K0(t,e)}catch{return"p2tr"}}function H0(t){return Xe.encode(["RETURN",t])}var Dl=546;function e6(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 Nv(t,e){if(!t.length)throw new zt("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>Dl);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 ${Dl}-sat dust limit`;throw new zt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:Dl})}return[...n].sort(e6)[0]}async function Cv(t,e){let r=await e.rest.address.getUtxos(t),n=Nv(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Tr(i)}}async function t6(t){let e=t.feeEstimator??Ol,{utxo:r,prevTxBytes:n}=await Cv(t.beaconAddress,t.bitcoin),i=$0(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Xr(t.network).decode(t.beaconAddress)),s=kv(i,t.network),c=await e.estimateFee(M0("p2tr",s));if(BigInt(r.value)<=c)throw new zt(`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(P0[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:H0(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 r6(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=Ao.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=Qe.decode(i);if(u.type!=="wpkh")throw new zt(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Qe.encode({type:"pkh",hash:u.hash}),f=Ao.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],Ao.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ni=class{service;constructor(e){this.service=e}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??Ol,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await Cv(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=K0(e.beaconAddress,r),o=$0(e.beaconAddress,r,e.changeAddress),s=Dv(i,n,r);if(s!==e.beaconAddress)throw new zt(`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=kv(o,r),a=await e.feeEstimator.estimateFee(M0(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new zt(`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=Di(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(P0[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:H0(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 r6(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var zu=class extends Ni{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=Qr(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=Wn(e),c={[o]:s},a=Bo(rr(c));i?.casPublish&&await i.casPublish(c);let u=await this.buildSignAndBroadcast(a,r,n,i);return{signedUpdate:e,txid:u,announcement:c}}};l();l();var Yu=class extends Ni{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=Bo(rr(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var n6=new Uint8Array(32),V0=1n<<BigInt(256),Lv=(()=>{let t=new Array(257),e=V0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Ju(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function Se(t,e,r=""){let n=Ju(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 kl(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");zn(t.outputLen),zn(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 Mv(t,e){Se(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 Nl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function xn(t,e){return t<<32-e|t>>>e}var Kv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ds(t){if(Se(t),Kv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=i6[t[r]];return e}var Ci={_0:48,_9:57,A:65,F:70,a:97,f:102};function Pv(t){if(t>=Ci._0&&t<=Ci._9)return t-Ci._0;if(t>=Ci.A&&t<=Ci.F)return t-(Ci.A-10);if(t>=Ci.a&&t<=Ci.f)return t-(Ci.a-10)}function ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Kv)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=Pv(t.charCodeAt(o)),c=Pv(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 lr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Se(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 $v(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 Hv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var F0=BigInt(0),q0=BigInt(1);function Zu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Vv(t){if(typeof t=="bigint"){if(!Cl(t))throw new Error("positive bigint expected, got "+t)}else zn(t);return t}function Xu(t){let e=Vv(t).toString(16);return e.length&1?"0"+e:e}function qv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?F0:BigInt("0x"+t)}function Oo(t){return qv(Ds(t))}function j0(t){return qv(Ds(o6(Se(t)).reverse()))}function Ll(t,e){zn(e),t=Vv(t);let r=ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function W0(t,e){return Ll(t,e).reverse()}function ia(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 o6(t){return Uint8Array.from(t)}function Fv(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 Cl=t=>typeof t=="bigint"&&F0<=t;function s6(t,e,r){return Cl(t)&&Cl(e)&&Cl(r)&&e<=t&&t<r}function jv(t,e,r,n){if(!s6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function G0(t){let e;for(e=0;t>F0;t>>=q0,e+=1);return e}var Qu=t=>(q0<<BigInt(t))-q0;function Wv(t,e,r){if(zn(t,"hashLen"),zn(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,lr(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 B=a.slice();S.push(B),E+=a.length}return lr(...S)};return(E,S)=>{f(),p(E);let B;for(;!(B=S(g()));)p();return f(),B}}function ed(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 z0(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 Y0(t){return t.length===32}function Pl(t){if(!Y0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function dt(...t){return ke(ut(...t))}function td(t){Pl(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function J0(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 Z0(t){Pl(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function X0(t,e){return!Y0(t)||!Y0(e)?!1:ia(t,e)}function oa(t){return Pl(t),qc.encode(t)}function Yn(t){let e=qc.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var Gv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(Gv||(Gv={}));l();l();var Do=256;function sa(t,e){return Number(t>>BigInt(e)&1n)}var zv=(()=>{let t=new Array(Do+1),e=new Uint8Array(32);for(let r=0;r<=Do;r++)e=dt(e,e),t[r]=e;return t})();function Ml(t,e){if(t.length===0)return zv[e];if(e===0)return t[0].leaf;let r=Do-e,n=[],i=[];for(let o of t)(sa(o.index,r)===0?n:i).push(o);return dt(Ml(n,e-1),Ml(i,e-1))}function Yv(t){return Ml(t,Do)}function Jv(t,e){let r=0n,n=[];for(let i=1;i<=Do;i++){let o=Do-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(sa(c.index,u)!==sa(e,u)){a=!1;break}a&&sa(c.index,o)!==sa(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Ml(s,i-1))}return{collapsed:r,hashes:n}}function Zv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Do;c++){let a=Do-1-c,u;if((t>>BigInt(a)&1n)===1n)u=zv[c];else{if(s>=e.length)return!1;u=e[s++]}o=sa(r,a)===1?dt(u,o):dt(o,u)}return s===e.length&&X0(o,i)}l();var c6=new TextEncoder;function Kl(t){return td(dt(c6.encode(t)))}function Xv(t,e){return dt(dt(t),dt(e))}function Qv(t){return dt(dt(t))}l();function e1(t,e,r){let n={id:oa(t),collapsed:oa(J0(e.collapsed)),hashes:e.hashes.map(i=>oa(i))};return r?.nonce&&(n.nonce=oa(r.nonce)),r?.updateId&&(n.updateId=oa(r.updateId)),n}function a6(t){let e={rootHash:Yn(t.id),collapsed:td(Yn(t.collapsed)),hashes:t.hashes.map(r=>Yn(r))};return t.nonce&&(e.nonce=Yn(t.nonce)),t.updateId&&(e.updateId=Yn(t.updateId)),e}function t1(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=a6(t);return Zv(i,o,e,r,n)}l();var $l=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=Kl(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?Xv(n.nonce,n.signedUpdate):Qv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=Yv(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=Jv(this.#n,r),o=n.signedUpdate!==void 0?dt(n.signedUpdate):void 0;return e1(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var rd=class extends Ni{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 ta("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=Kl(o),u=Yn(c.nonce),d=c.updateId?dt(dt(u),Yn(c.updateId)):dt(dt(u));if(!t1(c,a,d))throw new ta("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=Z0(Yn(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(rr(e)),c=_r(32),a=new $l;a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize();let u=a.proof(o),d=await this.buildSignAndBroadcast(a.rootHash,r,n,i);return{signedUpdate:e,txid:d,proof:u}}};var Cs=class{static establish(e){switch(e.type){case"SingletonBeacon":return new Yu(e);case"CASBeacon":return new zu(e);case"SMTBeacon":return new rd(e);default:throw new we("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Pi;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Pi||(Pi={}));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 f6=Pn(n1(),1);l();l();l();l();var kH=new Uint8Array(0);function i1(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 ca(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 h6(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,B=g.length;S!==B&&g[S]===0;)S++,y++;for(var A=(B-S)*d+1>>>0,O=new Uint8Array(A);S!==B;){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 B=(g.length-y)*u+1>>>0,A=new Uint8Array(B);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=B-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=B-S;q!==B&&A[q]===0;)q++;for(var j=new Uint8Array(E+(B-q)),$=E;q!==B;)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 p6=h6,y6=p6,o1=y6;var rg=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")}},ng=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 s1(this,e)}},ig=class{decoders;constructor(e){this.decoders=e}or(e){return s1(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 s1(t,e){return new ig({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var og=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 rg(e,r,n),this.decoder=new ng(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function c1({name:t,prefix:e,encode:r,decode:n}){return new og(t,e,r,n)}function sg({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=o1(r,t);return c1({prefix:e,name:t,encode:n,decode:o=>ca(i(o))})}function g6(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 m6(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 c1({prefix:e,name:t,encode(i){return m6(i,n,r)},decode(i){return g6(i,n,r,t)}})}var nd=nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VH=nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qH=nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),FH=nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jH=nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),WH=nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),GH=nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zH=nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cg=nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var hr=sg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),XH=sg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var rV=nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nV=nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Jn=nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iV=nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function a1(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function u1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function aa(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var id=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())})},d1=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)}},Vl=new TextEncoder,Ls=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(!u1(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 hr.baseDecode(this.data).buffer;case"Base64Url":return Jn.baseDecode(this.data).buffer;case"BufferSource":{if(aa(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return a1(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 id(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 cg.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 hr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return hr.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 Jn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Jn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Vl.encode(e);return Jn.baseEncode(r)}case"String":{let e=Vl.encode(this.data);return Jn.baseEncode(e)}case"Uint8Array":return Jn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return id(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=d1(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=Jn.baseDecode(this.data),r=Ls.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Ls.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return id(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 Ls.decode(this.data);case"Base64Url":{let e=Jn.baseDecode(this.data);return Ls.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Ls.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return id(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=d1(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+=Ls.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+=Ls.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 cg.baseDecode(this.data);case"Base58Btc":return hr.baseDecode(this.data);case"Base64Url":return Jn.baseDecode(this.data);case"BufferSource":{let e=aa(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 Vl.encode(e)}case"String":return Vl.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return id(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 od;(function(t){t.Debug="debug",t.Silent="silent"})(od||(od={}));var ag=class{constructor(){this.logLevel=od.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==od.Silent&&console.info(e)}error(e){this.logLevel!==od.Silent&&console.error(e)}},w6=new ag;typeof window<"u"&&(window.web5logger=w6);l();l();l();l();var Mi={};xu(Mi,{decode:()=>ua,encodeTo:()=>Ps,encodingLength:()=>Ms});l();l();var b6=h1,f1=128,x6=127,E6=~x6,v6=Math.pow(2,31);function h1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=v6;)e[r++]=t&255|f1,t/=128;for(;t&E6;)e[r++]=t&255|f1,t>>>=7;return e[r]=t|0,h1.bytes=r-n+1,e}var S6=ug,A6=128,l1=127;function ug(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw ug.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&l1)<<i:(s&l1)*Math.pow(2,i),i+=7}while(s>=A6);return ug.bytes=o-n,r}var T6=Math.pow(2,7),_6=Math.pow(2,14),B6=Math.pow(2,21),I6=Math.pow(2,28),R6=Math.pow(2,35),U6=Math.pow(2,42),O6=Math.pow(2,49),D6=Math.pow(2,56),k6=Math.pow(2,63),N6=function(t){return t<T6?1:t<_6?2:t<B6?3:t<I6?4:t<R6?5:t<U6?6:t<O6?7:t<D6?8:t<k6?9:10},C6={encode:b6,decode:S6,encodingLength:N6},L6=C6,sd=L6;function ua(t,e=0){return[sd.decode(t,e),sd.decode.bytes]}function Ps(t,e,r=0){return sd.encode(t,e,r),e}function Ms(t){return sd.encodingLength(t)}function dg(t,e){let r=e.byteLength,n=Ms(t),i=n+Ms(r),o=new Uint8Array(i+r);return Ps(t,o,0),Ps(r,o,n),o.set(e,i),new da(t,r,e,o)}function p1(t){let e=ca(t),[r,n]=ua(e),[i,o]=ua(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new da(r,i,s,e)}function y1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&i1(t.bytes,r.bytes)}}var da=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function g1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return M6(r,lg(t),e??hr.encoder);default:return K6(r,lg(t),e??nd.encoder)}}var m1=new WeakMap;function lg(t){let e=m1.get(t);if(e==null){let r=new Map;return m1.set(t,r),r}return e}var hg=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!==cd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==$6)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=dg(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&&y1(e.multihash,n.multihash)}toString(e){return g1(this,e)}toJSON(){return{"/":g1(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??w1(n,i,o.bytes))}else if(r[H6]===!0){let{version:n,multihash:i,code:o}=r,s=p1(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!==cd)throw new Error(`Version 0 CID must use dag-pb (code: ${cd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=w1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,cd,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=ca(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 da(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]=ua(e.subarray(r));return r+=h,f},i=n(),o=cd;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]=P6(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 lg(o).set(n,e),o}};function P6(t,e){switch(t[0]){case"Q":{let r=e??hr;return[hr.prefix,r.decode(`${hr.prefix}${t}`)]}case hr.prefix:{let r=e??hr;return[hr.prefix,r.decode(t)]}case nd.prefix:{let r=e??nd;return[nd.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 M6(t,e,r){let{prefix:n}=r;if(n!==hr.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 K6(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 cd=112,$6=18;function w1(t,e,r){let n=Ms(t),i=n+Ms(e),o=new Uint8Array(i+r.byteLength);return Ps(t,o,0),Ps(e,o,n),o.set(r,i),o}var H6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Yt=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=Mi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Mi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Mi.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]=Mi.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}}};Yt.codeToName=new Map;Yt.nameToCode=new Map;Yt.registerCodec({code:237,name:"ed25519-pub"});Yt.registerCodec({code:4864,name:"ed25519-priv"});Yt.registerCodec({code:236,name:"x25519-pub"});Yt.registerCodec({code:4866,name:"x25519-priv"});Yt.registerCodec({code:231,name:"secp256k1-pub"});Yt.registerCodec({code:4865,name:"secp256k1-priv"});l();function pg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&pg(t[e])})}l();var zU=Pn(sm(),1),Qs=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 gh=class{constructor(){this.store=new Map}clear(){return Qs(this,void 0,void 0,function*(){this.store.clear()})}close(){return Qs(this,void 0,void 0,function*(){})}delete(e){return Qs(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return Qs(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return Qs(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return Qs(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return Qs(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var fk=Pn(ww(),1);var lk=Pn(ww(),1);l();l();l();l();l();function hk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function bw(t,...e){if(!hk(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 xw(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 TT(t,e){bw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var La=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),_n=(t,e)=>t<<32-e|t>>>e;var Uj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function pk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Ew(t){return typeof t=="string"&&(t=pk(t)),bw(t),t}var zh=class{clone(){return this._cloneInto()}},Oj={}.toString;function _T(t){let e=n=>t().update(Ew(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function BT(t=32){if(La&&typeof La.getRandomValues=="function")return La.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function yk(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 IT=(t,e,r)=>t&e^~t&r,RT=(t,e,r)=>t&e^t&r^e&r,Jh=class extends zh{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=Yh(this.buffer)}update(e){xw(this);let{view:r,buffer:n,blockLen:i}=this;e=Ew(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=Yh(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){xw(this),TT(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;yk(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Yh(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 gk=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]),jo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Wo=new Uint32Array(64),vw=class extends Jh{constructor(){super(64,32,8,!1),this.A=jo[0]|0,this.B=jo[1]|0,this.C=jo[2]|0,this.D=jo[3]|0,this.E=jo[4]|0,this.F=jo[5]|0,this.G=jo[6]|0,this.H=jo[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)Wo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Wo[f-15],p=Wo[f-2],g=_n(h,7)^_n(h,18)^h>>>3,y=_n(p,17)^_n(p,19)^p>>>10;Wo[f]=y+Wo[f-7]+g+Wo[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+IT(c,a,u)+gk[f]+Wo[f]|0,y=(_n(n,2)^_n(n,13)^_n(n,22))+RT(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(){Wo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Go=_T(()=>new vw);var mk=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())})},Pa=class{static digest(e){return mk(this,arguments,void 0,function*({data:r}){return Go(r)})}};l();var si=class{};var wk=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())})},Zh=class extends si{digest(e){return wk(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Pa.digest({data:n})}})}};l();l();l();l();l();l();function UT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function bk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Sw(t,...e){if(!bk(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 OT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");UT(t.outputLen),UT(t.blockLen)}function Ma(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 DT(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 Xh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function kT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Qh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,xk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!xk)throw new Error("Non little-endian hardware is not supported");function Aw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function $d(t){if(typeof t=="string"&&(t=Aw(t)),!kT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function ep(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!kT(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 Ka=class{clone(){return this._cloneInto()}},rW={}.toString;function tp(t){let e=n=>t().update($d(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Hd(t=32){if(Xh&&typeof Xh.getRandomValues=="function")return Xh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Ek(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 $a=class extends Ka{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){Ma(this);let{view:r,buffer:n,blockLen:i}=this;e=$d(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){Ma(this),DT(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;Ek(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 vk=(t,e,r)=>t&e^~t&r,Sk=(t,e,r)=>t&e^t&r^e&r,Ak=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]),zo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yo=new Uint32Array(64),Tw=class extends $a{constructor(){super(64,32,8,!1),this.A=zo[0]|0,this.B=zo[1]|0,this.C=zo[2]|0,this.D=zo[3]|0,this.E=zo[4]|0,this.F=zo[5]|0,this.G=zo[6]|0,this.H=zo[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)Yo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Yo[f-15],p=Yo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;Yo[f]=y+Yo[f-7]+g+Yo[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+vk(c,a,u)+Ak[f]+Yo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+Sk(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(){Yo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var rp=tp(()=>new Tw);l();var ip={};xu(ip,{bitGet:()=>Ok,bitLen:()=>Uk,bitMask:()=>Vd,bitSet:()=>Dk,bytesToHex:()=>Zi,bytesToNumberBE:()=>Xi,bytesToNumberLE:()=>Rn,concatBytes:()=>eo,createHmacDrbg:()=>Iw,ensureBytes:()=>Ge,equalBytes:()=>Ik,hexToBytes:()=>fc,hexToNumber:()=>Bw,isBytes:()=>In,numberToBytesBE:()=>yr,numberToBytesLE:()=>Qi,numberToHexUnpadded:()=>PT,numberToVarBytesBE:()=>Bk,utf8ToBytes:()=>Rk,validateObject:()=>on});l();var LT=BigInt(0),np=BigInt(1),Tk=BigInt(2);function In(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var _k=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zi(t){if(!In(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=_k[t[r]];return e}function PT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Bw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Ji={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function NT(t){if(t>=Ji._0&&t<=Ji._9)return t-Ji._0;if(t>=Ji._A&&t<=Ji._F)return t-(Ji._A-10);if(t>=Ji._a&&t<=Ji._f)return t-(Ji._a-10)}function fc(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=NT(t.charCodeAt(o)),c=NT(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 Xi(t){return Bw(Zi(t))}function Rn(t){if(!In(t))throw new Error("Uint8Array expected");return Bw(Zi(Uint8Array.from(t).reverse()))}function yr(t,e){return fc(t.toString(16).padStart(e*2,"0"))}function Qi(t,e){return yr(t,e).reverse()}function Bk(t){return fc(PT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=fc(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 eo(...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 Ik(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 Rk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Uk(t){let e;for(e=0;t>LT;t>>=np,e+=1);return e}function Ok(t,e){return t>>BigInt(e)&np}var Dk=(t,e,r)=>t|(r?np:LT)<<BigInt(e),Vd=t=>(Tk<<BigInt(t-1))-np,_w=t=>new Uint8Array(t),CT=t=>Uint8Array.from(t);function Iw(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=_w(t),i=_w(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=_w())=>{i=c(CT([0]),f),n=c(),f.length!==0&&(i=c(CT([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 eo(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var kk={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 on(t,e,r={}){let n=(i,o,s)=>{let c=kk[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),et=BigInt(1),lc=BigInt(2),Nk=BigInt(3),Rw=BigInt(4),MT=BigInt(5),KT=BigInt(8),Ck=BigInt(9),Lk=BigInt(16);function Be(t,e){let r=t%e;return r>=Tt?r:e+r}function Uw(t,e,r){if(r<=Tt||e<Tt)throw new Error("Expected power/modulo > 0");if(r===et)return Tt;let n=et;for(;e>Tt;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >Tt;)n*=n,n%=r;return n}function op(t,e){if(t===Tt||e<=Tt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Be(t,e),n=e,i=Tt,o=et,s=et,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!==et)throw new Error("invert: does not exist");return Be(i,e)}function Pk(t){let e=(t-et)/lc,r,n,i;for(r=t-et,n=0;r%lc===Tt;r/=lc,n++);for(i=lc;i<t&&Uw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/Rw;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+et)/lc;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,et<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function Mk(t){if(t%Rw===Nk){let e=(t+et)/Rw;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%KT===MT){let e=(t-MT)/KT;return function(n,i){let o=n.mul(i,lc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,lc),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%Lk,Pk(t)}var $T=(t,e)=>(Be(t,e)&et)===et,Kk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ow(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Kk.reduce((n,i)=>(n[i]="function",n),e);return on(t,r)}function $k(t,e,r){if(r<Tt)throw new Error("Expected power > 0");if(r===Tt)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>Tt;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function Hk(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 Dw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ha(t,e,r=!1,n={}){if(t<=Tt)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=Dw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Mk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Vd(i),ZERO:Tt,ONE:et,create:a=>Be(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&et)===et,neg:a=>Be(-a,t),eql:(a,u)=>a===u,sqr:a=>Be(a*a,t),add:(a,u)=>Be(a+u,t),sub:(a,u)=>Be(a-u,t),mul:(a,u)=>Be(a*u,t),pow:(a,u)=>$k(c,a,u),div:(a,u)=>Be(a*op(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>op(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Hk(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Qi(a,o):yr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Rn(a):Xi(a)}});return Object.freeze(c)}function HT(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 VT(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 kw(t){let e=VT(t);return e+Math.ceil(e/2)}function qT(t,e,r=!1){let n=t.length,i=VT(e),o=kw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Xi(t):Rn(t),c=Be(s,e-et)+et;return r?Qi(c,i):yr(c,i)}l();l();var qk=BigInt(0),Nw=BigInt(1);function sp(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>qk;)o&Nw&&(s=s.add(c)),c=c.double(),o>>=Nw;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+=Nw);let S=y,B=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[B]))}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 qd(t){return Ow(t.Fp),on(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Dw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Fk(t){let e=qd(t);on(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:jk,hexToBytes:Wk}=ip,hc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=hc;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:jk(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=hc,r=typeof t=="string"?Wk(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}=hc._parseInt(r.subarray(2)),{d:s,l:c}=hc._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}`}},to=BigInt(0),sn=BigInt(1),SW=BigInt(2),FT=BigInt(3),AW=BigInt(4);function Gk(t){let e=Fk(t),{Fp:r}=e,n=e.toBytes||((g,y,E)=>{let S=y.toAffine();return eo(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),B=r.mul(S,g);return r.add(r.add(B,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"&&to<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:B}=e;if(y&&typeof g!="bigint"){if(In(g)&&(g=Zi(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:Xi(Ge("private key",g,E))}catch{throw new Error(`private key must be ${E} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Be(A,B)),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 B=A=>r.eql(A,r.ZERO);return B(E)&&B(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,B)=>S.toAffine(E[B])).map(f.fromAffine)}static fromHex(y){let E=f.fromAffine(i(Ge("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),B=o(y);if(!r.eql(S,B))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:B}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(E,T),r.mul(A,B)),q=r.eql(r.mul(S,T),r.mul(O,B));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,FT),{px:B,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(B,B),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(B,A);return Q=r.add(Q,Q),q=r.mul(B,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:B}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,FT),Q=r.mul(E,A),G=r.mul(S,O),_=r.mul(B,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,B);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,B),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(B=>B.pz));return E.map((B,A)=>B.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let E=f.ZERO;if(y===to)return E;if(c(y),y===sn)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:B,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=E,q=E,j=this;for(;A>to||T>to;)A&sn&&(M=M.add(j)),T&sn&&(q=q.add(j)),j=j.double(),A>>=sn,T>>=sn;return B&&(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,B,{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),B=$.add(Q)}else{let{p:O,f:T}=this.wNAF(E);S=O,B=T}return f.normalizeZ([S,B])[0]}multiplyAndAddUnsafe(y,E,S){let B=f.BASE,A=(T,M)=>M===to||M===sn||!T.equals(B)?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:B}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(B));let O=r.mul(E,y),T=r.mul(S,y),M=r.mul(B,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===sn)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===sn?this:E?E(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Zi(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=sp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function zk(t){let e=qd(t);return on(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function jT(t){let e=zk(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(x){return to<x&&x<r.ORDER}function c(x){return Be(x,n)}function a(x){return op(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Gk({...e,toBytes(x,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=eo;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=Xi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&sn)===sn;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=>Zi(yr(x,e.nByteLength));function g(x){let U=n>>sn;return x>U}function y(x){return g(x)?c(-x):x}let E=(x,U,L)=>Xi(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=Ge("compactSignature",U,L*2),new S(E(U,0,L),E(U,L,2*L))}static fromDER(U){let{r:L,s:N}=hc.toSig(Ge("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(Ge("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 fc(this.toDERHex())}toDERHex(){return hc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let B={isValidPrivateKey(x){try{return d(x),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let x=kw(e.n);return qT(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=Xi(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=Vd(e.nBitLength);function $(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(to<=x&&x<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return yr(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=Ge("msgHash",x),P&&(x=Ge("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(Ge("extraEntropy",ee))}let Y=eo(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Re=a(ce),Me=u.BASE.multiply(ce).toAffine(),Je=c(Me.x);if(Je===to)return;let wt=c(Re*c(Z+Je*z));if(wt===to)return;let hi=(Me.x===Je?0:2)|Number(Me.y&sn),lo=wt;return C&&g(wt)&&(lo=y(wt),hi^=1),new S(Je,lo,hi)}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 Iw(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=Ge("msgHash",U),L=Ge("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(Me){if(!(Me instanceof hc.Err))throw Me;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Me,s:Je}=R;V=new S(Me,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Me){if(Me.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:B}}l();l();var cp=class extends Ka{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,OT(e);let n=$d(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 Ma(this),this.iHash.update(e),this}digestInto(e){Ma(this),Sw(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()}},Cw=(t,e,r)=>new cp(t,e).update(r).digest();Cw.create=(t,e)=>new cp(t,e);function Yk(t){return{hash:t,hmac:(e,...r)=>Cw(t,e,ep(...r)),randomBytes:Hd}}function ap(t,e){let r=n=>jT({...t,...Yk(n)});return Object.freeze({...r(e),create:r})}var zT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),WT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Jk=BigInt(1),Lw=BigInt(2),GT=(t,e)=>(t+e/Lw)/e;function Zk(t){let e=zT,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=ze(d,r,e)*d%e,h=ze(f,r,e)*d%e,p=ze(h,Lw,e)*u%e,g=ze(p,i,e)*p%e,y=ze(g,o,e)*g%e,E=ze(y,c,e)*y%e,S=ze(E,a,e)*E%e,B=ze(S,c,e)*y%e,A=ze(B,r,e)*d%e,O=ze(A,s,e)*g%e,T=ze(O,n,e)*u%e,M=ze(T,Lw,e);if(!Pw.eql(Pw.sqr(M),t))throw new Error("Cannot find square root");return M}var Pw=Ha(zT,void 0,void 0,{sqrt:Zk}),gr=ap({a:BigInt(0),b:BigInt(7),Fp:Pw,n:WT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=WT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Jk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=GT(o*t,e),a=GT(-n*t,e),u=Be(t-c*r-a*i,e),d=Be(-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}}}},rp),KW=BigInt(0);var $W=gr.ProjectivePoint;l();l();function YT(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 Xk=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())})},Mw="urn:jwk:";function ge(t){return Xk(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}`);pg(n);let i=YT(n),o=ne.string(i).toUint8Array(),s=yield Pa.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ci(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 Va(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 ai(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 qa(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 JT(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())})},Qk=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=gr.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 gr.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 gr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return gr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Kt(this,void 0,void 0,function*(){let e=gr.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(!(ci(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=Qk(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(!ci(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(!(Va(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 gr.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=Go(r);return gr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){return gr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){try{gr.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=Go(i);return gr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Kt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=gr.getPublicKey(r));let n=gr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y:o}})}};l();l();var ZT=Ha(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),eN=ZT.create(BigInt("-3")),tN=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),rN=ap({a:eN,b:tN,Fp:ZT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},rp),Cr=rN;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())})},nN=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=Cr.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 Cr.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 Cr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=Cr.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(!(ci(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=nN(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(!ci(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(!(Va(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 Cr.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=Go(r);return Cr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return Cr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{Cr.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=Go(i);return Cr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Cr.getPublicKey(r));let n=Cr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y: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())})},jd=class extends si{computePublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ci(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 Fd(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 Fd(this,arguments,void 0,function*({key:r}){if(!ci(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 Fd(this,arguments,void 0,function*({key:r,data:n}){if(!ci(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 Fd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Va(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 up=BigInt(4294967295),Kw=BigInt(32);function XT(t,e=!1){return e?{h:Number(t&up),l:Number(t>>Kw&up)}:{h:Number(t>>Kw&up)|0,l:Number(t&up)|0}}function iN(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}=XT(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var oN=(t,e)=>BigInt(t>>>0)<<Kw|BigInt(e>>>0),sN=(t,e,r)=>t>>>r,cN=(t,e,r)=>t<<32-r|e>>>r,aN=(t,e,r)=>t>>>r|e<<32-r,uN=(t,e,r)=>t<<32-r|e>>>r,dN=(t,e,r)=>t<<64-r|e>>>r-32,fN=(t,e,r)=>t>>>r-32|e<<64-r,lN=(t,e)=>e,hN=(t,e)=>t,pN=(t,e,r)=>t<<r|e>>>32-r,yN=(t,e,r)=>e<<r|t>>>32-r,gN=(t,e,r)=>e<<r-32|t>>>64-r,mN=(t,e,r)=>t<<r-32|e>>>64-r;function wN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var bN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),xN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,EN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),vN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,SN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),AN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var TN={fromBig:XT,split:iN,toBig:oN,shrSH:sN,shrSL:cN,rotrSH:aN,rotrSL:uN,rotrBH:dN,rotrBL:fN,rotr32H:lN,rotr32L:hN,rotlSH:pN,rotlSL:yN,rotlBH:gN,rotlBL:mN,add:wN,add3L:bN,add3H:xN,add4L:EN,add4H:vN,add5H:AN,add5L:SN},le=TN;var[_N,BN]=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))),Jo=new Uint32Array(80),Zo=new Uint32Array(80),$w=class extends $a{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)Jo[A]=e.getUint32(r),Zo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Jo[A-15]|0,T=Zo[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=Jo[A-2]|0,$=Zo[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,Zo[A-7],Zo[A-16]),_=le.add4H(G,M,X,Jo[A-7],Jo[A-16]);Jo[A]=_|0,Zo[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:B}=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(B,T,q,BN[A],Zo[A]),$=le.add5H(j,S,O,M,_N[A],Jo[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,B=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:B}=le.add(this.Hh|0,this.Hl|0,S|0,B|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,E,S,B)}roundClean(){Jo.fill(0),Zo.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 Hw=tp(()=>new $w);l();var Un=BigInt(0),Lr=BigInt(1),dp=BigInt(2),IN=BigInt(8),RN={zip215:!0};function UN(t){let e=qd(t);return on(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function fp(t){let e=UN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=dp<<BigInt(c*8)-Lr,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 B(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,Lr,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)),Re=d(ue+d(C*d(W*Y)));if(ce!==Re)throw new Error("bad point: equation left != right (1)");let Me=d(P*V),Je=d(J*z);if(Me!==Je)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(dp*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Re=Y-z,Me=d(ue*ce),Je=d(ee*Re),wt=d(ue*Re),hi=d(ce*ee);return new T(Me,Je,hi,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 lu=d((J-V)*(Z+Y)),Ef=d((J+V)*(Z-Y)),hu=d(Ef-lu);if(hu===Un)return this.double();let vf=d(z*dp*ee),Sf=d(W*dp*ue),Wr=Sf+vf,po=Ef+lu,pu=Sf-vf,Af=d(Wr*hu),us=d(po*pu),Tf=d(Wr*pu),ry=d(hu*po);return new T(Af,us,ry,Tf)}let ce=d(V*Y),Re=d(J*Z),Me=d(W*P*ee),Je=d(z*ue),wt=d((V+J)*(Y+Z)-ce-Re),hi=Je-Me,lo=Je+Me,fu=d(Re-C*ce),xf=d(wt*hi),ty=d(lo*fu),ho=d(wt*fu),jr=d(hi*lo);return new T(xf,ty,jr,ho)}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=B(R);return C===Un?q:this.equals(q)||C===Lr?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?IN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Un,y:Lr};if(Y!==Lr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Lr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Ge("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-Lr),ee=d(P*Z-V),{isValid:ce,value:Re}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Re&Lr)===Lr,Je=(W&128)!==0;if(!C&&Re===Un&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Me&&(Re=d(-Re)),T.fromAffine({x:Re,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Qi(C,r.BYTES);return P[P.length-1]|=R&Lr?128:0,P}toHex(){return Zi(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Lr,d(e.Gx*e.Gy)),T.ZERO=new T(Un,Lr,Lr,Un);let{BASE:M,ZERO:q}=T,j=sp(T,c*8);function $(N){return Be(N,n)}function X(N){return $(Rn(N))}function Q(N){let R=c;N=Ge("private key",N,R);let C=Ge("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=eo(...R);return X(o(p(C,Ge("context",N),!!i)))}function D(N,R,C={}){N=Ge("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);B(Z);let ue=eo(W,Qi(Z,r.BYTES));return Ge("result",ue,c*2)}let x=RN;function U(N,R,C,P=x){let{context:V,zip215:J}=P,z=r.BYTES;N=Ge("signature",N,2*z),R=Ge("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 Wd=BigInt(0),Vw=BigInt(1);function ON(t){return on(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function QT(t){let e=ON(t),{P:r}=e,n=A=>Be(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>Uw(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"&&Wd<=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=Vw,$=Wd,X=T,Q=Vw,G=Wd,_;for(let x=BigInt(i-1);x>=Wd;x--){let U=M>>x&Vw;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 Qi(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),Rn(O)}function y(A){let O=Ge("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===Wd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function B(A){return E(A,S)}return{scalarMult:E,scalarMultBase:B,getSharedSecret:(A,O)=>E(A,O),getPublicKey:A=>B(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Gd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),e_=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),VG=BigInt(0),DN=BigInt(1),qw=BigInt(2),kN=BigInt(5),t_=BigInt(10),NN=BigInt(20),CN=BigInt(40),r_=BigInt(80);function n_(t){let e=Gd,n=t*t%e*t%e,i=ze(n,qw,e)*n%e,o=ze(i,DN,e)*t%e,s=ze(o,kN,e)*o%e,c=ze(s,t_,e)*s%e,a=ze(c,NN,e)*c%e,u=ze(a,CN,e)*a%e,d=ze(u,r_,e)*u%e,f=ze(d,r_,e)*u%e,h=ze(f,t_,e)*s%e;return{pow_p_5_8:ze(h,qw,e)*t%e,b2:n}}function i_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function LN(t,e){let r=Gd,n=Be(e*e*e,r),i=Be(n*n*e,r),o=n_(t*i).pow_p_5_8,s=Be(t*n*o,r),c=Be(e*s*s,r),a=s,u=Be(s*e_,r),d=c===t,f=c===Be(-t,r),h=c===Be(-t*e_,r);return d&&(s=a),(f||h)&&(s=u),$T(s,r)&&(s=Be(-s,r)),{isValid:d||f,value:s}}var cn=Ha(Gd,void 0,!0),zd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:cn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Hw,randomBytes:Hd,adjustScalarBytes:i_,uvRatio:LN},Xo=fp(zd);function o_(t,e,r){if(e.length>255)throw new Error("Context is too big");return ep(Aw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var qG=fp({...zd,domain:o_}),FG=fp({...zd,domain:o_,prehash:Hw}),pc=QT({P:Gd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Gd,{pow_p_5_8:r,b2:n}=n_(t);return Be(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:i_,randomBytes:Hd});function s_(t){let{y:e}=Xo.ExtendedPoint.fromHex(t),r=BigInt(1);return cn.toBytes(cn.create((r+e)*cn.inv(r-e)))}function c_(t){let e=zd.hash(t.subarray(0,32));return zd.adjustScalarBytes(e).subarray(0,32)}var PN=(cn.ORDER+BigInt(3))/BigInt(8),jG=cn.pow(qw,PN),WG=cn.sqrt(cn.neg(cn.ONE)),GG=(cn.ORDER-BigInt(5))/BigInt(8),zG=BigInt(486662);var YG=HT(cn,cn.neg(BigInt(486664)));var JG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ZG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),XG=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),QG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ez=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var an=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())})},MN=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 an(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Xo.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 an(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 an(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Xo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return an(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=c_(n),o=pc.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 an(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=s_(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return an(this,void 0,void 0,function*(){let e=Xo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return an(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=MN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return an(this,arguments,void 0,function*({privateKey:r}){if(!ai(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 an(this,arguments,void 0,function*({publicKey:r}){if(!qa(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 an(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Xo.sign(n,i)})}static validatePublicKey(e){return an(this,arguments,void 0,function*({publicKeyBytes:r}){try{Xo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return an(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Xo.verify(n,i,o)})}};var Yd=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())})},lp=class extends si{computePublicKey(e){return Yd(this,arguments,void 0,function*({key:r}){if(!ai(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 Yd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield _t.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Yd(this,arguments,void 0,function*({key:r}){if(!ai(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 Yd(this,arguments,void 0,function*({key:r,data:n}){if(!ai(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 Yd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!qa(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 ro=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())})},Fw={Ed25519:{implementation:lp,names:["Ed25519"]},secp256k1:{implementation:jd,names:["ES256K","secp256k1"]},secp256r1:{implementation:jd,names:["ES256","secp256r1"]},"SHA-256":{implementation:Zh,names:["SHA-256"]}},Qt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new gh}digest(e){return ro(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return ro(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return ro(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=`${Mw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return ro(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Mw}${n}`})}getPublicKey(e){return ro(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 ro(this,arguments,void 0,function*({key:r}){var n;if(!JT(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 ro(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 ro(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=Fw[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 Fw){let o=Fw[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 ro(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 hp=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 BT(e)}static randomUuid(){return La.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 Qo=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())})},KN=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},Fa=class t{static bytesToPrivateKey(e){return Qo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=pc.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 Qo(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 Qo(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=pc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return Qo(this,void 0,void 0,function*(){let e=pc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Qo(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=KN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Qo(this,arguments,void 0,function*({privateKey:r}){if(!ai(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 Qo(this,arguments,void 0,function*({publicKey:r}){if(!qa(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 Qo(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 pc.getSharedSecret(i,o)})}};l();l();l();function Pr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Gw({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(Ww))!==null&&r!==void 0?r:[]),Object.keys(Pi).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Ww))!==null&&s!==void 0?s:[])}),n}function a_({didDocument:t}){let r=Gw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function u_({didDocument:t,methodId:e}){let r=[];return Object.keys(Pi).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Pr(e);i.some(c=>{let a=Pr(c)===o,u=Ww(c)&&Pr(c.id)===o;return a||u})&&r.push(n)}}),r}function d_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Ww(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 zw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Yt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Yw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=Yt.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())})},mr=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 Pr(a.id)===((u=Pr(e?.methodId))!==null&&u!==void 0?u:Pr((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:hp.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 Qt}){var i;let o=Gw({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 Jw="0123456789abcdef",l_=[],f_=[];for(let t=0;t<256;t++)l_[t]=Jw[t>>4&15]+Jw[t&15],t<16&&(t<10?f_[48+t]=t:f_[87+t]=t);var Zw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=l_[t[n++]];return r};var h_=(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 p_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",HN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Zd=0;Zd<p_.length;Zd++)HN[p_.charCodeAt(Zd)]=Zd;var Zd;var VN=new TextDecoder,Xw=(t,e)=>e?new TextDecoder(e).decode(t):VN.decode(t),qN=new TextEncoder,un=t=>qN.encode(t);var y_=typeof window<"u"?window:self,g_=y_.crypto||y_.msCrypto||{},eJ=g_.subtle||g_.webkitSubtle;l();function ja(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function pp(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 Ie(t,e,r){let n=[],i=null;return Ie._encode(n,t),i=h_(n),Ie.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Ie.bytes=-1;Ie._floatConversionDetected=!1;Ie._encode=function(t,e){if(e!=null)switch(pp(e)){case"object":Ie.dict(t,e);break;case"map":Ie.dictMap(t,e);break;case"array":Ie.list(t,e);break;case"set":Ie.listSet(t,e);break;case"string":Ie.string(t,e);break;case"number":Ie.number(t,e);break;case"boolean":Ie.number(t,e);break;case"arraybufferview":Ie.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Ie.buffer(t,new Uint8Array(e));break}};var yp=new Uint8Array([101]),m_=new Uint8Array([100]),w_=new Uint8Array([108]);Ie.buffer=function(t,e){t.push(un(e.length+":"),e)};Ie.string=function(t,e){t.push(un(un(e).byteLength+":"+e))};Ie.number=function(t,e){if(Number.isInteger(e))return t.push(un("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(un("i"+o+"e")),o!==e&&!Ie._floatConversionDetected&&(Ie._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())};Ie.dict=function(t,e){t.push(m_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Ie.string(t,n),Ie._encode(t,e[n]));t.push(yp)};Ie.dictMap=function(t,e){t.push(m_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Ie._encode(t,n):Ie.string(t,String(n)),Ie._encode(t,e.get(n)));t.push(yp)};Ie.list=function(t,e){let r=0,n=e.length;for(t.push(w_);r<n;r++)e[r]!=null&&Ie._encode(t,e[r]);t.push(yp)};Ie.listSet=function(t,e){t.push(w_);for(let r of e)r!=null&&Ie._encode(t,r);t.push(yp)};var b_=Ie;l();var FN=105,jN=58,WN=100,GN=108,Qw=101;function x_(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)):un(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 WN:return de.dictionary();case GN:return de.list();case FN: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]!==Qw;){let e=de.buffer(),r=Xw(e);r.includes("\uFFFD")&&(r=Zw(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==Qw;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(Qw),e=x_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(jN),e=x_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?Xw(de.data.slice(t,r)):de.data.slice(t,r)};var E_=de;l();function zN(t){let e=2;for(let r of t)e+=gp(r);return e}function YN(t){let e=2;for(let[r,n]of t){let i=un(r).byteLength;e+=ja(i)+1+i,e+=gp(n)}return e}function JN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=un(r[n]).byteLength;e+=ja(i)+1+i,e+=gp(t[r[n]])}return e}function ZN(t){let e=un(t).byteLength;return ja(e)+1+e}function XN(t){let e=t.byteLength-t.byteOffset;return ja(e)+1+e}function gp(t){if(t==null)return 0;let r=pp(t);switch(r){case"arraybufferview":return XN(t);case"string":return ZN(t);case"array":case"set":return zN(t);case"number":return 1+ja(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return JN(t);case"map":return YN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var eb=gp;var QN=eb,tb={encode:b_,decode:E_,byteLength:eb,encodingLength:QN};l();l();var eC=/^(\d{1,3}\.){3,3}\d{1,3}$/;var tC=/^(::)?(((\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=>eC.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]}`}},no={name:"v6",size:16,isFormat:t=>t.length>0&&tC.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 v_(t){if(On.isFormat(t))return On.size;if(no.isFormat(t))return no.size;throw Error(`Invalid ip address: ${t}`)}function S_(t){return v_(t)===On.size?1:2}function A_(t,e,r){r=~~r;let n=v_(t);return typeof e=="function"&&(e=e(r+n)),n===On.size?On.encode(t,e,r):no.encode(t,e,r)}function T_(t,e,r){if(e=~~e,r=r||t.length-e,r===On.size)return On.decode(t,e,r);if(r===no.size)return no.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${On.size} for v4 or ${no.size} for v6.`)}l();function Xd(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 Wa(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 __(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 B_(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 rb(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 nb(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 I_(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 ib(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 ob(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 Ga(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(ob(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 Ga.bytes=i-r,e}Ga.bytes=0;function za(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 za.bytes=r-e,n}za.bytes=0;var es=t=>t instanceof Uint8Array;function io(t){return typeof t=="string"?ob(t):t.byteLength}function mp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Ga(t)}function wp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Ga(e,t,r),Ga.bytes}var Qd={},R_=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}`;R_[s]=c,Qd[c]=s,Qd[`${r}${i}`]=s,Qd[`${e}${o}`]=s,Qd[`${r}${o}`]=s}}function U_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=R_[o]}return n}function sb(t){return t.length>>>1}function O_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=Qd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var uC=Math.pow(2,24),dC=Math.pow(2,16),fC=Math.pow(2,8),ui=(t,e)=>t[e]*uC+t[e+1]*dC+t[e+2]*fC+t[e+3],he=(t,e)=>t[e]<<8|t[e+1],di=(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 wr(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:lC(t,e,r,n,i)}function lC(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 pC=0,D_=32768,ab=32768,yC=~ab,N_=32768,gC=~N_;function $e({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=$e({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=wp(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(za(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:io(t.replace(/^\.|\.$/gm,""))+2}}),Bt=$e({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=wp(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=za(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return io(t)+1}}),Ya=$e({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Ya.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?D_:pC;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&D_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:B_(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:__(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}}),xp=$e({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),wr(t,e,r+2,0,n),xp.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 xp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),Ep=$e({encode(t,e,r){return e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Ep.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 Ep.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),vp=$e({encode(t,e,r){e||(e=new Uint8Array(vp.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,di(e,t.serial||0,r),r+=4,di(e,t.refresh||0,r),r+=4,di(e,t.retry||0,r),r+=4,di(e,t.expire||0,r),r+=4,di(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),vp.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=ui(t,e),e+=4,n.refresh=ui(t,e),e+=4,n.retry=ui(t,e),e+=4,n.expire=ui(t,e),e+=4,n.minimum=ui(t,e),e+=4,vp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),Sp=$e({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=mp(t[i])),!es(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(Sp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,wr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),Sp.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 Sp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=io(r)+1:e+=r.length+1}),e}}),Ap=$e({encode(t,e,r){e||(e=new Uint8Array(Ap.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=mp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return wr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),Ap.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,Ap.decode.bytes=e-r,i},encodingLength(t){return t?(es(t)?t.length:io(t))+2:2}}),Tp=$e({encode(t,e,r){e||(e=new Uint8Array(Tp.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),Tp.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,Tp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),Xa=$e({encode(t,e,r){return e||(e=new Uint8Array(Xa.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Xa.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return Xa.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),_p=$e({encode(t,e,r){e||(e=new Uint8Array(_p.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),_p.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),_p.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),ts=$e({encode(t,e,r){let n=ts.encodingLength(t);return e||(e=new Uint8Array(ts.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=ts.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,wp(e,t.value,r),r+=io(t.value),ts.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=za(t,e,n+r),i.issuerCritical=!!(i.flags&ts.ISSUER_CRITICAL),ts.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});ts.ISSUER_CRITICAL=128;var Bp=$e({encode(t,e,r){e||(e=new Uint8Array(Bp.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),Bp.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,Bp.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),C_=$e({encode(t,e,r){return e||(e=new Uint8Array(C_.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}),Ip=$e({encode(t,e,r){return e||(e=new Uint8Array(Ip.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,no.encode(t,e,r),Ip.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=no.decode(t,e);return Ip.decode.bytes=18,r},bytes:18}),k_=t=>new Uint8Array(t),oo=$e({encode(t,e,r){e||(e=new Uint8Array(oo.encodingLength(t))),r||(r=0);let n=r,i=ib(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,wr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||S_(t.ip,k_),c=A_(t.ip,k_),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,wr(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 oo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=I_(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);wr(t,i,0,e,e+n-4),r.ip=T_(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 oo.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(ib(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}`)}}),rs=$e({encode(t,e,r){e||(e=new Uint8Array(rs.encodingLength(t))),r||(r=0);let n=r,i=Za(t,oo);return ae(e,i,r),r=sf(t,oo,e,r+2),rs.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++]=oo.decode(t,e),e+=oo.decode.bytes,i-=oo.decode.bytes;return rs.decode.bytes=e-r,n},encodingLength(t){return 2+Za(t||[],oo)}}),fi=$e({encode(t,e,r){e||(e=new Uint8Array(fi.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!es(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=fi.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,wr(i,e,r,0,i.length),r+=i.length,fi.encode.bytes=r-n,ae(e,fi.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]!==fi.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,fi.decode.bytes=e-r,n},encodingLength(t){return 6+io(t.key)}});fi.PROTOCOL_DNSSEC=3;fi.ZONE_KEY=128;fi.SECURE_ENTRYPOINT=32768;var ef=$e({encode(t,e,r){e||(e=new Uint8Array(ef.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!es(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Wa(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,di(e,t.originalTTL,r),r+=4,di(e,t.expiration,r),r+=4,di(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,wr(i,e,r,0,i.length),r+=i.length,ef.encode.bytes=r-n,ae(e,ef.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.typeCovered=Xd(he(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=ui(t,e),e+=4,n.expiration=ui(t,e),e+=4,n.inception=ui(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,ef.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+io(t.signature)}}),tf=$e({encode(t,e,r){e||(e=new Uint8Array(tf.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,tf.encode.bytes=r-n,ae(e,tf.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,tf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Mr=$e({encode(t,e,r){e||(e=new Uint8Array(Mr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Wa(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=mp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,wr(s,e,r,0,s.length),r+=s.length}return Mr.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=Xd(o<<8|c<<3|u);i.push(d)}}e+=s}return Mr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Wa(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}}),rf=$e({encode(t,e,r){e||(e=new Uint8Array(rf.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,rf.encode.bytes=r-n,ae(e,rf.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=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,rf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Mr.encodingLength(t.rrtypes)}}),nf=$e({encode(t,e,r){e||(e=new Uint8Array(nf.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!es(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!es(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,wr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,wr(o,e,r,0,o.length),r+=o.length,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,nf.encode.bytes=r-n,ae(e,nf.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=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,nf.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Mr.encodingLength(t.rrtypes)}}),of=$e({encode(t,e,r){e||(e=new Uint8Array(of.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!es(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,wr(i,e,r,0,i.length),r+=i.length,of.encode.bytes=r-n,ae(e,of.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,of.decode.bytes=e-r,n},encodingLength(t){return 6+io(t.digest)}}),Ja=$e({encode(t,e,r){e||(e=new Uint8Array(Ja.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=sb(t.fingerprint),o=ub(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return O_(e,t.fingerprint,r,r+=i),Ja.encode.bytes=r-n,ae(e,Ja.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=ub(n.hash);return n.fingerprint=U_(t,e,e+i),e+=i,Ja.decode.bytes=e-r,n},encodingLength(t){return 4+sb(t.fingerprint)}});function ub(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Ja.getFingerprintLengthForHashType=ub;function cb(t){switch(t.toUpperCase()){case"A":return C_;case"PTR":return Xa;case"CNAME":return Xa;case"DNAME":return Xa;case"TXT":return Sp;case"NULL":return Ap;case"AAAA":return Ip;case"SRV":return _p;case"HINFO":return Tp;case"CAA":return ts;case"NS":return Ep;case"SOA":return vp;case"MX":return Bp;case"OPT":return rs;case"DNSKEY":return fi;case"RRSIG":return ef;case"RP":return tf;case"NSEC":return rf;case"NSEC3":return nf;case"SSHFP":return Ja;case"DS":return of}return xp}var dn=$e({encode(t,e,r){e||(e=new Uint8Array(dn.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Wa(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,rs.encode(t.options||[],e,r),r+=rs.encode.bytes}else{let i=nb(t.class===void 0?"IN":t.class);t.flush&&(i|=ab),ae(e,i,r+2),di(e,t.ttl||0,r+4),r+=8;let o=cb(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return dn.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=Xd(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=rs.decode(t,e+8),e+=8+rs.decode.bytes;else{let i=he(t,e+2);r.ttl=ui(t,e+4),r.class=rb(i&yC),r.flush=!!(i&ab);let o=cb(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return dn.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+cb(t.type).encodingLength(e)}}),Qa=$e({encode(t,e,r){e||(e=new Uint8Array(Qa.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Wa(t.type),r),r+=2,ae(e,nb(t.class===void 0?"IN":t.class),r),r+=2,Qa.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=Xd(he(t,e)),e+=2,n.class=rb(he(t,e)),e+=2,!!(n.class&N_)&&(n.class&=gC),Qa.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var L_=1024;var Vt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(mC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Ya.encode(t,e,r),r+=Ya.encode.bytes,r=sf(t.questions,Qa,e,r),r=sf(t.answers,dn,e,r),r=sf(t.authorities,dn,e,r),r=sf(t.additionals,dn,e,r),Vt.encode.bytes=r-i,n&&cf.bytes!==e.length?e.slice(0,cf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Ya.decode(t,e);return e+=Ya.decode.bytes,e=bp(n.questions,Qa,t,e),e=bp(n.answers,dn,t,e),e=bp(n.authorities,dn,t,e),e=bp(n.additionals,dn,t,e),Vt.decode.bytes=e-r,n},encodingLength:function(t){return Ya.encodingLength(t)+Za(t.questions||[],Qa)+Za(t.answers||[],dn)+Za(t.authorities||[],dn)+Za(t.additionals||[],dn)}};Vt.encode.bytes=0;Vt.decode.bytes=0;function Rp(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 Up={encode:function(t,e,r){return e=Vt.encode(Rp(t,"query"),e,r),Up.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Up.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Rp(t,"query"))}};Up.encode.bytes=0;Up.decode.bytes=0;var Op={encode:function(t,e,r){return e=Vt.encode(Rp(t,"response"),e,r),Op.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Op.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Rp(t,"response"))}};Op.encode.bytes=0;Op.decode.bytes=0;var cf=Vt.encode,Dp=Vt.decode,mC=Vt.encodingLength;function P_(t){let e=cf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),wr(e,r,2,0,e.length),P_.bytes=r.byteLength,r}P_.bytes=0;function M_(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=Dp(t.slice(2));return M_.bytes=Dp.bytes,r}M_.bytes=0;function Za(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function sf(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 bp(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 K_=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())})},fn=class{static getSigningMethod(e){return K_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return K_(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())})},$_=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},H_="https://diddht.tbddev.org",wC=0,ns=7200,kp=";",or=",",db;(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"})(db||(db={}));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 fb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(fb||(fb={}));var q_={Ed25519:sr.Ed25519,ES256K:sr.secp256k1,ES256:sr.secp256r1,"P-256":sr.secp256r1,secp256k1:sr.secp256k1,secp256r1:sr.secp256r1,X25519:sr.X25519},V_={[sr.Ed25519]:"EdDSA",[sr.secp256k1]:"ES256K",[sr.secp256r1]:"ES256",[sr.X25519]:"ECDH-ES+A256KW"},af=class t extends fn{static create(){return kt(this,arguments,void 0,function*({keyManager:e=new Qt,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 q_)))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}),B=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}#${Pr(j)}`,(u=B.verificationMethod)!==null&&u!==void 0||(B.verificationMethod=[]),B.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:[])B[$]||(B[$]=[]),B[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=B.service)!==null&&M!==void 0||(B.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,B.service.push(T)});let O=new mr({uri:S,document:B,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 Qt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield mr.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 Pr(c.id)===((a=Pr(n))!==null&&a!==void 0?a:Pr((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=H_}){return yield Np.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:H_;try{yield Dt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Np.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})})}})}};af.methodName="dht";var Np=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(),B=sr[Number(p)],A=yield Dt.keyConverter(B).bytesToPublicKey({publicKeyBytes:S});A.alg=E||V_[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=$_(h,["id","t","se"]),S=y.includes(or)?y.split(or):[y],B=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({},B),{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=B=>B.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:B,previousDid:A}=o;yield Dt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:ns,data:`id=${A};s=${B}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:ns,data:r.alsoKnownAs.join(or)}),r.controller){let B=Array.isArray(r.controller)?r.controller.join(or):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:ns,data:B})}for(let[B,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${B}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in q_))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!==V_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:ns,data:X.join(kp)})}(u=r.service)===null||u===void 0||u.forEach((B,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=B,j=$_(B,["id","type","serviceEndpoint"]);T=Pr(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(kp),Q=Dt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:ns,data:Q})});let E=[`v=${wC}`];if(y.length&&E.push(`vm=${y.join(or)}`),Object.keys(Pi).forEach(B=>{var A;let O=(A=r[B])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=fb[B];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"?db[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:ns,data:`id=${A.join(or)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:ns,data:E.join(kp)});for(let B of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:ns,data:B+"."});return{id:0,type:"response",flags:L_,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=cf(r),c=tb.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!==af.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:${af.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:Fa}[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=tb.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 Dp(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(kp).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 Ye={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 Pe=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var eZ=new Uint8Array(0);var lb=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 hb=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")}},pb=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 F_(this,e)}},yb=class{constructor(e){this.decoders=e}or(e){return F_(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`)}},F_=(t,e)=>new yb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),gb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new hb(e,r,n),this.decoder=new pb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},bC=({name:t,prefix:e,encode:r,decode:n})=>new gb(t,e,r,n);var xC=(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},EC=(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},uf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>bC({prefix:e,name:t,encode(i){return EC(i,n,r)},decode(i){return xC(i,n,r,t)}});var fZ=uf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lZ=uf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),df=uf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hZ=uf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var br=class t{static encode(e){return df.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Pe(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return df.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 tB=Pn(W_(),1);l();l();var mb;(function(t){t.Public="public",t.Private="private"})(mb||(mb={}));var Kr=mb;var It=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Kr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Pe(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Pe(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Pe(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Kr.Private&&(e.d===void 0||e.d.length!==43))throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Pe(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!br.isBase64UrlString(e))throw new Pe(Ye.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 Pe(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var ff=class{};ff.hashAlgorithmInMultihashCode=18;ff.maxCanonicalizedDeltaSizeInBytes=1e3;var cr=ff;l();var Y_=Pn(z_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=Y_.default(r);return br.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 vC=X_,J_=128,SC=127,AC=~SC,TC=Math.pow(2,31);function X_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=TC;)e[r++]=t&255|J_,t/=128;for(;t&AC;)e[r++]=t&255|J_,t>>>=7;return e[r]=t|0,X_.bytes=r-n+1,e}var _C=wb,BC=128,Z_=127;function wb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw wb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&Z_)<<i:(s&Z_)*Math.pow(2,i),i+=7}while(s>=BC);return wb.bytes=o-n,r}var IC=Math.pow(2,7),RC=Math.pow(2,14),UC=Math.pow(2,21),OC=Math.pow(2,28),DC=Math.pow(2,35),kC=Math.pow(2,42),NC=Math.pow(2,49),CC=Math.pow(2,56),LC=Math.pow(2,63),PC=function(t){return t<IC?1:t<RC?2:t<UC?3:t<OC?4:t<DC?5:t<kC?6:t<NC?7:t<CC?8:t<LC?9:10},MC={encode:vC,decode:_C,encodingLength:PC},KC=MC,lf=KC;var bb=(t,e=0)=>[lf.decode(t,e),lf.decode.bytes],xb=(t,e,r=0)=>(lf.encode(t,e,r),e),Eb=t=>lf.encodingLength(t);var vb=(t,e)=>{let r=e.byteLength,n=Eb(t),i=n+Eb(r),o=new Uint8Array(i+r);return xb(t,o,0),xb(r,o,n),o.set(e,i),new Lp(t,r,e,o)},Q_=t=>{let e=lb(t),[r,n]=bb(e),[i,o]=bb(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Lp(r,i,s,e)};var Lp=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var Ab=({name:t,code:e,encode:r})=>new Sb(t,e,r),Sb=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?vb(this.code,r):r.then(n=>vb(this.code,n))}else throw Error("Unknown type, must be binary type")}};var eB=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pp=Ab({name:"sha2-256",code:18,encode:eB("SHA-256")}),GZ=Ab({name:"sha2-512",code:19,encode:eB("SHA-512")});var hf=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 hf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Pp.digest(e)).bytes;break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return hf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Pp.encode(e);break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return hf(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return hf(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 hf(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return br.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=br.decodeAsBytes(e,r);try{n=Q_(i)}catch{throw new Pe(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=cr.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var Tb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(Tb||(Tb={}));var pf=Tb;l();var _b;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(_b||(_b={}));var yc=_b;var Mp=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())})},is=class t{static createCreateRequest(e){return Mp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;It.validateEs256kOperationKey(r,Kr.Public),It.validateEs256kOperationKey(n,Kr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=cr.hashAlgorithmInMultihashCode,c=[{action:yc.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:pf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Mp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Kr.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:pf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Mp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextRecoveryPublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:yc.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:pf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Mp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.updatePublicKey,Kr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.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:yc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:yc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:yc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:yc.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:pf.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 Pe(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(It.validateId(n.id),r.has(n.id))throw new Pe(Ye.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 Pe(Ye.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 Pe(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Pe(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&tB.parse(e.serviceEndpoint).error!==void 0)throw new Pe(Ye.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 Pe(Ye.DeltaExceedsMaximumSize,n)}}};var rB=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())})},eu=class t{static createLongFormDid(e){return rB(this,void 0,void 0,function*(){let r=yield is.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=br.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return rB(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Nt.hash(r,cr.hashAlgorithmInMultihashCode);return br.encode(n)})}};l();l();var nB;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(nB||(nB={}));l();var iB;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(iB||(iB={}));l();var os=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())})},li;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(li||(li={}));var VC={Ed25519:li.Ed25519,ES256K:li.secp256k1,ES256:li.secp256r1,"P-256":li.secp256r1,secp256k1:li.secp256k1,secp256r1:li.secp256r1},oB="https://ion.tbd.engineering",Bb=class t extends fn{static create(){return os(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in VC)))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:li.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:li.secp256k1}),E=yield e.getPublicKey({keyUri:y}),S=yield gc.computeLongFormDidUri({recoveryKey:g,updateKey:E,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:B,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(B===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new mr({uri:S,document:B,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 os(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 os(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield mr.import({portableDid:r,keyManager:n})})}static publish(e){return os(this,arguments,void 0,function*({did:r,gatewayUri:n=oB}){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:u_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield gc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield gc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=gc.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 os(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:oB;try{let a=gc.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})})}})}};Bb.methodName="ion";var gc=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 os(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 eu.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return os(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield is.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return os(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())})},Ib=class t extends fn{static create(){return Kp(this,arguments,void 0,function*({keyManager:e=new Qt,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 mr({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 Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.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})})}};Ib.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())})},so;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(so||(so={}));var Rb={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"},qC={Ed25519:so.Ed25519,ES256K:so.secp256k1,ES256:so.secp256r1,"P-256":so.secp256r1,secp256k1:so.secp256k1,secp256r1:so.secp256r1,X25519:so.X25519},Ub=class t extends fn{static create(){return kn(this,arguments,void 0,function*({keyManager:e=new Qt,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 xr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new mr({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 Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.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 a_({didDocument:a}).forEach(g=>{let y=Rb[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=xr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=zw({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 Rb))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 xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.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}=Yw({multibaseKeyId:n}),f=a.byteLength,h=xr.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 Rb))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 xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.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}=Yw({multibaseKeyId:r});if(o===237){let s=yield xr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield _t.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield xr.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&&aa(n)==="String"&&n.startsWith("z")}};Ub.methodName="key";var xr=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:Yt.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:Fa}[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?Yt.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 qC))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 zw({keyBytes:i,multicodecName:o})})}};xr.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"};xr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};xr.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 FC=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())})},Ob=class t extends fn{static resolve(e,r){return FC(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"}})}})}};Ob.methodName="web";l();var JC=Pn(cB(),1),ZC=Pn(sm(),1);l();l();var Er=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 qe("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Pi).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 aB(t,e,r){return t&e^~t&r}function uB(t,e,r){return t&e^t&r^e&r}var Hp=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=Nl(this.buffer)}update(e){na(this),Se(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=Nl(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),Mv(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=Nl(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()}},co=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var XC=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]),ss=new Uint32Array(64),Db=class extends Hp{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)ss[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ss[f-15],p=ss[f-2],g=xn(h,7)^xn(h,18)^h>>>3,y=xn(p,17)^xn(p,19)^p>>>10;ss[f]=y+ss[f-7]+g+ss[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+aB(c,a,u)+XC[f]+ss[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+uB(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(ss)}destroy(){this.set(0,0,0,0,0,0,0,0),Os(this.buffer)}},kb=class extends Db{A=co[0]|0;B=co[1]|0;C=co[2]|0;D=co[3]|0;E=co[4]|0;F=co[5]|0;G=co[6]|0;H=co[7]|0;constructor(){super(32)}};var Vp=$v(()=>new kb,Hv(1));l();l();var ar=BigInt(0),er=BigInt(1),wc=BigInt(2),lB=BigInt(3),hB=BigInt(4),pB=BigInt(5),QC=BigInt(7),yB=BigInt(8),eL=BigInt(9),gB=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 dB(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=er,s=er,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!==er)throw new Error("invert: does not exist");return Nn(i,e)}function Cb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function mB(t,e){let r=(t.ORDER+er)/hB,n=t.pow(e,r);return Cb(t,n,e),n}function tL(t,e){let r=(t.ORDER-pB)/yB,n=t.mul(e,wc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,wc),i),c=t.mul(o,t.sub(s,t.ONE));return Cb(t,c,e),c}function rL(t){let e=iu(t),r=wB(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+QC)/gB;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 Cb(c,E,a),E}}function wB(t){if(t<lB)throw new Error("sqrt is not defined for small field");let e=t-er,r=0;for(;e%wc===ar;)e/=wc,r++;let n=wc,i=iu(t);for(;fB(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return mB;let o=i.pow(n,e),s=(e+er)/wc;return function(a,u){if(a.is0(u))return u;if(fB(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=er<<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 nL(t){return t%hB===lB?mB:t%yB===pB?tL:t%gB===eL?rL(t):wB(t)}var iL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lb(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=iL.reduce((n,i)=>(n[i]="function",n),e);return ed(t,r),t}function oL(t,e,r){if(r<ar)throw new Error("invalid exponent, negatives unsupported");if(r===ar)return t.ONE;if(r===er)return e;let n=t.ONE,i=e;for(;r>ar;)r&er&&(n=t.mul(n,i)),i=t.sqr(i),r>>=er;return n}function qp(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 fB(t,e){let r=(t.ORDER-er)/wc,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 sL(t,e){e!==void 0&&zn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Nb=class{ORDER;BITS;BYTES;isLE;ZERO=ar;ONE=er;_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}=sL(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&er)===er}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 oL(this,e,r)}div(e,r){return Nn(e*dB(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 dB(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=nL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?W0(e,this.BYTES):Ll(e,this.BYTES)}fromBytes(e,r=!1){Se(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?j0(e):Oo(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 qp(this,e)}cmov(e,r,n){return n?r:e}};function iu(t,e={}){return new Nb(t,e)}function bB(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 Pb(t){let e=bB(t);return e+Math.ceil(e/2)}function Fp(t,e,r=!1){Se(t);let n=t.length,i=bB(e),o=Pb(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?j0(t):Oo(t),c=Nn(s,e-er)+er;return r?W0(c,i):Ll(c,i)}var ou=BigInt(0),bc=BigInt(1);function yf(t,e){let r=e.negate();return t?r:e}function Hb(t,e){let r=qp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function SB(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Mb(t,e){SB(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Qu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function xB(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+=bc);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 Kb=new WeakMap,AB=new WeakMap;function $b(t){return AB.get(t)||1}function EB(t){if(t!==ou)throw new Error("invalid wNAF")}var jp=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>ou;)r&bc&&(n=n.add(i)),i=i.double(),r>>=bc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Mb(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=Mb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=xB(n,c,s);n=a,d?o=o.add(yf(h,r[p])):i=i.add(yf(f,r[u]))}return EB(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Mb(e,this.bits);for(let s=0;s<o.windows&&n!==ou;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=xB(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return EB(n),i}getPrecomputes(e,r,n){let i=Kb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Kb.set(r,i))),i}cached(e,r,n){let i=$b(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=$b(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){SB(r,this.bits),AB.set(e,r),Kb.delete(e)}hasCache(e){return $b(e)!==1}};function TB(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>ou||n>ou;)r&bc&&(o=o.add(i)),n&bc&&(s=s.add(i)),i=i.double(),r>>=bc,n>>=bc;return{p1:o,p2:s}}function vB(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lb(e),e}else return iu(t,{isLE:r})}function _B(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>ou))throw new Error(`CURVE.${a} must be positive bigint`)}let i=vB(e.p,r.Fp,n),o=vB(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 Wp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Gp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(kl(e),Se(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 na(this),this.iHash.update(e),this}digestInto(e){na(this),Se(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()}},Vb=(t,e,r)=>new Gp(t,e).update(r).digest();Vb.create=(t,e)=>new Gp(t,e);var BB=(t,e)=>(t+(t>=0?e:-e)/IB)/e;function cL(t,e,r){let[[n,i],[o,s]]=e,c=BB(s*t,r),a=BB(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<ao,h=d<ao;f&&(u=-u),h&&(d=-d);let p=Qu(Math.ceil(G0(r)/2))+su;if(u<ao||u>=p||d<ao||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Fb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function qb(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Zu(r.lowS,"lowS"),Zu(r.prehash,"prehash"),r.format!==void 0&&Fb(r.format),r}var jb=class extends Error{constructor(e=""){super(e)}},cs={Err:jb,_tlv:{encode:(t,e)=>{let{Err:r}=cs;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=Xu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Xu(i.length/2|128):"";return Xu(t)+o+i+e},decode(t,e){let{Err:r}=cs,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}=cs;if(t<ao)throw new e("integer: negative integers are not allowed");let r=Xu(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}=cs;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 Oo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=cs,i=Se(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}=cs,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},ao=BigInt(0),su=BigInt(1),IB=BigInt(2),zp=BigInt(3),aL=BigInt(4);function RB(t,e={}){let r=_B("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;ed(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=OB(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(Zu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return lr(UB(N),L)}else return lr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){Se(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,zp),aL),B=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,B)))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 cL(G,a.basises,i.ORDER)}let M=z0((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=z0(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),_=yf(x,_),D=yf(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(Se(_,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(zp),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,zp),{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,zp),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=>Hb($,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 Hb($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===ao||x.is0())return $.ZERO;if(_===su)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}=TB($,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===su?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===su?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Zu(_,"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 jp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function UB(t){return Uint8Array.of(t?2:3)}function OB(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function uL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(OB(t.Fp,r),{seed:Pb(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 Fp(Se(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(!Ju(p)||"_lengths"in r&&r._lengths||g===y)return;let S=Se(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=Wp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function DB(t,e,r={}){kl(e),ed(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)=>Vb(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=uL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*IB<o.ORDER;function E(D){let x=c>>su;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 B(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,x){Fb(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return Se(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(B(),![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}=cs.toSig(Se(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(lr(UB((N&1)===0),C)),V=s.inv(R),J=M(Se(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(Fb(x),x==="der")return ks(cs.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return x==="recovered"?(B(),lr(Uint8Array.of(this.assertRecovery()),N,R)):lr(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=Oo(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=Qu(a);function j(D){return jv("num < 2^"+a,D,ao,q),s.toBytes(D)}function $(D,x){return Se(D,void 0,"message"),x?Se(e(D),void 0,"prehashed message"):D}function X(D,x,U){let{lowS:L,prehash:N,extraEntropy:R}=qb(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(Se(Y,void 0,"extraEntropy"))}let J=lr(...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===ao)return;let Re=s.create(ue*s.create(z+ce*P));if(Re===ao)return;let Me=(ee.x===ce?0:2)|Number(ee.y&su),Je=Re;return L&&E(Re)&&(Je=s.neg(Re),Me^=1),new O(ce,Je,y?void 0:Me)}return{seed:J,k2sig:W}}function Q(D,x,U={}){let{seed:L,k2sig:N}=X(D,x,U);return Wv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=qb(L,g);if(U=Se(U,void 0,"publicKey"),x=$(x,R),!Ju(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}=qb(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 Zp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},dL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},fL=BigInt(0),Wb=BigInt(2);function lL(t){let e=Zp.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,Wb,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,B=$r(S,c,e)*y%e,A=$r(B,r,e)*d%e,O=$r(A,s,e)*g%e,T=$r(O,n,e)*u%e,M=$r(T,Wb,e);if(!Yp.eql(Yp.sqr(M),t))throw new Error("Cannot find square root");return M}var Yp=iu(Zp.p,{sqrt:lL}),xc=RB(Zp,{Fp:Yp,endo:dL}),ln=DB(xc,Vp),kB={};function Jp(t,...e){let r=kB[t];if(r===void 0){let n=Vp(Fv(t));r=lr(n,n),kB[t]=r}return Vp(lr(r,...e))}var zb=t=>t.toBytes(!0).slice(1),Yb=t=>t%Wb===fL;function Gb(t){let{Fn:e,BASE:r}=xc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Yb(i.y)?n:e.neg(n),bytes:zb(i)}}function CB(t){let e=Yp;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);Yb(i)||(i=e.neg(i));let o=xc.fromAffine({x:t,y:i});return o.assertValidity(),o}var gf=Oo;function LB(...t){return xc.Fn.create(gf(Jp("BIP0340/challenge",...t)))}function NB(t){return Gb(t).bytes}function hL(t,e,r=Ns(32)){let{Fn:n}=xc,i=Se(t,void 0,"message"),{bytes:o,scalar:s}=Gb(e),c=Se(r,32,"auxRand"),a=n.toBytes(s^gf(Jp("BIP0340/aux",c))),u=Jp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Gb(u),h=LB(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!PB(p,i,o))throw new Error("sign: Invalid signature produced");return p}function PB(t,e,r){let{Fp:n,Fn:i,BASE:o}=xc,s=Se(t,64,"signature"),c=Se(e,void 0,"message"),a=Se(r,32,"publicKey");try{let u=CB(gf(a)),d=gf(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=gf(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=LB(i.toBytes(d),zb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Yb(y)||g!==d)}catch{return!1}}var Xp=(()=>{let r=(n=Ns(48))=>Fp(n,Zp.n);return{keygen:Wp(r,NB),getPublicKey:NB,sign:hL,verify:PB,Point:xc,utils:{randomSecretKey:r,taggedHash:Jp,lift_x:CB,pointToBytes:zb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function pL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function KB(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 Jb(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function $B(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Zb(t){if(!Array.isArray(t))throw new Error("array expected")}function HB(t,e){if(!KB(!0,e))throw new Error(`${t}: array of strings expected`)}function yL(t,e){if(!KB(!1,e))throw new Error(`${t}: array of numbers expected`)}function gL(...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 mL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;HB("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Zb(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=>(Zb(i),i.map(o=>{Jb("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function wL(t=""){return Jb("join",t),{encode:e=>(HB("join.decode",e),e.join(t)),decode:e=>(Jb("join.decode",e),e.split(t))}}function MB(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(Zb(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if($B(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 bL(t){$B(t);let e=2**8;return{encode:r=>{if(!pL(r))throw new Error("radix.encode input should be Uint8Array");return MB(Array.from(r),e,t)},decode:r=>(yL("radix.decode",r),Uint8Array.from(MB(r,t,e)))}}var xL=t=>gL(bL(58),mL(t),wL("")),cu=xL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var VB=new Uint8Array([231,1]),ht=class t{#e;#t={prefix:VB,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Tr(e);if(!r||r.length!==33)throw new Bs("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!ln.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 ln.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 cu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(VB);return r.push(...e),"z"+cu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return ln.verify(e,r,this.compressed);if(n.scheme==="schnorr")return Xp.verify(e,r,this.x);throw new Bs(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return ia(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 qB=new Uint8Array([129,38]),EL=Ct(ke(qB)),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<ln.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>=ln.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(qB);return r.push(...e),"z"+cu.encode(Uint8Array.from(r))}equals(e){return ia(this.bytes,e.bytes)}computePublicKey(){return new ht(ln.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 ln.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return ln.sign(e,this.bytes);if(r.scheme==="schnorr")return Xp.sign(e,this.bytes);throw new jn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=cu.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(ke(n))!==EL)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(!ln.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=_r(32);while(!ln.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var uo=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"?Tr(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 ur=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in Io))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=Gu[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:${Fc.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}`,xl,{identifier:e});if(!o)throw new mt(`Invalid method-specific id: ${e}`,Lt,{identifier:e});let{prefix:s,bytes:c}=Fc.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=Gu[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=uo.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 Vr=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new we("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!Er.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 zt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=ur.decode(e),o=Uo(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:Di(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new zt("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=Di(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 zt("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 getBeaconServiceIds(e){return this.getBeaconServices(e).map(r=>r.id)}};var vL=/^6a20([0-9a-f]{64})$/i;function Xb(t){if(!t)return null;let e=vL.exec(t.trim());return e?e[1].toLowerCase():null}var Qb=class t{static async spendsFromAddress(e,r,n){for(let i of e.vin??[]){if(i.is_coinbase)continue;let o=i.prevout;if(!o&&i.txid&&(o=(await n.rest.transaction.get(i.txid))?.vout?.[i.vout]),o?.scriptpubkey_address===r)return!0}return!1}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=Vr.parseBitcoinAddress(o.serviceEndpoint),c=await r.rest.address.getTxs(s);if(!(!c||!c.length))for(let a of c){let u=a.vout.slice(-1)[0];if(!u)continue;let d=Xb(u.scriptpubkey);if(!d||!await t.spendsFromAddress(a,s,r))continue;let f=i-a.status.block_height+1;n.get(o)?.push({tx:a,signalBytes:d,blockMetadata:{confirmations:f,height:a.status.block_height,time:a.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 Ve("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=new Map(e.map(u=>[Vr.parseBitcoinAddress(u.serviceEndpoint),u])),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===N0)continue;let d=u.vout.slice(-1)[0];if(!d)continue;let f=Xb(d.scriptPubKey?.hex);if(!f)continue;let h=new Set;for(let p of u.vin){if(p.coinbase||p.txinwitness&&p.txinwitness.length===1&&p.txinwitness[0]===k0||!p.txid||p.vout===void 0)continue;let g=await i.getRawTransaction(p.txid,2);if(!g.vout[p.vout])continue;let y=g.vout[p.vout].scriptPubKey;if(!y.address)continue;let E=s.get(y.address);!E||h.has(E)||(h.add(E),console.info(`Tx ${u.txid} contains beacon address ${y.address}`),n.get(E)?.push({tx:u,signalBytes:f,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 tre=new Uint8Array(0);function FB(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 SL(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,B=g.length;S!==B&&g[S]===0;)S++,y++;for(var A=(B-S)*d+1>>>0,O=new Uint8Array(A);S!==B;){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 B=(g.length-y)*u+1>>>0,A=new Uint8Array(B);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=B-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=B-S;q!==B&&A[q]===0;)q++;for(var j=new Uint8Array(E+(B-q)),$=E;q!==B;)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 AL=SL,TL=AL,jB=TL;var ex=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")}},tx=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 WB(this,e)}},rx=class{decoders;constructor(e){this.decoders=e}or(e){return WB(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 WB(t,e){return new rx({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var nx=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 ex(e,r,n),this.decoder=new tx(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function _L({name:t,prefix:e,encode:r,decode:n}){return new nx(t,e,r,n)}function ix({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=jB(r,t);return _L({prefix:e,name:t,encode:n,decode:o=>FB(i(o))})}var mf=ix({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),fre=ix({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function GB(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var au=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 mn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",_o,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new mn("Domain mismatch: proof.domain !== config.domain",_o,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new mn("Challenge mismatch options and challenge passed",_o,{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 mn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",ki,s);if(r&&r!==c.proofPurpose)throw new mn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",ki,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new mn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=GB(i),d=GB(c.domain);if(u.length!==d.length)throw new mn("Domain mismatch: expectedDomain length does not match proof.domain length",ki,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new mn("Domain mismatch: expectedDomain and proof.domain do not match",ki,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var uu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new au(this)}#e(){return{type:this.type,cryptosuite:this.cryptosuite,verificationMethod:this.multikey.fullId()}}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=mf.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=mf.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 we("Type mismatch: config.type !== this.type",ki,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new we("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",ki,{config:r,suite:this.#e()});return rr(e)}generateHash(e,r){let n=ke(ws(e)),i=ke(ws(r)),o=ut(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new To("Type mismatch: config.type !== this.type",_o,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new To("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",_o,{config:e,suite:this.#e()});if(e.created&&!Ro.isValidXsdDateTime(e.created))throw new To('Invalid config: "created" must be a valid XMLSchema DateTime string',_o,e);return rr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",vv,{config:r,suite:this.#e()});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",ki,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var as=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 uu(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 Rr.sign(e,this.secretKey.bytes,_r(32))}verify(e,r){return Rr.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(){let e;try{e=this.signer}catch{e=!1}return{id:this.id,controller:this.controller,fullId:this.fullId(),signer:e,keyPair:this.keyPair.toJSON(),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 uo({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 uo({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 uo({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",El,{publicKeyMultibase:n});let i=mf.decode(n);if(i.length!==35)throw new bn(`Invalid publicKeyMultibase length: ${i.length}`,El,{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)??"??"}]`,El,{publicKeyMultibase:n});let o=i.slice(2),s=new uo({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();l();var zB=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Ec="Multikey",vc="zQ3s",qr="did:btcr2:_",BL="",YB=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function JB(t){if(!Er.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===Ec&&typeof r=="string"&&r.startsWith(vc)}var Qp=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==Ec)throw new qe(`Invalid verification method: type must be "${Ec}"`,Oe,{id:e,type:r});if(typeof i!="string"||!i.startsWith(vc))throw new qe(`Invalid verification method: publicKeyMultibase must start with "${vc}"`,Oe,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},Fr=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 qe("DID Document must have an id",Oe,e);let r=e.id.includes("k1")?Io.KEY:Io.EXTERNAL,n=e.id===qr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new qe(`Invalid id: ${i}`,Oe,e);if(!t.isValidVerificationMethods(o))throw new qe("Invalid verificationMethod: "+o,Oe,e);if(!t.isValidServices(s))throw new qe("Invalid service: "+s,Oe,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===Io.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 Qp({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 qe('Invalid "@context"',Oe,e);if(!this.isValidId(e?.id))throw new qe('Invalid "id"',Oe,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new qe('Invalid "verificationMethod"',Oe,e);if(!this.isValidServices(e?.service))throw new qe('Invalid "service"',Oe,e);if(!this.isValidVerificationRelationships(e))throw new qe("Invalid verification relationships",Oe,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:zB.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return ur.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(JB)}static isValidServices(e){return Array.isArray(e)&&e.every(d_)}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"||Er.isDidVerificationMethod(c))})}static validate(e){return e.id===qr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==qr)throw new qe("Invalid GenesisDocument ID",Oe,this);if(!this.verificationMethod.every(e=>e.id.includes(qr)&&e.controller===qr))throw new qe("Invalid GenesisDocument verificationMethod",Oe,this);if(!this.service.every(e=>e.id.includes(qr)))throw new qe("Invalid GenesisDocument service",Oe,this);if(!t.isValidVerificationRelationships(this))throw new qe("Invalid GenesisDocument assertionMethod",Oe,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new qe("Cannot convert a key identifier to an intermediate document",Oe,this);return new ey(this)}},ey=class t extends Fr{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(qr,e),n=JSON.parse(r);return new Fr(n)}static fromDidDocument(e){let r=Us.cloneReplace(e,YB,qr);return new t(r)}static create(e,r,n){return new t({id:qr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ht(e),i=qr,o=Di(n.compressed,Uo(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 Bo(rr(e))}};var wf=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:Wn(e)},o=ea.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}").`,De,{sourceId:e.id,targetId:o.id});try{Fr.isValid(o)}catch(s){throw new vt("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),De,o)}return i.targetHash=Wn(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}".`,De,{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}".`,De,{verificationMethodId:n.id});let c=n.id.slice(s),a=as.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.`,De,{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,o){return Cs.establish(e).broadcastSignal(r,n,i,o)}#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.`,De,{phase:this.#e.phase});if(!r)throw new vt("NeedSigningKey requires a Signer.",De);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.`,De,{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)}.`,De,{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.`,De,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var bf=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new we("idType is required for creating a did:btcr2 identifier",Oe,r);return ur.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=ur.decode(e),i=fo.sidecarData(r.sidecar),o=n.hrp===Ul.k?fo.deterministic(n):null;return new fo(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",Oe,e);let s=this.getSigningMethod(e,i);if(!s)throw new vt("Invalid verificationMethod: not found in source document",Oe,{sourceDocument:e,verificationMethodId:i});if(s.type!==Ec)throw new vt(`Invalid verificationMethod: verificationMethod.type must be "${Ec}"`,Oe,s);if(!s.publicKeyMultibase?.startsWith(vc))throw new vt(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${vc}"`,Oe,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",De,{sourceDocument:e,beaconId:o});return new wf({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 we(`Method not supported: ${n.method}`,xl,{identifier:e.id});let i=e.verificationMethod?.find(o=>Er.extractDidFragment(o.id)===(Er.extractDidFragment(r)??Er.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 du(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function IL(t){return du(t)&&Object.values(t).every(e=>typeof e=="string")}function RL(t){return du(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&du(t.proof):!1}function UL(t){return du(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}function ZB(t,e){let r=du(e)?e.id:e;if(!(typeof r!="string"||r.length===0))return r.startsWith("#")?`${t}${r}`:r}var fo=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=ur.encode(r,e),{multibase:i}=new ht(r),o=Vr.generateBeaconServices({id:n,publicKey:r,network:Uo(e.network),beaconType:"SingletonBeacon"});return new Fr({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Xc(r);if(!_u(e.genesisBytes,n))throw new Ve("Initial document mismatch: genesisBytes !== genesisDocumentHash",Oe,{genesisBytes:Qr(e.genesisBytes,"hex"),genesisDocumentHash:Qr(n,"hex")});let i=ur.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(qr,i));return new Fr(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Wn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Wn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(Qr(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=Xc(u.didDocument),p=Ro.blocktimeToTimestamp(f.time);if(u.metadata.updated=Ro.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(n&&p>Ro.dateStringToTimestamp(n))return u;if(d.targetVersionId===s+1){let y=Is(d.sourceHash,"base64urlnopad");if(!_u(y,h))throw new Ve("Hash mismatch: update.sourceHash !== currentDocumentHash",De,{sourceHash:d.sourceHash,currentDocumentHash:Qr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let E=Us.deleteKeys(d,["proof"]);c.push(Xc(E))}else throw new Ve("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",vl,{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){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new Ve("Invalid duplicate: targetVersionId must be an integer >= 2",De,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=Xc(i),s=r[e.targetVersionId-2];if(s===void 0)throw new Ve("Invalid duplicate: no applied update in history for targetVersionId",vl,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!_u(s,o))throw new Ve("Invalid duplicate: unsigned update hash does not match historical hash",vl,{unsignedUpdateHash:Qr(o,"hex"),historicalHash:Qr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new Ve("No root capability found in update",De,r);let i=Er.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(A=>A===e.id))throw new Ve("Invalid root capability",De,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new Ve("No verificationMethod found in update",De,r);let a=ZB(e.id,c);if(!(a!==void 0&&e.capabilityInvocation?.some(A=>ZB(e.id,A)===a)))throw new Ve("Invalid update: verificationMethod is not authorized for capabilityInvocation",De,{verificationMethodId:c,capabilityInvocation:e.capabilityInvocation});let d=bf.getSigningMethod(e,c),f=as.fromVerificationMethod(d),h=new uu(f),p=rr(r),y=new au(h).verifyProof(p,"capabilityInvocation");if(!y.verified)throw new Ve("Invalid update: proof not verified",De,y);let E=ea.apply(e,r.patch);Fr.validate(E);let S=Xc(E),B=Is(r.targetHash);if(!_u(B,S))throw new Ve("Invalid update: update.targetHash !== currentDocumentHash",De,{updateTargetHash:B,currentDocumentHash:S});return E}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:Qr(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=Vr.getBeaconServices(this.#i).filter(n=>{let i=Vr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=Vr.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=Cs.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=[],Vr.getBeaconServices(this.#i).some(n=>{let i=Vr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new Ve(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,Ev,{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(!du(r))throw new Ve("Provided data for NeedGenesisDocument must be a document object.",De,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new Ve("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",De,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!IL(r))throw new Ve("Provided data for NeedCASAnnouncement is not a CAS announcement.",De,{kind:e.kind});let n=Wn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new Ve(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,De,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!RL(r))throw new Ve("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",De,{kind:e.kind});let n=Wn(r,{encoding:"hex"});if(n!==e.updateHash)throw new Ve(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,De,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!UL(r))throw new Ve("Provided data for NeedSMTProof is not an SMT proof.",De,{kind:e.kind});let n=Qr(Is(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new Ve(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,De,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function XB(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new qe("Cannot derive aggregation communication key: capabilityInvocation is absent",Oe,{id:t.id});let r=typeof e=="string"?t.verificationMethod?.find(n=>n.id===e):e;if(!r)throw new qe(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,Oe,{id:t.id,invocation:e});return as.fromVerificationMethod(r).publicKey}function OL(t,e){try{let r=ur.decode(t);if(r.idType==="KEY")return new ht(r.genesisBytes);if(e?.genesisDocument){let n=fo.external(r,e.genesisDocument);return XB(n)}}catch{}}l();l();l();var ox=class{document={};constructor(e){if(!e.id)throw new qe('Missing required "id" property',Oe,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 Fr(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};return SI(DL);})();
4
4
  /*! Bundled license information:
5
5
 
6
6
  ieee754/index.js: