@did-btcr2/method 0.58.0 → 0.60.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/README.md +2 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/browser.js +3 -3
- package/dist/browser.mjs +3 -3
- package/dist/cjs/index.js +985 -753
- package/dist/esm/core/beacon/beacon.js +8 -1
- package/dist/esm/core/beacon/beacon.js.map +1 -1
- package/dist/esm/core/beacon/signal-discovery.js +24 -3
- package/dist/esm/core/beacon/signal-discovery.js.map +1 -1
- package/dist/esm/core/identifier.js +175 -23
- package/dist/esm/core/identifier.js.map +1 -1
- package/dist/esm/core/resolver.js +77 -3
- package/dist/esm/core/resolver.js.map +1 -1
- package/dist/esm/did-btcr2.js +2 -1
- package/dist/esm/did-btcr2.js.map +1 -1
- package/dist/types/core/beacon/beacon.d.ts.map +1 -1
- package/dist/types/core/beacon/signal-discovery.d.ts +14 -0
- package/dist/types/core/beacon/signal-discovery.d.ts.map +1 -1
- package/dist/types/core/identifier.d.ts +67 -0
- package/dist/types/core/identifier.d.ts.map +1 -1
- package/dist/types/core/interfaces.d.ts +13 -0
- package/dist/types/core/interfaces.d.ts.map +1 -1
- package/dist/types/core/resolver.d.ts +13 -0
- package/dist/types/core/resolver.d.ts.map +1 -1
- package/dist/types/did-btcr2.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/core/beacon/beacon.ts +14 -3
- package/src/core/beacon/signal-discovery.ts +25 -3
- package/src/core/identifier.ts +267 -22
- package/src/core/interfaces.ts +13 -0
- package/src/core/resolver.ts +87 -3
- package/src/did-btcr2.ts +2 -1
package/dist/browser.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var BTCR2=(()=>{var gB=Object.create;var Rf=Object.defineProperty;var mB=Object.getOwnPropertyDescriptor;var wB=Object.getOwnPropertyNames;var bB=Object.getPrototypeOf,xB=Object.prototype.hasOwnProperty;var EB=(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})},yx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wB(e))!xB.call(t,i)&&i!==r&&Rf(t,i,{get:()=>e[i],enumerable:!(n=mB(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?gB(bB(t)):{},yx(e||!t||!t.__esModule?Rf(r,"default",{value:t,enumerable:!0}):r,t)),vB=t=>yx(Rf({},"__esModule",{value:!0}),t);var wx=oe(Uf=>{"use strict";l();Uf.byteLength=AB;Uf.toByteArray=_B;Uf.fromByteArray=RB;var Mn=[],Yr=[],SB=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 AB(t){var e=mx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function TB(t,e,r){return(e+r)*3/4-r}function _B(t){var e,r=mx(t),n=r[0],i=r[1],o=new SB(TB(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 IB(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function BB(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(IB(n));return i.join("")}function RB(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(BB(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=CB;Oc.INSPECT_MAX_BYTES=50;var Of=2147483647;Oc.kMaxLength=Of;F.TYPED_ARRAY_SUPPORT=UB();!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 UB(){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 DB(t,e);if(ArrayBuffer.isView(t))return kB(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=NB(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 OB(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 OB(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 DB(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 kB(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 NB(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 CB(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 LB(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 WB(this,e,r);case"utf8":case"utf-8":return Ix(this,e,r);case"ascii":return FB(this,e,r);case"latin1":case"binary":return jB(this,e,r);case"base64":return VB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return GB(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?Ix(this,0,e):LB.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 PB(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 MB(t,e,r,n){return Df(fy(e,t.length-r),t,r,n)}function KB(t,e,r,n){return Df(JB(e),t,r,n)}function $B(t,e,r,n){return Df(Ox(e),t,r,n)}function HB(t,e,r,n){return Df(ZB(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 PB(this,e,r,n);case"utf8":case"utf-8":return MB(this,e,r,n);case"ascii":case"latin1":case"binary":return KB(this,e,r,n);case"base64":return $B(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return HB(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 VB(t,e,r){return e===0&&r===t.length?ay.fromByteArray(t):ay.fromByteArray(t.slice(e,r))}function Ix(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 qB(n)}var vx=4096;function qB(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 FB(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 jB(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 WB(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+=XB[t[o]];return i}function GB(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 Ut(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||Ut(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||Ut(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||Ut(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(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||Ut(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||Ut(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||Ut(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||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(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||Ut(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||Ut(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||Ut(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||Ut(e,4,this.length),Uc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Uc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Uc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Uc.read(this,e,!1,52,8)};function fr(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;fr(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;fr(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||fr(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||fr(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||fr(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||fr(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||fr(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);fr(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);fr(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||fr(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||fr(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||fr(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||fr(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||fr(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 Rx(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 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||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 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 zB=/[^+/0-9A-Za-z-_]/g;function YB(t){if(t=t.split("=")[0],t=t.trim().replace(zB,""),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 JB(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function ZB(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(YB(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 XB=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((GL,Cx)=>{l();var ut=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 QB(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 e8(){!Dc||!ys||(Dc=!1,ys.length?wi=ys.concat(wi):kf=-1,wi.length&&kx())}function kx(){if(!Dc){var t=Dx(e8);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,QB(t)}}ut.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)};ut.title="browser";ut.browser=!0;ut.env={};ut.argv=[];ut.version="";ut.versions={};function bi(){}ut.on=bi;ut.addListener=bi;ut.once=bi;ut.off=bi;ut.removeListener=bi;ut.removeAllListeners=bi;ut.emit=bi;ut.prependListener=bi;ut.prependOnceListener=bi;ut.listeners=function(t){return[]};ut.binding=function(t){throw new Error("process.binding is not supported")};ut.cwd=function(){return"/"};ut.chdir=function(t){throw new Error("process.chdir is not supported")};ut.umask=function(){return 0}});var b,w,YL,l=EB(()=>{b=Pn(Ar()),w=Pn(xi()),YL=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((BH,r1)=>{l();var a6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Hl=()=>a6.now(),u6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),eg=t=>t===1/0||u6(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((XV,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((eq,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(),V6=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"||!V6.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(),q6=gg(),cd=class extends vg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new ad({encode:this.encode,decode:e=>this.decode(Eg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},ad=class extends vg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new cd({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 cd({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}=q6();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=xg});var I1=oe(Ks=>{"use strict";l();var{Buffer:Zt}=Ar()||{Buffer:{isBuffer:()=>!1}},{textEncoder:T1,textDecoder:A1}=gg()(),{BufferFormat:ud,ViewFormat:Ag,UTF8Format:_1}=Sg(),Fl=t=>t;Ks.utf8=new _1({encode:function(t){return Zt.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 ud({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.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 ud({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:Fl,name:"buffer",createViewTranscoder(){return new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:Zt.from(String(t),"utf8")},decode:function(t){return Zt.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 ud({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:Fl,name:`${this.name}+buffer`})}});Ks.hex=new ud({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ks.base64=new ud({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var U1=oe(R1=>{"use strict";l();var B1=En(),Wl=I1(),{Encoding:F6}=bg(),{BufferFormat:j6,ViewFormat:W6,UTF8Format:G6}=Sg(),dd=Symbol("formats"),jl=Symbol("encodings"),z6=new Set(["buffer","view","utf8"]),Tg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>z6.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=X6[e],!r)throw new B1(`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=Y6(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 B1(`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 Y6(t){if(t instanceof F6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${Q6++}`;switch(J6(t)){case"view":return new W6({...t,name:r});case"utf8":return new G6({...t,name:r});case"buffer":return new j6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function J6(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 Z6={binary:Wl.buffer,"utf-8":Wl.utf8},X6={...Wl,...Z6},Q6=0});var la=oe((dq,_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 eU(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=iU;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,eU(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 tU(){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=tU.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():rU(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?nU(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 rU(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function nU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function iU(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"&&oU(t,i,{once:!0})})}function oU(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((lq,H1)=>{l();H1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var fd=oe(Ig=>{"use strict";l();var q1=V1();Ig.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};Ig.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(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:Rg}=fd(),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"),ld=Symbol("handleClose"),Jl=Symbol("closed"),hd=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({}),sU=()=>{},j1=!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[Zn]=!1,this[ko]=!1,this[Og]=!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[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?sU:(this[Zn]=!1,this[ha]=null,this[ko]&&this._close(this[ld]),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[hd].push(e):(this[ko]=!0,this[hd].push(e),this[Zn]?this[Dg]&&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[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 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[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 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[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:cU,AbstractValueIterator:aU}=Mo(),qs=Symbol("iterator"),yd=Symbol("callback"),ya=Symbol("handleOne"),Fs=Symbol("handleMany"),gd=class extends cU{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 aU{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)}}Pg.DefaultKeyIterator=gd;Pg.DefaultValueIterator=eh});var G1=oe(sh=>{"use strict";l();var{AbstractIterator:uU,AbstractKeyIterator:dU,AbstractValueIterator:fU}=Mo(),Mg=En(),yr=Symbol("nut"),ih=Symbol("undefer"),oh=Symbol("factory"),th=class extends uU{constructor(e,r){super(e,r),this[yr]=null,this[oh]=()=>e.iterator(r),this.db.defer(()=>this[ih]())}},rh=class extends dU{constructor(e,r){super(e,r),this[yr]=null,this[oh]=()=>e.keys(r),this.db.defer(()=>this[ih]())}},nh=class extends fU{constructor(e,r){super(e,r),this[yr]=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[yr]=this[oh]())},t.prototype._next=function(e){this[yr]!==null?this[yr].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[yr]!==null?this[yr].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[yr]!==null?this[yr].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[yr]!==null?this[yr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[yr]!==null?this[yr].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}=fd(),ch=En(),{getCallback:lU,getOptions:hU}=Yl(),ah=Symbol("promise"),tn=Symbol("status"),ga=Symbol("operations"),md=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[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[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=lU(e,r),r=z1(r,ah),e=hU(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[md])})),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[md]))),e[ah]}_close(e){this.nextTick(e)}[md](){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:pU}=$g(),yU=En(),wa=Symbol("encoded"),Hg=class extends pU{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 yU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};J1.DefaultChainedBatch=Hg});var e2=oe((Bq,Q1)=>{"use strict";l();var X1=En(),gU=Object.prototype.hasOwnProperty,mU=new Set(["lt","lte","gt","gte"]);Q1.exports=function(t,e){let r={};for(let n in t)if(gU.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"});mU.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((Uq,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((Dq,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:wU,AbstractKeyIterator:bU,AbstractValueIterator:xU}=Mo(),ba=Symbol("unfix"),vn=Symbol("iterator"),js=Symbol("handleOne"),Ko=Symbol("handleMany"),$i=Symbol("callback"),wd=class extends wU{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 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){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 xU{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 d2=oe((Lq,u2)=>{"use strict";l();var qg=En(),{Buffer:Wg}=Ar()||{},{AbstractSublevelIterator:EU,AbstractSublevelKeyIterator:vU,AbstractSublevelValueIterator:SU}=s2(),Hi=Symbol("prefix"),c2=Symbol("upperBound"),Ed=Symbol("prefixRange"),kr=Symbol("parent"),Fg=Symbol("unfix"),a2=new TextEncoder,AU={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?AU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=_U(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(TU(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)}}[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[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[Ed](n,n.keyEncoding),this[kr].clear(n,i)}_iterator(n){this[Ed](n,n.keyEncoding);let i=this[kr].iterator(n),o=this[Fg].get(this[Hi].utf8.length,n.keyEncoding);return new EU(this,n,i,o)}_keys(n){this[Ed](n,n.keyEncoding);let i=this[kr].keys(n),o=this[Fg].get(this[Hi].utf8.length,n.keyEncoding);return new vU(this,n,i,o)}_values(n){this[Ed](n,n.keyEncoding);let i=this[kr].values(n);return new SU(this,n,i)}}return{AbstractSublevel:e}};var TU=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}},_U=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:BU}=U1(),{EventEmitter:RU}=la(),{fromCallback:$o}=fd(),Sn=En(),{AbstractIterator:Ws}=Mo(),{DefaultKeyIterator:UU,DefaultValueIterator:OU}=W1(),{DeferredIterator:DU,DeferredKeyIterator:kU,DeferredValueIterator:NU}=G1(),{DefaultChainedBatch:f2}=Z1(),{getCallback:Gs,getOptions:Ho}=Yl(),fh=e2(),pe=Symbol("promise"),Vi=Symbol("landed"),zs=Symbol("resources"),zg=Symbol("closeResources"),vd=Symbol("operations"),Sd=Symbol("undefer"),lh=Symbol("deferOpen"),l2=Symbol("options"),be=Symbol("status"),Ys=Symbol("defaultOptions"),xa=Symbol("transcoder"),hh=Symbol("keyEncoding"),Yg=Symbol("valueEncoding"),CU=()=>{},Ad=class extends RU{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[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 BU(LU(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},CU)})}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[Sd]();return}this[be]="open",this[Sd](),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[Sd](),this.emit(Vi),r(i)};this[zg](()=>{this._close(i=>{if(i)return n(i);this[be]="closed",this[Sd](),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 DU(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 kU(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 UU(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 NU(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 OU(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 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"})}};Ad.prototype.nextTick=o2();var{AbstractSublevel:Jg}=d2()({AbstractLevel:Ad});Zg.AbstractLevel=Ad;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},LU=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((Vq,h2)=>{l();h2.exports=MU;var PU=Vg();function MU(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?PU(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((Fq,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((Wq,g2)=>{"use strict";l();var KU=new TextEncoder;g2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):KU.encode(t)}});var E2=oe(x2=>{"use strict";l();var{AbstractIterator:$U}=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 $U{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((Jq,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(B2=>{"use strict";l();var{AbstractLevel:HU}=Qg(),A2=En(),VU=p2(),{fromCallback:qU}=fd(),{Iterator:FU}=E2(),T2=tm(),jU=S2(),WU=em(),I2="level-js-",Td=Symbol("idb"),im=Symbol("namePrefix"),ji=Symbol("location"),om=Symbol("version"),Xs=Symbol("store"),_d=Symbol("onComplete"),_2=Symbol("promise"),yh=class extends HU{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??I2,this[om]=parseInt(o||1,10),this[Td]=null}get location(){return this[ji]}get namePrefix(){return this[im]}get version(){return this[om]}get db(){return this[Td]}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[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 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)}});VU(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 FU(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=WU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return jU(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=I2),r=qU(r,_2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[_2]};B2.BrowserLevel=yh});var sm=oe(U2=>{l();U2.Level=R2().BrowserLevel});var nt=oe((cF,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((uF,mh)=>{"use strict";l();var{AbortController:D2,AbortSignal:zU}=typeof self<"u"?self:typeof window<"u"?window:void 0;mh.exports=D2;mh.exports.AbortSignal=zU;mh.exports.default=D2});var Xt=oe((fF,am)=>{"use strict";l();var YU=Ar(),{kResistStopPropagation:JU,SymbolDispose:ZU}=nt(),XU=globalThis.AbortSignal||Sa().AbortSignal,QU=globalThis.AbortController||Sa().AbortController,e5=Object.getPrototypeOf(async function(){}).constructor,k2=globalThis.Blob||YU.Blob,t5=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)},r5=(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 e5},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:t5,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"),r5(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[JU]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[ZU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:XU.any||function(e){if(e.length===1)return e[0];let r=new QU,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 or=oe((hF,P2)=>{"use strict";l();var{format:n5,inspect:wh,AggregateError:i5}=Xt(),o5=globalThis.AggregateError||i5,s5=Symbol("kIsNodeError"),c5=["string","function","number","object","Function","Object","boolean","bigint","symbol"],a5=/^([A-Z][a-z0-9]*)+$/,u5="__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 d5(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:n5(e,...r)}function Kt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(d5(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[s5]=!0,bh[t]=n}function L2(t){let e=u5+t.name;return Object.defineProperty(t,"name",{value:e}),t}function f5(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new o5([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"}};Kt("ERR_ASSERTION","%s",Error);Kt("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"),c5.includes(a)?i.push(a.toLowerCase()):a5.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);Kt("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);Kt("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);Kt("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);Kt("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);Kt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Kt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Kt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Kt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Kt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Kt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Kt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Kt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Kt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Kt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Kt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);P2.exports={AbortError:um,aggregateTwoErrors:L2(f5),hideStackFrames:L2,codes:bh}});var Ta=oe((yF,G2)=>{"use strict";l();var{ArrayIsArray:fm,ArrayPrototypeIncludes:H2,ArrayPrototypeJoin:V2,ArrayPrototypeMap:l5,NumberIsInteger:lm,NumberIsNaN:h5,NumberMAX_SAFE_INTEGER:p5,NumberMIN_SAFE_INTEGER:y5,NumberParseInt:g5,ObjectPrototypeHasOwnProperty:m5,RegExpPrototypeExec:q2,String:w5,StringPrototypeToUpperCase:b5,StringPrototypeTrim:x5}=nt(),{hideStackFrames:rn,codes:{ERR_SOCKET_BAD_PORT:E5,ERR_INVALID_ARG_TYPE:Qt,ERR_INVALID_ARG_VALUE:Aa,ERR_OUT_OF_RANGE:tc,ERR_UNKNOWN_SIGNAL:M2}}=or(),{normalizeEncoding:v5}=Xt(),{isAsyncFunction:S5,isArrayBufferView:A5}=Xt().types,K2={};function T5(t){return t===(t|0)}function _5(t){return t===t>>>0}var I5=/^[0-7]+$/,B5="must be a 32-bit unsigned integer or an octal string";function R5(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(q2(I5,t)===null)throw new Aa(e,t,B5);t=g5(t,8)}return F2(t,e),t}var U5=rn((t,e,r=y5,n=p5)=>{if(typeof t!="number")throw new Qt(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)}),O5=rn((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Qt(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 Qt(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 Qt(e,"string",t)}function D5(t,e,r=void 0,n){if(typeof t!="number")throw new Qt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&h5(t))throw new tc(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var k5=rn((t,e,r)=>{if(!H2(r,t)){let i="must be one of: "+V2(l5(r,o=>typeof o=="string"?`'${o}'`:w5(o)),", ");throw new Aa(e,t,i)}});function j2(t,e){if(typeof t!="boolean")throw new Qt(e,"boolean",t)}function dm(t,e,r){return t==null||!m5(t,e)?r:t[e]}var N5=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 Qt(e,"Object",t)}),C5=rn((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Qt(e,"a dictionary",t)}),xh=rn((t,e,r=0)=>{if(!fm(t))throw new Qt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new Aa(e,t,n)}});function L5(t,e){xh(t,e);for(let r=0;r<t.length;r++)hm(t[r],`${e}[${r}]`)}function P5(t,e){xh(t,e);for(let r=0;r<t.length;r++)j2(t[r],`${e}[${r}]`)}function M5(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 Qt(i,"AbortSignal",n);W2(n,i)}}function K5(t,e="signal"){if(hm(t,e),K2[t]===void 0)throw K2[b5(t)]!==void 0?new M2(t+" (signals must use all capital letters)"):new M2(t)}var $5=rn((t,e="buffer")=>{if(!A5(t))throw new Qt(e,["Buffer","TypedArray","DataView"],t)});function H5(t,e){let r=v5(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Aa("encoding",e,`is invalid for data of length ${n}`)}function V5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&x5(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new E5(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 Qt(e,"AbortSignal",t)}),q5=rn((t,e)=>{if(typeof t!="function")throw new Qt(e,"Function",t)}),F5=rn((t,e)=>{if(typeof t!="function"||S5(t))throw new Qt(e,"Function",t)}),j5=rn((t,e)=>{if(t!==void 0)throw new Qt(e,"undefined",t)});function W5(t,e,r){if(!H2(r,t))throw new Qt(e,`('${V2(r,"|")}')`,t)}var G5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function $2(t,e){if(typeof t>"u"||!q2(G5,t))throw new Aa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function z5(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:T5,isUint32:_5,parseFileMode:R5,validateArray:xh,validateStringArray:L5,validateBooleanArray:P5,validateAbortSignalArray:M5,validateBoolean:j2,validateBuffer:$5,validateDictionary:C5,validateEncoding:H5,validateFunction:q5,validateInt32:O5,validateInteger:U5,validateNumber:D5,validateObject:N5,validateOneOf:k5,validatePlainFunction:F5,validatePort:V5,validateSignalName:K5,validateString:hm,validateUint32:F2,validateUndefined:j5,validateUnion:W5,validateAbortSignal:W2,validateLinkHeaderValue:z5}});var ti=oe((mF,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"),Y5=rc("nodejs.webstream.isClosedPromise"),J5=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 Z5(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 X5(t){return Q2(t)||eS(t)||tS(t)}function Q5(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 eO(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 tO(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 rO(t,e){return ei(t)?Sh(t)?!0:!(e?.readable!==!1&&iS(t)||e?.writable!==!1&&oS(t)):null}function nO(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 iO(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 oO(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 sO(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 cO(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 aO(t){var e;return!!(t&&((e=t[X2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function uO(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:aO,kIsDisturbed:X2,isErrored:uO,kIsErrored:Z2,isReadable:iS,kIsReadable:pm,kIsClosedPromise:Y5,kControllerErrorFunction:J5,kIsWritable:ym,isClosed:oO,isDuplexNodeStream:Z5,isFinished:rO,isIterable:Q5,isReadableNodeStream:Eh,isReadableStream:Q2,isReadableEnded:tO,isReadableFinished:nS,isReadableErrored:iO,isNodeStream:ei,isWebStream:X5,isWritable:oS,isWritableNodeStream:vh,isWritableStream:eS,isWritableEnded:rS,isWritableFinished:eO,isWritableErrored:nO,isServerRequest:sO,isServerResponse:cS,willEmitClose:cO,isTransformStream:tS}});var Wi=oe((bF,xm)=>{l();var Vo=xi(),{AbortError:mS,codes:dO}=or(),{ERR_INVALID_ARG_TYPE:fO,ERR_STREAM_PREMATURE_CLOSE:uS}=dO,{kEmptyObject:mm,once:wm}=Xt(),{validateAbortSignal:lO,validateFunction:hO,validateObject:pO,validateBoolean:yO}=Ta(),{Promise:gO,PromisePrototypeThen:mO,SymbolDispose:wS}=nt(),{isClosed:wO,isReadable:dS,isReadableNodeStream:gm,isReadableStream:bO,isReadableFinished:fS,isReadableErrored:lS,isWritable:hS,isWritableNodeStream:pS,isWritableStream:xO,isWritableFinished:yS,isWritableErrored:gS,isNodeStream:EO,willEmitClose:vO,kIsClosedPromise:SO}=ti(),_a;function AO(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:pO(e,"options"),hO(r,"callback"),lO(e.signal,"options.signal"),r=wm(r),bO(t)||xO(t))return TO(t,e,r);if(!EO(t))throw new fO("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=vO(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=wO(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)},I=()=>{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)};AO(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||dS(t))&&(f||hS(t)===!1)||!s&&(!d||hS(t))&&(p||dS(t)===!1)||a&&t.req&&t.aborted)&&Vo.nextTick(I);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||Xt().addAbortListener;let M=_a(e.signal,T),q=r;r=wm((...j)=>{M[wS](),q.apply(t,j)})}}return O}function TO(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||Xt().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 mO(t[SO].promise,o,o),bm}function _O(t,e){var r;let n=!1;return e===null&&(e=mm),(r=e)!==null&&r!==void 0&&r.cleanup&&(yO(e.cleanup,"cleanup"),n=e.cleanup),new gO((i,o)=>{let s=bS(t,e,c=>{n&&s(),c?o(c):i()})})}xm.exports=bS;xm.exports.finished=_O});var nc=oe((EF,IS)=>{"use strict";l();var ri=xi(),{aggregateTwoErrors:IO,codes:{ERR_MULTIPLE_CALLBACK:BO},AbortError:RO}=or(),{Symbol:vS}=nt(),{kIsDestroyed:UO,isDestroyed:OO,isFinished:DO,isServerRequest:kO}=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 NO(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(CO,t,o):ri.nextTick(TS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function CO(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 LO(){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 PO(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(MO,t)}function MO(t){let e=!1;function r(n){if(e){Sm(t,n??new BO);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(KO,t)}try{t._construct(n=>{ri.nextTick(r,n)})}catch(n){ri.nextTick(r,n)}}function KO(t){t.emit(Em)}function ES(t){return t?.setHeader&&typeof t.abort=="function"}function _S(t){t.emit("close")}function $O(t,e){t.emit("error",e),ri.nextTick(_S,t)}function HO(t,e){!t||OO(t)||(!e&&!DO(t)&&(e=new RO),kO(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($O,t,e):ri.nextTick(_S,t),t.destroyed||(t[UO]=!0))}IS.exports={construct:PO,destroyer:HO,destroy:NO,undestroy:LO,errorOrDestroy:Sm}});var _h=oe((SF,RS)=>{"use strict";l();var{ArrayIsArray:VO,ObjectSetPrototypeOf:BS}=nt(),{EventEmitter:Ah}=la();function Th(t){Ah.call(this,t)}BS(Th.prototype,Ah.prototype);BS(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):VO(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}RS.exports={Stream:Th,prependListener:Am}});var Id=oe((TF,Ih)=>{"use strict";l();var{SymbolDispose:qO}=nt(),{AbortError:US,codes:FO}=or(),{isNodeStream:OS,isWebStream:jO,kControllerErrorFunction:WO}=ti(),GO=Wi(),{ERR_INVALID_ARG_TYPE:DS}=FO,Tm,zO=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new DS(e,"AbortSignal",t)};Ih.exports.addAbortSignal=function(e,r){if(zO(e,"signal"),!OS(r)&&!jO(r))throw new DS("stream",["ReadableStream","WritableStream","Stream"],r);return Ih.exports.addAbortSignalNoValidate(e,r)};Ih.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[WO](new US(void 0,{cause:t.reason}))};if(t.aborted)r();else{Tm=Tm||Xt().addAbortListener;let n=Tm(t,r);GO(e,n[qO])}return e}});var CS=oe((BF,NS)=>{"use strict";l();var{StringPrototypeSlice:kS,SymbolIterator:YO,TypedArrayPrototypeSet:Bh,Uint8Array:JO}=nt(),{Buffer:_m}=Ar(),{inspect:ZO}=Xt();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;)Bh(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}*[YO](){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)Bh(r,s,n-e),e-=s.length;else{e===s.length?(Bh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Bh(r,new JO(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 ZO(this,{...r,depth:0,customInspect:!1})}}});var Bd=oe((UF,KS)=>{"use strict";l();var{MathFloor:XO,NumberIsInteger:QO}=nt(),{validateInteger:e3}=Ta(),{ERR_INVALID_ARG_VALUE:t3}=or().codes,LS=16*1024,PS=16;function r3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function MS(t){return t?PS:LS}function n3(t,e){e3(e,"value",0),t?PS=e:LS=e}function i3(t,e,r,n){let i=r3(e,n,r);if(i!=null){if(!QO(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new t3(o,i)}return XO(i)}return MS(t.objectMode)}KS.exports={getHighWaterMark:i3,getDefaultHighWaterMark:MS,setDefaultHighWaterMark:n3}});var VS=oe((Im,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,Im),Im.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 o3(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 s3(t){var e=o3(t);if(typeof e!="string"&&(Rm.isEncoding===qS||!qS(t)))throw new Error("Unknown encoding: "+t);return e||t}FS.StringDecoder=Rd;function Rd(t){this.encoding=s3(t);var e;switch(this.encoding){case"utf16le":this.text=l3,this.end=h3,e=4;break;case"utf8":this.fillLast=u3,e=4;break;case"base64":this.text=p3,this.end=y3,e=3;break;default:this.write=g3,this.end=m3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Rm.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=f3;Rd.prototype.text=d3;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 c3(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 a3(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 u3(t){var e=this.lastTotal-this.lastNeed,r=a3(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 d3(t,e){var r=c3(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 f3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function l3(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 h3(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 p3(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 y3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function g3(t){return t.toString(this.encoding)}function m3(t){return t&&t.length?this.write(t):""}});var Um=oe((CF,YS)=>{"use strict";l();var WS=xi(),{PromisePrototypeThen:w3,SymbolAsyncIterator:GS,SymbolIterator:zS}=nt(),{Buffer:b3}=Ar(),{ERR_INVALID_ARG_TYPE:x3,ERR_STREAM_NULL_VALUES:E3}=or().codes;function v3(t,e,r){let n;if(typeof e=="string"||e instanceof b3)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 x3("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){w3(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 E3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}YS.exports=v3});var Od=oe((PF,hA)=>{l();var An=xi(),{ArrayPrototypeIndexOf:S3,NumberIsInteger:A3,NumberIsNaN:T3,NumberParseInt:_3,ObjectDefineProperties:Mm,ObjectKeys:I3,ObjectSetPrototypeOf:XS,Promise:QS,SafeSet:B3,SymbolAsyncDispose:R3,SymbolAsyncIterator:U3,Symbol:O3}=nt();hA.exports=ye;ye.ReadableState=kh;var{EventEmitter:D3}=la(),{Stream:qo,prependListener:k3}=_h(),{Buffer:Om}=Ar(),{addAbortSignal:N3}=Id(),eA=Wi(),xe=Xt().debuglog("stream",t=>{xe=t}),C3=CS(),Ra=nc(),{getHighWaterMark:L3,getDefaultHighWaterMark:P3}=Bd(),{aggregateTwoErrors:JS,codes:{ERR_INVALID_ARG_TYPE:M3,ERR_METHOD_NOT_IMPLEMENTED:K3,ERR_OUT_OF_RANGE:$3,ERR_STREAM_PUSH_AFTER_EOF:H3,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:V3},AbortError:q3}=or(),{validateObject:F3}=Ta(),oc=O3("kPaused"),{StringDecoder:tA}=jS(),j3=Um();XS(ye.prototype,qo.prototype);XS(ye,qo);var Dm=()=>{},{errorOrDestroy:Ia}=Ra,Ba=1,W3=2,rA=4,Ud=8,nA=16,Uh=32,Oh=64,iA=128,G3=256,z3=512,Y3=1024,Lm=2048,Pm=4096,J3=8192,Z3=16384,X3=32768,oA=65536,Q3=1<<17,eD=1<<18;function At(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Mm(kh.prototype,{objectMode:At(Ba),ended:At(W3),endEmitted:At(rA),reading:At(Ud),constructed:At(nA),sync:At(Uh),needReadable:At(Oh),emittedReadable:At(iA),readableListening:At(G3),resumeScheduled:At(z3),errorEmitted:At(Y3),emitClose:At(Lm),autoDestroy:At(Pm),destroyed:At(J3),closed:At(Z3),closeEmitted:At(X3),multiAwaitDrain:At(oA),readingMore:At(Q3),dataEmitted:At(eD)});function kh(t,e,r){typeof r!="boolean"&&(r=e instanceof ii()),this.state=Lm|Pm|nA|Uh,t&&t.objectMode&&(this.state|=Ba),r&&t&&t.readableObjectMode&&(this.state|=Ba),this.highWaterMark=t?L3(this,t,"readableHighWaterMark",r):P3(!1),this.buffer=new C3,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&&N3(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[D3.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[R3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new q3,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&Ba||(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 M3("chunk",["string","Buffer","Uint8Array"],e))),o)Ia(t,o);else if(e===null)i.state&=~Ud,nD(t,i);else if(i.state&Ba||e&&e.length>0)if(n)if(i.state&rA)Ia(t,new V3);else{if(i.destroyed||i.errored)return!1;km(t,i,e,!0)}else if(i.ended)Ia(t,new H3);else{if(i.destroyed||i.errored)return!1;i.state&=~Ud,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&=~Ud,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 tD=1073741824;function rD(t){if(t>tD)throw new $3("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&Ba?1:T3(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:A3(t)||(t=_3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=rD(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|=Ud|Uh,e.length===0&&(e.state|=Oh);try{this._read(e.highWaterMark)}catch(o){Ia(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 nD(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(iD,t,e))}function iD(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 K3("_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 B3(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,I){xe("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.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=oD(r,t),t.on("drain",a))}r.on("data",h);function h(S){xe("ondata");let I=t.write(S);xe("dest.write",I),I===!1&&f()}function p(S){if(xe("onerror",S),E(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Ia(t,S):t.emit("error",S)}}k3(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 oD(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=S3(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(sD,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 sD(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,cD(this,t)),t[oc]=!1,this};function cD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(aD,t,e))}function aD(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=>{Ia(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[U3]=function(){return dA(this)};ye.prototype.iterator=function(t){return t!==void 0&&F3(t,"options"),dA(this,t)};function dA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=uD(t,e);return r.stream=t,r}async function*uD(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(dD,e,t))}function dD(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(fD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function fD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return j3(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((KF,TA)=>{l();var sc=xi(),{ArrayPrototypeSlice:gA,Error:lD,FunctionPrototypeSymbolHasInstance:mA,ObjectDefineProperty:wA,ObjectDefineProperties:hD,ObjectSetPrototypeOf:bA,StringPrototypeToLowerCase:pD,Symbol:yD,SymbolHasInstance:gD}=nt();TA.exports=it;it.WritableState=Nd;var{EventEmitter:mD}=la(),Dd=_h().Stream,{Buffer:Ch}=Ar(),Mh=nc(),{addAbortSignal:wD}=Id(),{getHighWaterMark:bD,getDefaultHighWaterMark:xD}=Bd(),{ERR_INVALID_ARG_TYPE:ED,ERR_METHOD_NOT_IMPLEMENTED:vD,ERR_MULTIPLE_CALLBACK:xA,ERR_STREAM_CANNOT_PIPE:SD,ERR_STREAM_DESTROYED:kd,ERR_STREAM_ALREADY_FINISHED:AD,ERR_STREAM_NULL_VALUES:TD,ERR_STREAM_WRITE_AFTER_END:_D,ERR_UNKNOWN_ENCODING:EA}=or().codes,{errorOrDestroy:Ua}=Mh;bA(it.prototype,Dd.prototype);bA(it,Dd);function Hm(){}var Oa=yD("kOnFinished");function Nd(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?bD(this,t,"writableHighWaterMark",r):xD(!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=BD.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 gA(this.buffered,this.bufferedIndex)};wA(Nd.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 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&&wD(t.signal,this)),Dd.call(this,t),Mh.construct(this,()=>{let r=this._writableState;r.writing||qm(this,r),Fm(this,r)})}wA(it,gD,{__proto__:null,value:function(t){return mA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Nd}});it.prototype.pipe=function(){Ua(this,new SD)};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 TD;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 ED("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new _D:i.destroyed&&(o=new kd("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=pD(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 kd("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 BD(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(RD,r.afterWriteTickInfo)):SA(t,r,1,i))}function RD({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 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 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 vD("_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 lD&&(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 AD("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 UD(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 OD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,UD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Fm(t,e,r){Lh(e)&&(OD(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()}}hD(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 DD=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),DD.call(this,t,e),this};it.prototype._undestroy=Mh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[mD.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((HF,KA)=>{l();var jm=xi(),kD=Ar(),{isReadable:ND,isWritable:CD,isIterable:_A,isNodeStream:LD,isReadableNodeStream:IA,isWritableNodeStream:BA,isDuplexNodeStream:PD,isReadableStream:RA,isWritableStream:UA}=ti(),OA=Wi(),{AbortError:PA,codes:{ERR_INVALID_ARG_TYPE:MD,ERR_INVALID_RETURN_VALUE:DA}}=or(),{destroyer:ka}=nc(),KD=ii(),MA=Od(),$D=Kh(),{createDeferredPromise:kA}=Xt(),NA=Um(),CA=globalThis.Blob||kD.Blob,HD=typeof CA<"u"?function(e){return e instanceof CA}:function(e){return!1},VD=globalThis.AbortController||Sa().AbortController,{FunctionPrototypeCall:LA}=nt(),Fo=class extends KD{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(PD(e))return e;if(IA(e))return Da({readable:e});if(BA(e))return Da({writable:e});if(LD(e))return Da({writable:!1,readable:!1});if(RA(e))return Da({readable:MA.fromWeb(e)});if(UA(e))return Da({writable:$D.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=qD(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(HD(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?IA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?BA(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 MD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function qD(t){let{promise:e,resolve:r}=kA(),n=new VD,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=!!ND(e),i=!!CD(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((qF,qA)=>{"use strict";l();var{ObjectDefineProperties:FD,ObjectGetOwnPropertyDescriptor:Gi,ObjectKeys:jD,ObjectSetPrototypeOf:HA}=nt();qA.exports=Tn;var zm=Od(),nn=Kh();HA(Tn.prototype,zm.prototype);HA(Tn,zm);{let t=jD(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}FD(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((jF,jA)=>{"use strict";l();var{ObjectSetPrototypeOf:FA,Symbol:WD}=nt();jA.exports=zi;var{ERR_METHOD_NOT_IMPLEMENTED:GD}=or().codes,Jm=ii(),{getHighWaterMark:zD}=Bd();FA(zi.prototype,Jm.prototype);FA(zi,Jm);var Cd=WD("kCallback");function zi(t){if(!(this instanceof zi))return new zi(t);let e=t?zD(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[Cd]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",YD)}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 YD(){this._final!==Ym&&Ym.call(this)}zi.prototype._final=Ym;zi.prototype._transform=function(t,e,r){throw new GD("_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 Qm=oe((GF,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((YF,XA)=>{l();var Ld=xi(),{ArrayIsArray:JD,Promise:ZD,SymbolAsyncIterator:XD,SymbolDispose:QD}=nt(),Vh=Wi(),{once:e4}=Xt(),t4=nc(),zA=ii(),{aggregateTwoErrors:r4,codes:{ERR_INVALID_ARG_TYPE:aw,ERR_INVALID_RETURN_VALUE:ew,ERR_MISSING_ARGS:n4,ERR_STREAM_DESTROYED:i4,ERR_STREAM_PREMATURE_CLOSE:o4},AbortError:s4}=or(),{validateFunction:c4,validateAbortSignal:a4}=Ta(),{isIterable:cc,isReadable:tw,isReadableNodeStream:Hh,isNodeStream:YA,isTransformStream:Ca,isWebStream:u4,isReadableStream:rw,isReadableFinished:d4}=ti(),f4=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,t4.destroyer(t,o||new i4("pipe")))},cleanup:i}}function l4(t){return c4(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function sw(t){if(cc(t))return t;if(Hh(t))return h4(t);throw new aw("val",["Readable","Iterable","AsyncIterable"],t)}async function*h4(t){iw||(iw=Od()),yield*iw.prototype[XD].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 ZD((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?r4(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 p4(...t){return ZA(t,e4(l4(t)))}function ZA(t,e,r){if(t.length===1&&JD(t[0])&&(t=t[0]),t.length<2)throw new n4("streams");let n=new f4,i=n.signal,o=r?.signal,s=[];a4(o,"options.signal");function c(){g(new s4)}ow=ow||Xt().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[QD](),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(YA(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}=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(),Ld.nextTick(p)},_=>{$.destroy(_),Ld.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 $=y4(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(u4(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)&&Ld.nextTick(c),y}function y4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new o4)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;d4(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)}XA.exports={pipelineImpl:ZA,pipeline:p4}});var dw=oe((ZF,iT)=>{"use strict";l();var{pipeline:g4}=qh(),Fh=ii(),{destroyer:m4}=nc(),{isNodeStream:jh,isReadable:QA,isWritable:eT,isWebStream:uw,isTransformStream:ac,isWritableStream:tT,isReadableStream:rT}=ti(),{AbortError:w4,codes:{ERR_INVALID_ARG_VALUE:nT,ERR_MISSING_ARGS:b4}}=or(),x4=Wi();iT.exports=function(...e){if(e.length===0)throw new b4("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=g4(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,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;x4(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 w4),o=null,n=null,i=null,s===null?g(p):(s=g,jh(d)&&m4(d,p))},c}});var pT=oe((QF,hw)=>{"use strict";l();var E4=globalThis.AbortController||Sa().AbortController,{codes:{ERR_INVALID_ARG_VALUE:v4,ERR_INVALID_ARG_TYPE:Pd,ERR_MISSING_ARGS:S4,ERR_OUT_OF_RANGE:A4},AbortError:oi}=or(),{validateAbortSignal:uc,validateInteger:oT,validateObject:dc}=Ta(),T4=nt().Symbol("kWeak"),_4=nt().Symbol("kResistStopPropagation"),{finished:I4}=Wi(),B4=dw(),{addAbortSignalNoValidate:R4}=Id(),{isWritable:U4,isNodeStream:O4}=ti(),{deprecate:D4}=Xt(),{ArrayPrototypePush:k4,Boolean:N4,MathFloor:sT,Number:C4,NumberIsNaN:L4,Promise:cT,PromiseReject:aT,PromiseResolve:P4,PromisePrototypeThen:uT,Symbol:fT}=nt(),Wh=fT("kEmpty"),dT=fT("kEof");function M4(t,e){if(e!=null&&dc(e,"options"),e?.signal!=null&&uc(e.signal,"options.signal"),O4(t)&&!U4(t))throw new v4("stream",t,"must be writable");let r=B4(this,t);return e!=null&&e.signal&&R4(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=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=Xt().AbortSignalAny([e?.signal].filter(N4)),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=P4(S)}catch(I){S=aT(I)}h+=1,uT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new cT(I=>{d=I})}c.push(dT)}catch(S){let I=aT(S);uT(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===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 K4(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 $4(t,e=void 0){if(typeof t!="function")throw new Pd("fn",["Function","AsyncFunction"],t);return!await lT.call(this,async(...r)=>!await t(...r),e)}async function H4(t,e){for await(let r of lw.call(this,t,e))return r}async function V4(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 lw(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 fw=class extends S4{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function q4(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 oi(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await I4(this.destroy(u)),u}let o=new E4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[T4]:this,[_4]:!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 F4(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});k4(e,n)}return e}function j4(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=C4(t),L4(t))return 0;if(t<0)throw new A4("number",">= 0",t);return t}function W4(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 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;if(t-- >0&&(yield o),t<=0)return}}).call(this)}hw.exports.streamReturningOperators={asIndexedPairs:D4(K4,"readable.asIndexedPairs will be removed in a future version."),drop:W4,filter:lw,flatMap:j4,map:Gh,take:G4,compose:M4};hw.exports.promiseReturningOperators={every:$4,forEach:V4,reduce:q4,toArray:F4,some:lT,find:H4}});var pw=oe((tj,yT)=>{"use strict";l();var{ArrayPrototypePop:z4,Promise:Y4}=nt(),{isIterable:J4,isNodeStream:Z4,isWebStream:X4}=ti(),{pipelineImpl:Q4}=qh(),{finished:ek}=Wi();yw();function tk(...t){return new Y4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!Z4(o)&&!J4(o)&&!X4(o)){let s=z4(t);n=s.signal,i=s.end}Q4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}yT.exports={finished:ek,pipeline:tk}});var yw=oe((nj,AT)=>{l();var{Buffer:rk}=Ar(),{ObjectDefineProperty:Yi,ObjectKeys:wT,ReflectApply:bT}=nt(),{promisify:{custom:xT}}=Xt(),{streamReturningOperators:gT,promiseReturningOperators:mT}=pT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:ET}}=or(),nk=dw(),{setDefaultHighWaterMark:ik,getDefaultHighWaterMark:ok}=Bd(),{pipeline:vT}=qh(),{destroyer:sk}=nc(),ST=Wi(),gw=pw(),Md=ti(),We=AT.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 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:ck}=Id();We.addAbortSignal=ck;We.finished=ST;We.destroy=sk;We.compose=nk;We.setDefaultHighWaterMark=ik;We.getDefaultHighWaterMark=ok;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 rk.from(e.buffer,e.byteOffset,e.byteLength)}});var ww=oe((oj,ht)=>{"use strict";l();var Tt=yw(),ak=pw(),uk=Tt.Readable.destroy;ht.exports=Tt.Readable;ht.exports._uint8ArrayToBuffer=Tt._uint8ArrayToBuffer;ht.exports._isUint8Array=Tt._isUint8Array;ht.exports.isDisturbed=Tt.isDisturbed;ht.exports.isErrored=Tt.isErrored;ht.exports.isReadable=Tt.isReadable;ht.exports.Readable=Tt.Readable;ht.exports.Writable=Tt.Writable;ht.exports.Duplex=Tt.Duplex;ht.exports.Transform=Tt.Transform;ht.exports.PassThrough=Tt.PassThrough;ht.exports.addAbortSignal=Tt.addAbortSignal;ht.exports.finished=Tt.finished;ht.exports.destroy=Tt.destroy;ht.exports.destroy=uk;ht.exports.pipeline=Tt.pipeline;ht.exports.compose=Tt.compose;Object.defineProperty(Tt,"promises",{configurable:!0,enumerable:!0,get(){return ak}});ht.exports.Stream=Tt.Stream;ht.exports.default=ht.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 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)),yt="[\\:\\/\\?\\#\\[\\]\\@]",Ee="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(yt,Ee),gt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=B?"[\\uE000-\\uF8FF]":"[]",Ae=e(v,K,"[\\-\\.\\_\\~]",gt),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),pu=r(r(r(Ke+"\\:")+"{0,2}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{2}"+Sr),_f=r(r(r(Ke+"\\:")+"{0,3}"+Ke)+"?\\:\\:"+Ke+"\\:"+Sr),If=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,pu,_f,If,Ac,Tc].join("|")),_c=r(r(Ae+"|"+Ue)+"+"),iy=r(yi+"\\%25"+_c),ls=r(yi+r("\\%25|\\%(?!"+te+"{2})")+_c),uB=r("[vV]"+te+"+\\."+e(Ae,Ee,"[\\:]")+"+"),dB=r("\\["+r(ls+"|"+yi+"|"+uB)+"\\]"),fx=r(r(Ue+"|"+e(Ae,Ee))+"*"),yu=r(dB+"|"+Gr+"(?!"+fx+")|"+fx),gu=r(K+"*"),lx=r(r(Ne+"@")+"?"+yu+r("\\:"+gu)+"?"),mu=r(Ue+"|"+e(Ae,Ee,"[\\:\\@]")),fB=r(mu+"*"),hx=r(mu+"+"),lB=r(r(Ue+"|"+e(Ae,Ee,"[\\@]"))+"+"),gi=r(r("\\/"+fB)+"*"),Ic=r("\\/"+r(hx+gi)+"?"),oy=r(lB+gi),Bf=r(hx+gi),Bc="(?!"+mu+")",DL=r(gi+"|"+Ic+"|"+oy+"|"+Bf+"|"+Bc),Rc=r(r(mu+"|"+e("[\\/\\?]",Ze))+"*"),wu=r(r(mu+"|[\\/\\?]")+"*"),px=r(r("\\/\\/"+lx+gi)+"|"+Ic+"|"+Bf+"|"+Bc),hB=r(rt+"\\:"+px+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),pB=r(r("\\/\\/"+lx+gi)+"|"+Ic+"|"+oy+"|"+Bc),yB=r(pB+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),kL=r(hB+"|"+yB),NL=r(rt+"\\:"+px+r("\\?"+Rc)+"?"),CL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+gi+"|"+Ic+"|"+Bf+"|"+Bc+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",LL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+gi+"|"+Ic+"|"+oy+"|"+Bc+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",PL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+gi+"|"+Ic+"|"+Bf+"|"+Bc+")")+r("\\?("+Rc+")")+"?$",ML="^"+r("\\#("+wu+")")+"?$",KL="^"+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("^\\[?("+yi+")"+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(yt){te=!0,fe=yt}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 yt=ve>0?ve+1:0;yt<K;){for(var Ee=H,tt=1,gt=p;;gt+=p){yt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(yt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Ae=gt<=fe?g:gt>=fe+y?y:gt-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,yt=void 0;try{for(var Ee=v[Symbol.iterator](),tt;!(ve=(tt=Ee.next()).done);ve=!0){var gt=tt.value;gt<128&&k.push(Q(gt))}}catch(ls){Ue=!0,yt=ls}finally{try{!ve&&Ee.return&&Ee.return()}finally{if(Ue)throw yt}}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 pu=v[Symbol.iterator](),_f;!(Ln=(_f=pu.next()).done);Ln=!0){var If=_f.value;if(If<H&&++te>h&&G("overflow"),If==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&&pu.return&&pu.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(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],yt=ve[1],Ee=yt?yt.split(":").map(ee):[],tt=Ue.split(":").map(ee),gt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=gt?7:8,Ae=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=Ee[Ne]||tt[Ae+Ne]||"";gt&&(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 B}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function bt(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 hi(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=hi(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=bt(jr(B,k),k),v=bt(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(bt(B,K),bt(v,K),K,!0),K)}function lu(B,v){return typeof B=="string"?B=jr(bt(B,v),v):n(B)==="object"&&(B=bt(jr(B,v),v)),B}function vf(B,v,k){return typeof B=="string"?B=jr(bt(B,k),k):n(B)==="object"&&(B=jr(B,k)),typeof v=="string"?v=jr(bt(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={},XI=!0,sx="[A-Za-z0-9\\-\\.\\_\\~"+(XI?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",QI=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),eB="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",tB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",rB=e(tB,'[\\"\\\\]'),nB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",iB=new RegExp(sx,"g"),Sc=new RegExp(QI,"g"),oB=new RegExp(e("[^]",eB,"[\\.]",'[\\"]',rB),"g"),cx=new RegExp(e("[^]",sx,nB),"g"),sB=cx;function ny(B){var v=Z(B);return v.match(iB)?v:B}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,yt=ve.length;Ue<yt;++Ue){var Ee=ve[Ue].split("=");switch(Ee[0]){case"to":for(var tt=Ee[1].split(","),gt=0,Ze=tt.length;gt<Ze;++gt)H.push(tt[gt]);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("@"),yt=ve.slice(0,Ue).replace(Sc,ny).replace(Sc,i).replace(oB,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]=yt+"@"+Ee}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var gt=[];for(var Ze in tt)tt[Ze]!==ry[Ze]&>.push(Ze.replace(Sc,ny).replace(Sc,i).replace(cx,Y)+"="+tt[Ze].replace(Sc,ny).replace(Sc,i).replace(sB,Y));return gt.length&&(K.query=gt.join("&")),K}},cB=/^([^\:]+)\:(.*)/,ux={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(cB),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),ve=K[2],Ue=te+":"+(k.nid||fe),yt=W[Ue];H.nid=fe,H.nss=ve,H.path=void 0,yt&&(H=yt.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}},aB=/^[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(aB))&&(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[ax.scheme]=ax,W[ux.scheme]=ux,W[dx.scheme]=dx,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=bt,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 z_=oe((OZ,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 cI=oe((NQ,sI)=>{l();var tu=1e3,ru=tu*60,nu=ru*60,mc=nu*24,FC=mc*7,jC=mc*365.25;sI.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return WC(t);if(r==="number"&&isFinite(t))return e.long?zC(t):GC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function WC(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*jC;case"weeks":case"week":case"w":return r*FC;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 GC(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 zC(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 OL={};bu(OL,{AggregateBeaconError:()=>U0,Appendix:()=>ot,BECH32M_CHARS:()=>_L,BTCR2_DID_DOCUMENT_CONTEXT:()=>zI,BeaconError:()=>Yt,BeaconFactory:()=>Cs,BeaconSignalDiscovery:()=>Qb,BeaconUtils:()=>Vr,CASBeacon:()=>Gu,CASBeaconError:()=>O0,CHANGE_OUTPUT_VBYTES:()=>L0,DEFAULT_FEE_ESTIMATOR:()=>Ol,DID_REGEX:()=>YI,DUST_LIMIT_SATS:()=>P0,DidBtcr2:()=>wf,DidDocument:()=>Fr,DidDocumentBuilder:()=>ox,DidVerificationMethod:()=>Qp,GenesisDocument:()=>ey,ID_PLACEHOLDER_VALUE:()=>qr,Identifier:()=>dr,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>vc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Ec,P2PKH_BEACON_TX_VSIZE:()=>Uv,P2TR_BEACON_TX_VSIZE:()=>Bv,P2WPKH_BEACON_TX_VSIZE:()=>Rv,Resolver:()=>fo,SINGLETON_BEACON_TX_VSIZE:()=>Ov,SMTBeacon:()=>td,SMTBeaconError:()=>ta,SPENDABLE_DUST_LIMIT_SATS:()=>Dl,SinglePartyBeacon:()=>Ni,SingletonBeacon:()=>zu,SingletonBeaconError:()=>R0,StaticFeeEstimator:()=>ra,Updater:()=>mf,beaconTxVsize:()=>M0,buildAggregationBeaconTx:()=>e6,deriveSingletonAddress:()=>Dv,detectSingletonScriptKind:()=>K0,extractOpReturnSignalHash:()=>Xb,getAggregationCommunicationKey:()=>ZI,isMultikeyVerificationMethod:()=>JI,opReturnScript:()=>H0,resolveBtcr2SenderPk:()=>UL,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 xu(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");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 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 Eu(t,e){return t<<e|t>>>32-e>>>0}var Mx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",t8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lt(t){if(hn(t),Mx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=t8[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 vu(t){return typeof t=="string"&&(t=ws(t)),hn(t),t}function dt(...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(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 r8(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),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;r8(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 n8=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)+n8[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=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),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 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 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(Lt(t))}function Ay(t){return hn(t),Kx(Lt(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 st(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 $x(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 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 dt(...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 rr=BigInt(0),Ft=BigInt(1),bs=BigInt(2),Fx=BigInt(3),jx=BigInt(4),Wx=BigInt(5),i8=BigInt(7),Gx=BigInt(8),o8=BigInt(9),zx=BigInt(16);function Ir(t,e){let r=t%e;return r>=rr?r:e+r}function Br(t,e,r){let n=t;for(;e-- >rr;)n*=n,n%=r;return n}function Vx(t,e){if(t===rr)throw new Error("invert: expected non-zero number");if(e<=rr)throw new Error("invert: expected positive modulus, got "+e);let r=Ir(t,e),n=e,i=rr,o=Ft,s=Ft,c=rr;for(;r!==rr;){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!==Ft)throw new Error("invert: does not exist");return Ir(i,e)}function Iy(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+Ft)/jx,n=t.pow(e,r);return Iy(t,n,e),n}function s8(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 Iy(t,c,e),c}function c8(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+i8)/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 Iy(c,E,a),E}}function Jx(t){if(t<Fx)throw new Error("sqrt is not defined for small field");let e=t-Ft,r=0;for(;e%bs===rr;)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+Ft)/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=Ft<<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 a8(t){return t%jx===Fx?Yx:t%Gx===Wx?s8:t%zx===o8?c8(t):Jx(t)}var u8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function By(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=u8.reduce((n,i)=>(n[i]="function",n),e);return Iu(t,r),t}function d8(t,e,r){if(r<rr)throw new Error("invalid exponent, negatives unsupported");if(r===rr)return t.ONE;if(r===Ft)return e;let n=t.ONE,i=e;for(;r>rr;)r&Ft&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ft;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-Ft)/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<=rr)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:rr,ONE:Ft,allowedLengths:c,create:h=>Ir(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return rr<=h&&h<t},is0:h=>h===rr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ft)===Ft,neg:h=>Ir(-h,t),eql:(h,p)=>h===p,sqr:h=>Ir(h*h,t),add:(h,p)=>Ir(h+p,t),sub:(h,p)=>Ir(h-p,t),mul:(h,p)=>Ir(h*p,t),pow:(h,p)=>d8(f,h,p),div:(h,p)=>Ir(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=a8(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=Ir(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=Ir(s,e-Ft)+Ft;return r?Ty(c,i):Lc(c,i)}var Pc=BigInt(0),xs=BigInt(1);function Bu(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 f8(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 l8(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(Bu(h,r[p])):i=i.add(Bu(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){f8(r,t),l8(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 By(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 h8(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 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)}},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=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}=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=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}=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=st("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),p8=BigInt(4);function bo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=st("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 y8(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(Su(D,"isCompressed"),D){d();let N=!n.isOdd(U);return dt(aE(N),L)}else return dt(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),p8),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 h8(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),_=Bu(x,_),D=Bu(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(st("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 Su(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Lt(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 g8(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=st("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 m8(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,dt(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=g8(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}=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(dt(aE((R&1)===0),V)),z=s.inv(P),W=T(st("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 dt(Uint8Array.of(this.recovery),U,L)}return dt(U,L)}toHex(x){return Lt(this.toBytes(x))}assertValidity(){}static fromCompact(x){return A.fromBytes(st("sig",x),"compact")}static fromDER(x){return A.fromBytes(st("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 Lt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Lt(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(st("extraEntropy",Y))}let J=dt(...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=st("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(st("sig",D),"der")}catch(N){if(!(N instanceof Ai.Err))throw N}if(!x)try{x=A.fromBytes(st("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=st("publicKey",U),x=j(st("message",x),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(st("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 w8(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 b8(t){let{CURVE:e,curveOpts:r}=w8(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 x8(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}=b8(t),o=y8(e,r),s=m8(o,n,i);return x8(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")},E8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},v8=BigInt(0),lE=BigInt(1),Ly=BigInt(2);function S8(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=Br(d,r,e)*d%e,h=Br(f,r,e)*d%e,p=Br(h,Ly,e)*u%e,g=Br(p,i,e)*p%e,y=Br(g,o,e)*g%e,E=Br(y,c,e)*y%e,S=Br(E,a,e)*E%e,I=Br(S,c,e)*y%e,A=Br(I,r,e)*d%e,O=Br(A,s,e)*g%e,T=Br(O,n,e)*u%e,M=Br(T,Ly,e);if(!jf.eql(jf.sqr(M),t))throw new Error("Cannot find square root");return M}var jf=wo(Kc.p,{sqrt:S8}),xo=fE({...Kc,Fp:jf,lowS:!0,endo:E8},ke),hE={};function Wf(t,...e){let r=hE[t];if(r===void 0){let n=ke(ws(t));r=dt(n,n),hE[t]=r}return ke(dt(r,...e))}var My=t=>t.toBytes(!0).slice(1),$c=xo.Point,Ky=t=>t%Ly===v8;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 Ru=Si;function gE(...t){return $c.Fn.create(Ru(Wf("BIP0340/challenge",...t)))}function pE(t){return Py(t).bytes}function A8(t,e,r=_r(32)){let{Fn:n}=$c,i=st("message",t),{bytes:o,scalar:s}=Py(e),c=st("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=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=st("signature",t,64),s=st("message",e),c=st("publicKey",r,32);try{let a=yE(Ru(c)),u=Ru(o.subarray(0,32));if(!_u(u,lE,Kc.p))return!1;let d=Ru(o.subarray(32,64));if(!_u(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:A8,verify:mE,Point:$c,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Wf,lift_x:yE,pointToBytes:My,numberToBytesBE:Lc,bytesToNumberBE:Si,mod:Ir},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var T8=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)),_8=bE.map(t=>(9*t+5)%16),xE=(()=>{let r=[[bE],[_8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>T8[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])),B8=vE.map((t,e)=>t.map(r=>SE[e][r])),R8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),U8=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=R8[p],E=U8[p],S=EE[p],I=vE[p],A=I8[p],O=B8[p];for(let T=0;T<16;T++){let M=Eu(n+wE(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+wE(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)}},AE=Lf(()=>new $y);l();l();function Hc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function O8(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 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 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 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;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 D8(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(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 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(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 k8(t){Ou(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(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 _E(t){return qy(t),function(...e){try{return t.apply(null,e)}catch{}}}function N8(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("")),C8=t=>Du(k8(58),Zf(t),Xf("")),Qf=C8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var DE=t=>Du(N8(4,e=>t(t(e))),Qf);var Vy=Du(Zf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Xf("")),IE=[996825010,642813549,513874426,1027748829,705979059];function Uu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<IE.length;n++)(e>>n&1)===1&&(r^=IE[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 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=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=_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)},L8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",P8={encode(t){return O8(t),t.toHex()},decode(t){return Vc("hex",t),Uint8Array.fromHex(t)}},Te=L8?P8:Du(jy(4),Zf("0123456789abcdef"),Xf(""),D8(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 M8(...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:M8,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}}},Ot={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ot.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(Ot.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ot.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)=>{Ot.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ot,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)=>`[${Ot.range(Ot.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ot.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ot,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 Ot.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ot.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(!Ot.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ot.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=Ot.create(this.data.length),Ot.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:Ot.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=Ot.indices(this.bs,this.data.length,!0);if(e.length){let r=Ot.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 jt(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 Wt=t=>{let e=PE(t);return t.validate?jt(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 K8(){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 $8={encode:t=>{if(typeof t!="bigint")throw new Error(`expected bigint, got ${typeof t}`);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${t}`);return Number(t)},decode:t=>{if(!qn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function H8(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 V8(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 q8(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}},Ii={dict:K8,numberBigint:$8,tsEnum:H8,decimal:V8,match:q8,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 Wt({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 F8=(t,e)=>Wt({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 F8(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)}),HE=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 gn=ku(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 Wt({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)=>jt(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 Wt({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 Wt({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 Wt({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 Wt({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 xt(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 Wt({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 Wt({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 Gt(t,e){if(!Ur(e))throw new Error(`array: invalid inner value ${e}`);let r=CE(typeof t=="string"?`../${t}`:t);return Wt({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,ct=tl.equalBytes;var zc=t=>AE(ke(t)),Bi=(...t)=>ke(ke(Fn(...t))),oM=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,Nu=Rr.utils.taggedHash,Et;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(Et||(Et={}));function vo(t,e){let r=t.length;if(e===Et.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return cl.fromHex(t),t}else if(e===Et.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 Cu(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 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 mt;(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"})(mt||(mt={}));function r0(t=6,e=!1){return Wt({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=Wt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(mt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(mt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(mt.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<mt.PUSHDATA1?t.byte(n):n<=255?(t.byte(mt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(mt.PUSHDATA2),t.bytes(Xy.encode(n))):(t.byte(mt.PUSHDATA4),t.bytes(_e.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(mt.OP_0<r&&r<=mt.PUSHDATA4){let n;if(r<mt.PUSHDATA1)n=r;else if(r===mt.PUSHDATA1)n=gn.decodeStream(t);else if(r===mt.PUSHDATA2)n=Xy.decodeStream(t);else if(r===mt.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(mt.OP_1<=r&&r<=mt.OP_16)e.push(r-(mt.OP_1-1));else{let n=mt[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=Wt({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,Ii.numberBigint),lr=Fe(Yc),Jc=Gt(Or,lr),dl=t=>Gt(Yc,t),tv=xt({txid:Fe(32,!0),index:_e,finalScriptSig:lr,sequence:_e}),Ri=xt({amount:Gc,script:lr}),j8=xt({version:Eo,segwitFlag:FE(new Uint8Array([0,1])),inputs:dl(tv),outputs:dl(Ri),witnesses:jE("segwitFlag",Gt("inputs/length",Jc)),lockTime:_e});function W8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Ui=jt(j8,W8),Es=xt({version:Eo,inputs:dl(tv),outputs:dl(Ri),lockTime:_e});var i0=jt(Fe(null),t=>vo(t,Et.ecdsa)),fl=jt(Fe(32),t=>vo(t,Et.schnorr)),rv=jt(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=xt({fingerprint:HE,path:Gt(null,_e)}),ov=xt({hashes:Gt(Or,Fe(32)),der:ll}),G8=Fe(78),z8=xt({pubKey:fl,leafHash:Fe(32)}),Y8=xt({version:gn,internalKey:Fe(32),merklePath:Gt(null,Fe(32))}),Oi=jt(Y8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),J8=Gt(null,xt({depth:gn,version:gn,script:lr})),vt=Fe(null),nv=Fe(20),Pu=Fe(32),hl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,G8,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,vt,vt,[],[0,2],!1]},Mu={nonWitnessUtxo:[0,!1,Ui,[],[0,2],!1],witnessUtxo:[1,!1,Ri,[],[0,2],!1],partialSig:[2,i0,vt,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,vt,[],[0,2],!1],witnessScript:[5,!1,vt,[],[0,2],!1],bip32Derivation:[6,i0,ll,[],[0,2],!1],finalScriptSig:[7,!1,vt,[],[0,2],!1],finalScriptWitness:[8,!1,Jc,[],[0,2],!1],porCommitment:[9,!1,vt,[],[0,2],!1],ripemd160:[10,nv,vt,[],[0,2],!1],sha256:[11,Pu,vt,[],[0,2],!1],hash160:[12,nv,vt,[],[0,2],!1],hash256:[13,Pu,vt,[],[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,rv,[],[0,2],!1],tapScriptSig:[20,z8,rv,[],[0,2],!1],tapLeafScript:[21,Oi,vt,[],[0,2],!1],tapBip32Derivation:[22,Pu,ov,[],[0,2],!1],tapInternalKey:[23,!1,fl,[],[0,2],!1],tapMerkleRoot:[24,!1,Pu,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},sv=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],cv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Ku={redeemScript:[0,!1,vt,[],[0,2],!1],witnessScript:[1,!1,vt,[],[0,2],!1],bip32Derivation:[2,i0,ll,[],[0,2],!1],amount:[3,!1,$E,[2],[2],!0],script:[4,!1,vt,[2],[2],!0],tapInternalKey:[5,!1,fl,[],[0,2],!1],tapTree:[6,!1,J8,[],[0,2],!1],tapBip32Derivation:[7,fl,ov,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},av=[],iv=Gt(Yy,xt({key:VE(Or,xt({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 hM=xt({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 Wt({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})}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=jt(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,Et.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,Et.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=jt(s0(Ku),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,Et.ecdsa);return t}),uv=jt(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=xt({magic:il(nl(new Uint8Array([255])),"psbt"),global:uv,inputs:Gt("global/unsignedTx/inputs/length",pl),outputs:Gt(null,yl)}),X8=xt({magic:il(nl(new Uint8Array([255])),"psbt"),global:uv,inputs:Gt("global/inputCount",pl),outputs:Gt("global/outputCount",yl)}),pM=xt({magic:il(nl(new Uint8Array([255])),"psbt"),items:Gt(null,yn(Gt(Yy,GE([qE(Or),Fe(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 dv(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&&!ct(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=jt(Z8,dv),u0=jt(X8,dv);var eR={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 tR={encode(t){if(!(t.length!==2||!Ce(t[0])||!So(t[0],Et.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},rR={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},nR={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},iR={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},oR={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},sR={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},cR={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},aR={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}},uR={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}},dR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},fR=[eR,tR,rR,nR,iR,oR,sR,cR,aR,uR,dR],lR=yn(Xe,Ii.match(fR)),Qe=jt(lR,t=>{if(t.type==="pk"&&!So(t.pubkey,Et.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,Et.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,Et.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,Et.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(!ct(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(!ct(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,Et.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,Et.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 hR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=yn(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(ct(s,ul))throw new Error("Unspendable taproot key in leaf script");if(ct(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&&!ct(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 hR(d,e,r,n),{type:"leaf",version:a,script:d,hash:$u(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 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]),lr.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,Et.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: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=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 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),pR={amount:0xffffffffffffffffn,script:He},yR=t=>Math.ceil(t/4),gR=8,mR=2,As=0,b0=4294967295,wR=Ii.decimal(gR),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 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 bR(t,e,r,n=He){return ct(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 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;sv.includes(r)||delete t[r]}}var m0=xt({txid:Fe(32,!0),index:_e});function xR(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 ER(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,mR),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 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&&(!ct(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(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=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=ER(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,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?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*lr.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*lr.encode(n.finalScriptSig||He).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Jc.encode(n.finalScriptWitness).length);return e}get vsize(){return yR(this.weight)}toBytes(e=!1,r=!1){return Ui.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(Bi(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Bi(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(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=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(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(pR).concat([a[e]]));let u=Ui.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Bi(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(Hu),h=this.outputs.map(Ts);o||(a=Bi(...f.map(m0.encode))),!o&&!c&&!s&&(u=Bi(...f.map(g=>_e.encode(g.sequence)))),!c&&!s?d=Bi(...h.map(Ri.encode)):c&&e<h.length&&(d=Bi(Ri.encode(h[e])));let p=f[e];return Bi(Eo.encode(this.version),a,u,Fe(32,!0).encode(p.txid),_e.encode(p.index),lr.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(Hu),p=this.outputs.map(Ts);f!==je.ANYONECANPAY&&u.push(...[h.map(m0.encode),i.map(Gc.encode),r.map(lr.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]),lr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(ke(lr.encode(a||He))),d===je.SINGLE&&u.push(e<p.length?ke(Ri.encode(p[e])):ml),s&&u.push($u(s,c),gn.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(!ct(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(xR):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}=bR(e,g,o.tapInternalKey,y),[I,A]=Cu(o.tapInternalKey,y);if(ct(I,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 I=S.subarray(0,-1),A=Xe.decode(I),O=S[S.length-1],T=$u(I,O);if(A.findIndex($=>Ce($)&&ct($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,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)&&(ct(y,d)||ct(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=$u(f,h),y=r.tapScriptSig.filter(S=>ct(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=>ct(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=>ct(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)&&ct(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(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=>ct(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(!ct(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,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 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:Pt,METHOD_NOT_SUPPORTED:xl,INTERNAL_ERROR:Ev,INVALID_DID_DOCUMENT:Oe,INVALID_DID_UPDATE:De,INVALID_DID_URL:nK,INVALID_PREVIOUS_DID_PROOF:iK,INVALID_PUBLIC_KEY:oK,INVALID_PUBLIC_KEY_MULTIBASE:sK,INVALID_PUBLIC_KEY_LENGTH:cK,INVALID_PUBLIC_KEY_TYPE:aK,INVALID_SIGNATURE:uK,PROOF_VERIFICATION_ERROR:ki,PROOF_GENERATION_ERROR:_o,PROOF_SERIALIZATION_ERROR:vv,PROOF_PARSING_ERROR:dK,VERIFICATION_METHOD_ERROR:El,LATE_PUBLISHING_ERROR:vl,INVALID_SIDECAR_DATA:fK,MISSING_UPDATE_DATA:lK,MISSING_RESOLUTION_OPTIONS:hK}=x0,zt=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 zt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var wt=class extends zt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},St=class extends zt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},Ve=class extends zt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var qe=class extends zt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},To=class extends zt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},mn=class extends zt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},wn=class extends zt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},jn=class extends zt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Is=class extends zt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},bn=class extends zt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var Zc=class extends zt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var vR=new Set(["jcs"]),SR=new Set(["hex","base58","base64urlnopad"]);function E0(t){let e=t.toLowerCase();if(!vR.has(e))throw new Zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function v0(t){let e=t.toLowerCase();if(!SR.has(e))throw new Zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function nr(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 Io(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 Bs(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 Io(nr(t,E0(e)))}function Wn(t,e){let r=E0(e?.algorithm??"jcs"),n=v0(e?.encoding??"base64urlnopad");return Qr(Io(nr(t,r)),n)}l();l();var S0={};bu(S0,{JsonPatchError:()=>at,_areEquals:()=>ju,applyOperation:()=>Rs,applyPatch:()=>Rl,applyReducer:()=>BR,deepClone:()=>_R,getValueByPointer:()=>Il,validate:()=>Av,validator:()=>Bl});l();l();var AR=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)}}(),TR=Object.prototype.hasOwnProperty;function Al(t,e){return TR.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 Mt(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 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 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 Fu=function(t){AR(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 at=Fu,_R=Mt,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=Il(r,this.path);n&&(n=Mt(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=Il(r,this.from);return Rs(r,{op:"add",path:this.path,value:Mt(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}}},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 Il(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):Bl(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=Il(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 at("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 at("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Mt(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=Bl;;){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 at("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 at("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 at("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 at("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new at("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 at("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Mt(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 BR(t,e,r){var n=Rs(t,e);if(n.test===!1)throw new at("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Bl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new at("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Qc[t.op]){if(typeof t.path!="string")throw new at("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new at('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 at("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 at("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 at("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 at("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 at("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 at("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new at("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 at("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Rl(Mt(e),Mt(t),r||!0);else{r=r||Bl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof at)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 I0={};bu(I0,{compare:()=>LR,generate:()=>A0,observe:()=>CR,unobserve:()=>NR});l();var T0=new WeakMap,RR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),UR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function OR(t){return T0.get(t)}function DR(t,e){return t.observers.get(e)}function kR(t,e){t.observers.delete(e.callback)}function NR(t,e){e.unobserve()}function CR(t,e){var r=[],n,i=OR(t);if(!i)i=new RR(t),T0.set(t,i);else{var o=DR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Mt(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),kR(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 UR(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:Mt(f)}),r.push({op:"replace",path:n+"/"+Gn(d),value:Mt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Gn(d),value:Mt(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:Mt(e[d])})}}}function LR(t,e,r){r===void 0&&(r=!1);var n=[];return _0(t,e,n,"",r),n}var Tv=Object.assign({},S0,I0,{JsonPatchError:Fu,deepClone:Mt,escapePathComponent:Gn,unescapePathComponent:qu});var{applyPatch:PR,compare:MR,deepClone:KR}=Tv,$R=new Set(["__proto__","constructor","prototype"]);function _v(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>$R.has(e))}var ea=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??KR,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=PR(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=MR(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 Bo;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(Bo||(Bo={}));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 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],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();function B0(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)||B0(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&&B0(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))B0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var Yt=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 JR={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 JR;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 Bv=160,Rv=155,Uv=240,Ov={p2pkh:Uv,p2wpkh:Rv,p2tr:Bv},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 Yt(`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 Yt(`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 QR(t,e){if(t.status.block_height!==e.status.block_height)return t.status.block_height-e.status.block_height;let r=t.txid.localeCompare(e.txid);return r!==0?r:t.vout-e.vout}function Nv(t,e){if(!t.length)throw new Yt("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 Yt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:Dl})}return[...n].sort(QR)[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 e6(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 Yt(`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 t6(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=dt(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 Yt(`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=dt(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;did;constructor(e,r){this.service=e,this.did=r}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 Yt(`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 Yt(`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 t6(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,r){super({...e,type:"CASBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;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(Bs(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.did,s=Wn(e),c={[o]:s},a=Io(nr(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,r){super({...e,type:"SingletonBeacon"},r)}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=Io(nr(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var r6=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 Yu(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=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");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",n6=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+=n6[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 hr(...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 Ju(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 Zu(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(i6(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 i6(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 o6(t,e,r){return Cl(t)&&Cl(e)&&Cl(r)&&e<=t&&t<r}function jv(t,e,r,n){if(!o6(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 Xu=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,hr(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 hr(...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 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 ft(...t){return ke(dt(...t))}function ed(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=ft(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 ft(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?ft(u,o):ft(o,u)}return s===e.length&&X0(o,i)}l();var s6=new TextEncoder;function Kl(t){return ed(ft(s6.encode(t)))}function Xv(t,e){return ft(ft(t),ft(e))}function Qv(t){return ft(ft(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 c6(t){let e={rootHash:Yn(t.id),collapsed:ed(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}=c6(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?ft(n.signedUpdate):void 0;return e1(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var td=class extends Ni{constructor(e,r){super({...e,type:"SMTBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;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?ft(ft(u),Yn(c.updateId)):ft(ft(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.did,s=new TextEncoder().encode(nr(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,r){switch(e.type){case"SingletonBeacon":return new zu(e,r);case"CASBeacon":return new Gu(e,r);case"SMTBeacon":return new td(e,r);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 lt={"@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 d6=Pn(n1(),1);l();l();l();l();var DH=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 l6(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 h6=l6,p6=h6,o1=p6;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 y6(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 g6(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 ir({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return c1({prefix:e,name:t,encode(i){return g6(i,n,r)},decode(i){return y6(i,n,r,t)}})}var rd=ir({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),HH=ir({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),VH=ir({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qH=ir({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),FH=ir({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jH=ir({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),WH=ir({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GH=ir({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cg=ir({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var pr=sg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ZH=sg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var tV=ir({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rV=ir({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Jn=ir({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nV=ir({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 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())})},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 pr.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 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 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 pr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return pr.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 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=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 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=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 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=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 pr.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 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 ag=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)}},m6=new ag;typeof window<"u"&&(window.web5logger=m6);l();l();l();l();var Mi={};bu(Mi,{decode:()=>ua,encodeTo:()=>Ps,encodingLength:()=>Ms});l();l();var w6=h1,f1=128,b6=127,x6=~b6,E6=Math.pow(2,31);function h1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=E6;)e[r++]=t&255|f1,t/=128;for(;t&x6;)e[r++]=t&255|f1,t>>>=7;return e[r]=t|0,h1.bytes=r-n+1,e}var v6=ug,S6=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>=S6);return ug.bytes=o-n,r}var A6=Math.pow(2,7),T6=Math.pow(2,14),_6=Math.pow(2,21),I6=Math.pow(2,28),B6=Math.pow(2,35),R6=Math.pow(2,42),U6=Math.pow(2,49),O6=Math.pow(2,56),D6=Math.pow(2,63),k6=function(t){return t<A6?1:t<T6?2:t<_6?3:t<I6?4:t<B6?5:t<R6?6:t<U6?7:t<O6?8:t<D6?9:10},N6={encode:w6,decode:v6,encodingLength:k6},C6=N6,od=C6;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 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 P6(r,lg(t),e??pr.encoder);default:return M6(r,lg(t),e??rd.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!==sd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==K6)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[$6]===!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!==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=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,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]=L6(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 L6(t,e){switch(t[0]){case"Q":{let r=e??pr;return[pr.prefix,r.decode(`${pr.prefix}${t}`)]}case pr.prefix:{let r=e??pr;return[pr.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 P6(t,e,r){let{prefix:n}=r;if(n!==pr.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 M6(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,K6=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 $6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Jt=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}}};Jt.codeToName=new Map;Jt.nameToCode=new Map;Jt.registerCodec({code:237,name:"ed25519-pub"});Jt.registerCodec({code:4864,name:"ed25519-priv"});Jt.registerCodec({code:236,name:"x25519-pub"});Jt.registerCodec({code:4866,name:"x25519-priv"});Jt.registerCodec({code:231,name:"secp256k1-pub"});Jt.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 GU=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 dk=Pn(ww(),1);var fk=Pn(ww(),1);l();l();l();l();l();function lk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function bw(t,...e){if(!lk(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 Rj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hk(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=hk(t)),bw(t),t}var zh=class{clone(){return this._cloneInto()}},Uj={}.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 IT(t=32){if(La&&typeof La.getRandomValues=="function")return La.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function pk(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 BT=(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;pk(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 yk=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+BT(c,a,u)+yk[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 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())})},Pa=class{static digest(e){return gk(this,arguments,void 0,function*({data:r}){return Go(r)})}};l();var si=class{};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())})},Zh=class extends si{digest(e){return mk(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 wk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Sw(t,...e){if(!wk(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),In=(t,e)=>t<<32-e|t>>>e,bk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!bk)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 Kd(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()}},tW={}.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 xk(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),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;xk(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 Ek=(t,e,r)=>t&e^~t&r,vk=(t,e,r)=>t&e^t&r^e&r,Sk=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=In(h,7)^In(h,18)^h>>>3,y=In(p,17)^In(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=In(c,6)^In(c,11)^In(c,25),p=d+h+Ek(c,a,u)+Sk[f]+Yo[f]|0,y=(In(n,2)^In(n,13)^In(n,22))+vk(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={};bu(ip,{bitGet:()=>Uk,bitLen:()=>Rk,bitMask:()=>Hd,bitSet:()=>Ok,bytesToHex:()=>Zi,bytesToNumberBE:()=>Xi,bytesToNumberLE:()=>Rn,concatBytes:()=>eo,createHmacDrbg:()=>Bw,ensureBytes:()=>Ge,equalBytes:()=>Ik,hexToBytes:()=>fc,hexToNumber:()=>Iw,isBytes:()=>Bn,numberToBytesBE:()=>gr,numberToBytesLE:()=>Qi,numberToHexUnpadded:()=>PT,numberToVarBytesBE:()=>_k,utf8ToBytes:()=>Bk,validateObject:()=>on});l();var LT=BigInt(0),np=BigInt(1),Ak=BigInt(2);function Bn(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Tk=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zi(t){if(!Bn(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Tk[t[r]];return e}function PT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Iw(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 Iw(Zi(t))}function Rn(t){if(!Bn(t))throw new Error("Uint8Array expected");return Iw(Zi(Uint8Array.from(t).reverse()))}function gr(t,e){return fc(t.toString(16).padStart(e*2,"0"))}function Qi(t,e){return gr(t,e).reverse()}function _k(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(Bn(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(!Bn(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 Bk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Rk(t){let e;for(e=0;t>LT;t>>=np,e+=1);return e}function Uk(t,e){return t>>BigInt(e)&np}var Ok=(t,e,r)=>t|(r?np:LT)<<BigInt(e),Hd=t=>(Ak<<BigInt(t-1))-np,_w=t=>new Uint8Array(t),CT=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=_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 Dk={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"||Bn(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=Dk[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 _t=BigInt(0),et=BigInt(1),lc=BigInt(2),kk=BigInt(3),Rw=BigInt(4),MT=BigInt(5),KT=BigInt(8),Nk=BigInt(9),Ck=BigInt(16);function Ie(t,e){let r=t%e;return r>=_t?r:e+r}function Uw(t,e,r){if(r<=_t||e<_t)throw new Error("Expected power/modulo > 0");if(r===et)return _t;let n=et;for(;e>_t;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >_t;)n*=n,n%=r;return n}function op(t,e){if(t===_t||e<=_t)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Ie(t,e),n=e,i=_t,o=et,s=et,c=_t;for(;r!==_t;){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 Ie(i,e)}function Lk(t){let e=(t-et)/lc,r,n,i;for(r=t-et,n=0;r%lc===_t;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 Pk(t){if(t%Rw===kk){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%Ck,Lk(t)}var $T=(t,e)=>(Ie(t,e)&et)===et,Mk=["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=Mk.reduce((n,i)=>(n[i]="function",n),e);return on(t,r)}function Kk(t,e,r){if(r<_t)throw new Error("Expected power > 0");if(r===_t)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>_t;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function $k(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<=_t)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=Pk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Hd(i),ZERO:_t,ONE:et,create:a=>Ie(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return _t<=a&&a<t},is0:a=>a===_t,isOdd:a=>(a&et)===et,neg:a=>Ie(-a,t),eql:(a,u)=>a===u,sqr:a=>Ie(a*a,t),add:(a,u)=>Ie(a+u,t),sub:(a,u)=>Ie(a-u,t),mul:(a,u)=>Ie(a*u,t),pow:(a,u)=>Kk(c,a,u),div:(a,u)=>Ie(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=>$k(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Qi(a,o):gr(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=Ie(s,e-et)+et;return r?Qi(c,i):gr(c,i)}l();l();var Vk=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>Vk;)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,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 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 qk(t){let e=Vd(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:Fk,hexToBytes:jk}=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:Fk(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=hc,r=typeof t=="string"?jk(t):t;if(!Bn(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),vW=BigInt(2),FT=BigInt(3),SW=BigInt(4);function Wk(t){let e=qk(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(Bn(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=Ie(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,FT),{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,FT),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===sn)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&sn&&(M=M.add(j)),T&sn&&(q=q.add(j)),j=j.double(),A>>=sn,T>>=sn;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===sn||!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===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 Gk(t){let e=Vd(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=Gk(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 Ie(x,n)}function a(x){return op(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Wk({...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(gr(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 I={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=Bn(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 gr(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 bt=c(Re*c(Z+Je*z));if(bt===to)return;let hi=(Me.x===Je?0:2)|Number(Me.y&sn),lo=bt;return C&&g(bt)&&(lo=y(bt),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 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"||Bn(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,OT(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),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 zk(t){return{hash:t,hmac:(e,...r)=>Cw(t,e,ep(...r)),randomBytes:$d}}function ap(t,e){let r=n=>jT({...t,...zk(n)});return Object.freeze({...r(e),create:r})}var zT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),WT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Yk=BigInt(1),Lw=BigInt(2),GT=(t,e)=>(t+e/Lw)/e;function Jk(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,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,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:Jk}),mr=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=-Yk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=GT(o*t,e),a=GT(-n*t,e),u=Ie(t-c*r-a*i,e),d=Ie(-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),MW=BigInt(0);var KW=mr.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 Zk=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 Zk(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 $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},Dt=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=mr.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:"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 $t(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 $t(this,arguments,void 0,function*({publicKeyBytes:r}){return mr.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:"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 $t(this,arguments,void 0,function*({derSignature:r}){return mr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return mr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=mr.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==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 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(!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 $t(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 $t(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 mr.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 mr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return mr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{mr.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 mr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=mr.getPublicKey(r));let n=mr.ProjectivePoint.fromHex(r),i=gr(n.x,32),o=gr(n.y,32);return{x:i,y:o}})}};l();l();var ZT=Ha(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Qk=ZT.create(BigInt("-3")),eN=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),tN=ap({a:Qk,b:eN,Fp:ZT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},rp),Cr=tN;var Ht=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())})},rN=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},Vt=class t{static adjustSignatureToLowS(e){return Ht(this,arguments,void 0,function*({signature:r}){let n=Cr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ht(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 Ht(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 Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ht(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 Ht(this,arguments,void 0,function*({derSignature:r}){return Cr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ht(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 Ht(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=rN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Ht(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 Ht(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 Ht(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 Ht(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 Ht(this,arguments,void 0,function*({privateKeyBytes:r}){return Cr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){try{Cr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ht(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 Ht(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Cr.getPublicKey(r));let n=Cr.ProjectivePoint.fromHex(r),i=gr(n.x,32),o=gr(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 si{computePublicKey(e){return qd(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 Dt.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.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 Dt.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Vt.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return qd(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 Dt.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.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(!ci(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield Dt.sign({key:r,data:n});case"P-256":return yield Vt.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 Dt.verify({key:r,signature:n,data:i});case"P-256":return yield Vt.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 nN(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 iN=(t,e)=>BigInt(t>>>0)<<Kw|BigInt(e>>>0),oN=(t,e,r)=>t>>>r,sN=(t,e,r)=>t<<32-r|e>>>r,cN=(t,e,r)=>t>>>r|e<<32-r,aN=(t,e,r)=>t<<32-r|e>>>r,uN=(t,e,r)=>t<<64-r|e>>>r-32,dN=(t,e,r)=>t>>>r-32|e<<64-r,fN=(t,e)=>e,lN=(t,e)=>t,hN=(t,e,r)=>t<<r|e>>>32-r,pN=(t,e,r)=>e<<r|t>>>32-r,yN=(t,e,r)=>e<<r-32|t>>>64-r,gN=(t,e,r)=>t<<r-32|e>>>64-r;function mN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var wN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),bN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,xN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),EN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,vN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),SN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var AN={fromBig:XT,split:nN,toBig:iN,shrSH:oN,shrSL:sN,rotrSH:cN,rotrSL:aN,rotrBH:uN,rotrBL:dN,rotr32H:fN,rotr32L:lN,rotlSH:hN,rotlSL:pN,rotlBH:yN,rotlBL:gN,add:mN,add3L:wN,add3H:bN,add4L:xN,add4H:EN,add5H:SN,add5L:vN},le=AN;var[TN,_N]=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: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,_N[A],Zo[A]),$=le.add5H(j,S,O,M,TN[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 Hw=tp(()=>new $w);l();var Un=BigInt(0),Lr=BigInt(1),dp=BigInt(2),IN=BigInt(8),BN={zip215:!0};function RN(t){let e=Vd(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=RN(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),bt=d(ue*Re),hi=d(ce*ee);return new T(Me,Je,hi,bt)}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),bt=d((V+J)*(Y+Z)-ce-Re),hi=Je-Me,lo=Je+Me,du=d(Re-C*ce),xf=d(bt*hi),ty=d(lo*du),ho=d(bt*du),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=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?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 Ie(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=BN;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),Vw=BigInt(1);function UN(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=UN(t),{P:r}=e,n=A=>Ie(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"&&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=Vw,$=jd,X=T,Q=Vw,G=jd,_;for(let x=BigInt(i-1);x>=jd;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===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"),e_=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),HG=BigInt(0),ON=BigInt(1),qw=BigInt(2),DN=BigInt(5),t_=BigInt(10),kN=BigInt(20),NN=BigInt(40),r_=BigInt(80);function n_(t){let e=Wd,n=t*t%e*t%e,i=ze(n,qw,e)*n%e,o=ze(i,ON,e)*t%e,s=ze(o,DN,e)*o%e,c=ze(s,t_,e)*s%e,a=ze(c,kN,e)*c%e,u=ze(a,NN,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 CN(t,e){let r=Wd,n=Ie(e*e*e,r),i=Ie(n*n*e,r),o=n_(t*i).pow_p_5_8,s=Ie(t*n*o,r),c=Ie(e*s*s,r),a=s,u=Ie(s*e_,r),d=c===t,f=c===Ie(-t,r),h=c===Ie(-t*e_,r);return d&&(s=a),(f||h)&&(s=u),$T(s,r)&&(s=Ie(-s,r)),{isValid:d||f,value:s}}var cn=Ha(Wd,void 0,!0),Gd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:cn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Hw,randomBytes:$d,adjustScalarBytes:i_,uvRatio:CN},Xo=fp(Gd);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 VG=fp({...Gd,domain:o_}),qG=fp({...Gd,domain:o_,prehash:Hw}),pc=QT({P:Wd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Wd,{pow_p_5_8:r,b2:n}=n_(t);return Ie(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:i_,randomBytes:$d});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=Gd.hash(t.subarray(0,32));return Gd.adjustScalarBytes(e).subarray(0,32)}var LN=(cn.ORDER+BigInt(3))/BigInt(8),FG=cn.pow(qw,LN),jG=cn.sqrt(cn.neg(cn.ONE)),WG=(cn.ORDER-BigInt(5))/BigInt(8),GG=BigInt(486662);var zG=HT(cn,cn.neg(BigInt(486664)));var YG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),JG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ZG=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),XG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var QG=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())})},PN=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},It=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=PN(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 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 si{computePublicKey(e){return zd(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 It.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 It.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return zd(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 It.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(!ai(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield It.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 It.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:Fd,names:["ES256K","secp256k1"]},secp256r1:{implementation:Fd,names:["ES256","secp256r1"]},"SHA-256":{implementation:Zh,names:["SHA-256"]}},er=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 IT(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())})},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},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=MN(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=Jt.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}=Jt.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())})},wr=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 er}){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+/",$N=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Jd=0;Jd<p_.length;Jd++)$N[p_.charCodeAt(Jd)]=Jd;var Jd;var HN=new TextDecoder,Xw=(t,e)=>e?new TextDecoder(e).decode(t):HN.decode(t),VN=new TextEncoder,un=t=>VN.encode(t);var y_=typeof window<"u"?window:self,g_=y_.crypto||y_.msCrypto||{},QY=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 Be(t,e,r){let n=[],i=null;return Be._encode(n,t),i=h_(n),Be.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Be.bytes=-1;Be._floatConversionDetected=!1;Be._encode=function(t,e){if(e!=null)switch(pp(e)){case"object":Be.dict(t,e);break;case"map":Be.dictMap(t,e);break;case"array":Be.list(t,e);break;case"set":Be.listSet(t,e);break;case"string":Be.string(t,e);break;case"number":Be.number(t,e);break;case"boolean":Be.number(t,e);break;case"arraybufferview":Be.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Be.buffer(t,new Uint8Array(e));break}};var yp=new Uint8Array([101]),m_=new Uint8Array([100]),w_=new Uint8Array([108]);Be.buffer=function(t,e){t.push(un(e.length+":"),e)};Be.string=function(t,e){t.push(un(un(e).byteLength+":"+e))};Be.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&&!Be._floatConversionDetected&&(Be._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+o+'"'),console.trace())};Be.dict=function(t,e){t.push(m_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Be.string(t,n),Be._encode(t,e[n]));t.push(yp)};Be.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)?Be._encode(t,n):Be.string(t,String(n)),Be._encode(t,e.get(n)));t.push(yp)};Be.list=function(t,e){let r=0,n=e.length;for(t.push(w_);r<n;r++)e[r]!=null&&Be._encode(t,e[r]);t.push(yp)};Be.listSet=function(t,e){t.push(w_);for(let r of e)r!=null&&Be._encode(t,r);t.push(yp)};var b_=Be;l();var qN=105,FN=58,jN=100,WN=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 jN:return de.dictionary();case WN:return de.list();case qN: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(FN),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 GN(t){let e=2;for(let r of t)e+=gp(r);return e}function zN(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 YN(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 JN(t){let e=un(t).byteLength;return ja(e)+1+e}function ZN(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 ZN(t);case"string":return JN(t);case"array":case"set":return GN(t);case"number":return 1+ja(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return YN(t);case"map":return zN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var eb=gp;var XN=eb,tb={encode:b_,decode:E_,byteLength:eb,encodingLength:XN};l();l();var QN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var eC=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var On={name:"v4",size:4,isFormat:t=>QN.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},no={name:"v6",size:16,isFormat:t=>t.length>0&&eC.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 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 __(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 I_(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 B_(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 Xd={},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,Xd[c]=s,Xd[`${r}${i}`]=s,Xd[`${e}${o}`]=s,Xd[`${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=Xd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var aC=Math.pow(2,24),uC=Math.pow(2,16),dC=Math.pow(2,8),ui=(t,e)=>t[e]*aC+t[e+1]*uC+t[e+2]*dC+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 br(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:fC(t,e,r,n,i)}function fC(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 hC=0,D_=32768,ab=32768,pC=~ab,N_=32768,yC=~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_:hC;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:I_(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),br(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,br(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 br(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 Ip=$e({encode(t,e,r){e||(e=new Uint8Array(Ip.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),Ip.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,Ip.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}),Bp=$e({encode(t,e,r){return e||(e=new Uint8Array(Bp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,no.encode(t,e,r),Bp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=no.decode(t,e);return Bp.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,br(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,br(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=B_(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);br(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=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)}}),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,br(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 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,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,br(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=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,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,br(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,br(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,br(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,br(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=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 Bp;case"SRV":return _p;case"HINFO":return Tp;case"CAA":return ts;case"NS":return Ep;case"SOA":return vp;case"MX":return Ip;case"OPT":return rs;case"DNSKEY":return fi;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 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=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=ui(t,e+4),r.class=rb(i&pC),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=Zd(he(t,e)),e+=2,n.class=rb(he(t,e)),e+=2,!!(n.class&N_)&&(n.class&=yC),Qa.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var L_=1024;var qt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(gC(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,dn,e,r),r=of(t.authorities,dn,e,r),r=of(t.additionals,dn,e,r),qt.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,dn,t,e),e=bp(n.authorities,dn,t,e),e=bp(n.additionals,dn,t,e),qt.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)}};qt.encode.bytes=0;qt.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=qt.encode(Rp(t,"query"),e,r),Up.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Up.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Rp(t,"query"))}};Up.encode.bytes=0;Up.decode.bytes=0;var Op={encode:function(t,e,r){return e=qt.encode(Rp(t,"response"),e,r),Op.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Op.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Rp(t,"response"))}};Op.encode.bytes=0;Op.decode.bytes=0;var sf=qt.encode,Dp=qt.decode,gC=qt.encodingLength;function P_(t){let e=sf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),br(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 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 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 Nt=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",mC=0,ns=7200,kp=";",sr=",",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 cr;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(cr||(cr={}));var fb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(fb||(fb={}));var q_={Ed25519:cr.Ed25519,ES256K:cr.secp256k1,ES256:cr.secp256r1,"P-256":cr.secp256r1,secp256k1:cr.secp256k1,secp256r1:cr.secp256r1,X25519:cr.X25519},V_={[cr.Ed25519]:"EdDSA",[cr.secp256k1]:"ES256K",[cr.secp256r1]:"ES256",[cr.X25519]:"ECDH-ES+A256KW"},cf=class t extends fn{static create(){return Nt(this,arguments,void 0,function*({keyManager:e=new er,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 kt.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 wr({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 Nt(this,arguments,void 0,function*({portableDid:r,keyManager:n=new er}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield wr.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 Nt(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 Nt(this,arguments,void 0,function*({did:r,gatewayUri:n=H_}){return yield Np.put({did:r,gatewayUri:n})})}static resolve(e){return Nt(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:H_;try{yield kt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Np.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},lt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},lt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};cf.methodName="dht";var Np=class t{static get(e){return Nt(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=kt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield kt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return Nt(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield kt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:kt.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 Nt(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 Nt(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 Nt(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=kt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(sr);break}case f.startsWith("cnt"):{let h=kt.parseTxtDataToString(d.data);c.controller=h.includes(sr)?h.split(sr):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:E}=kt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),I=cr[Number(p)],A=yield kt.keyConverter(I).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=kt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,E=$_(h,["id","t","se"]),S=y.includes(sr)?y.split(sr):[y],I=Object.fromEntries(Object.entries(E).map(([A,O])=>[A,O.includes(sr)?O.split(sr):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}=kt.parseTxtDataToObject(d.data);a.types=h.split(sr).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(sr).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:E,agm:S}=kt.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 Nt(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 kt.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(sr)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(sr):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 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=cr[M.crv],j=yield kt.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((I,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=I,j=$_(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=kt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:ns,data:Q})});let E=[`v=${mC}`];if(y.length&&E.push(`vm=${y.join(sr)}`),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=fb[I];E.push(`${T}=${O.join(sr)}`)}}),g.length&&E.push(`svc=${g.join(sr)}`),!((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(sr)}`})}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:L_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},kt=class t{static createBep44PutMessage(e){return Nt(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=sf(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 Nt(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield It.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 Nt(this,arguments,void 0,function*({identityKey:r}){let n=yield It.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${cf.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:It,"P-256":{publicKeyToBytes:i=>Nt(this,[i],void 0,function*({publicKey:o}){let s=yield Vt.publicKeyToBytes({publicKey:o});return yield Vt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Vt.bytesToPublicKey,privateKeyToBytes:Vt.privateKeyToBytes,bytesToPrivateKey:Vt.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>Nt(this,[i],void 0,function*({publicKey:o}){let s=yield Dt.publicKeyToBytes({publicKey:o});return yield Dt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Dt.bytesToPublicKey,privateKeyToBytes:Dt.privateKeyToBytes,bytesToPrivateKey:Dt.bytesToPrivateKey},X25519:Fa}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return Nt(this,arguments,void 0,function*({bep44Message:r}){let n=yield It.bytesToPublicKey({publicKeyBytes:r.k}),i=tb.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield It.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 Nt(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 It.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 QJ=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)}},wC=({name:t,prefix:e,encode:r,decode:n})=>new gb(t,e,r,n);var bC=(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},xC=(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})=>wC({prefix:e,name:t,encode(i){return xC(i,n,r)},decode(i){return bC(i,n,r,t)}});var dZ=af({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fZ=af({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uf=af({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lZ=af({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xr=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 tI=Pn(W_(),1);l();l();var mb;(function(t){t.Public="public",t.Private="private"})(mb||(mb={}));var Kr=mb;var Rt=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(!xr.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 ar=df;l();var Y_=Pn(z_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=Y_.default(r);return xr.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 EC=X_,J_=128,vC=127,SC=~vC,AC=Math.pow(2,31);function X_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=AC;)e[r++]=t&255|J_,t/=128;for(;t&SC;)e[r++]=t&255|J_,t>>>=7;return e[r]=t|0,X_.bytes=r-n+1,e}var TC=wb,_C=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>=_C);return wb.bytes=o-n,r}var IC=Math.pow(2,7),BC=Math.pow(2,14),RC=Math.pow(2,21),UC=Math.pow(2,28),OC=Math.pow(2,35),DC=Math.pow(2,42),kC=Math.pow(2,49),NC=Math.pow(2,56),CC=Math.pow(2,63),LC=function(t){return t<IC?1:t<BC?2:t<RC?3:t<UC?4:t<OC?5:t<DC?6:t<kC?7:t<NC?8:t<CC?9:10},PC={encode:EC,decode:TC,encodingLength:LC},MC=PC,ff=MC;var bb=(t,e=0)=>[ff.decode(t,e),ff.decode.bytes],xb=(t,e,r=0)=>(ff.encode(t,e,r),e),Eb=t=>ff.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 eI=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pp=Ab({name:"sha2-256",code:18,encode:eI("SHA-256")}),WZ=Ab({name:"sha2-512",code:19,encode:eI("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())})},Ct=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 xr.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=xr.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=ar.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 hf=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;Rt.validateEs256kOperationKey(r,Kr.Public),Rt.validateEs256kOperationKey(n,Kr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=ar.hashAlgorithmInMultihashCode,c=[{action:yc.Replace,document:e.document}],a={updateCommitment:yield Ct.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Ct.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Ct.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),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public);let r=ar.hashAlgorithmInMultihashCode,n=yield Ct.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),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextRecoveryPublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=ar.hashAlgorithmInMultihashCode,n=yield Ct.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:yc.Replace,document:e.document}],o=yield Ct.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Ct.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Ct.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),Rt.validateEs256kOperationKey(e.updatePublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)Rt.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)Rt.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=ar.hashAlgorithmInMultihashCode,a=yield Ct.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Ct.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Ct.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){Ct.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(Rt.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),Rt.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){Rt.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"&&tI.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>ar.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${ar.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Pe(Ye.DeltaExceedsMaximumSize,n)}}};var rI=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 rI(this,void 0,void 0,function*(){let r=yield is.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;ar.network===void 0||ar.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${ar.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Dn.canonicalizeAsBytes(o),c=xr.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return rI(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Ct.hash(r,ar.hashAlgorithmInMultihashCode);return xr.encode(n)})}};l();l();var nI;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(nI||(nI={}));l();var iI;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(iI||(iI={}));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 HC={Ed25519:li.Ed25519,ES256K:li.secp256k1,ES256:li.secp256r1,"P-256":li.secp256r1,secp256k1:li.secp256k1,secp256r1:li.secp256r1},oI="https://ion.tbd.engineering",Ib=class t extends fn{static create(){return os(this,arguments,void 0,function*({keyManager:e=new er,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in HC)))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: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 wr({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 er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield wr.import({portableDid:r,keyManager:n})})}static publish(e){return os(this,arguments,void 0,function*({did:r,gatewayUri:n=oI}){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({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:oI;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({},lt),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({},lt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};Ib.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 fn{static create(){return Kp(this,arguments,void 0,function*({keyManager:e=new er,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 wr({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 er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield wr.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({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},lt),{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({},lt),{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 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"},VC={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 er,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 Er.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new wr({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 er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield wr.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({},lt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},lt),{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=Er.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 Er.multicodecToJwk({code:u});c.publicKeyJwk=yield Er.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=Er.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 Dt.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield It.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 Er.multicodecToJwk({code:u});c.publicKeyJwk=yield Er.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 Er.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield It.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield Er.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 Er=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:Jt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Vt.compressPublicKey,secp256k1:Dt.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:It,"P-256":Vt,secp256k1:Dt,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?Jt.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 VC))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})})}};Er.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"};Er.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};Er.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 qC=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 qC(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},lt),{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({},lt),{didDocument:c})}catch{return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"notFound"}})}})}};Ob.methodName="web";l();var YC=Pn(cI(),1),JC=Pn(sm(),1);l();l();var ot=class t{static absoluteDidUrl(e,r){if(typeof e=="string"&&e.length!==0)return e.startsWith("#")?`${r}${e}`:e}static relationshipMethodId(e,r){let n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.id:e;return t.absoluteDidUrl(n,r)}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 aI(t,e,r){return t&e^~t&r}function uI(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 ZC=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+aI(c,a,u)+ZC[f]+ss[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+uI(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 ur=BigInt(0),tr=BigInt(1),wc=BigInt(2),lI=BigInt(3),hI=BigInt(4),pI=BigInt(5),XC=BigInt(7),yI=BigInt(8),QC=BigInt(9),gI=BigInt(16);function Nn(t,e){let r=t%e;return r>=ur?r:e+r}function $r(t,e,r){let n=t;for(;e-- >ur;)n*=n,n%=r;return n}function dI(t,e){if(t===ur)throw new Error("invert: expected non-zero number");if(e<=ur)throw new Error("invert: expected positive modulus, got "+e);let r=Nn(t,e),n=e,i=ur,o=tr,s=tr,c=ur;for(;r!==ur;){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!==tr)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 mI(t,e){let r=(t.ORDER+tr)/hI,n=t.pow(e,r);return Cb(t,n,e),n}function eL(t,e){let r=(t.ORDER-pI)/yI,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 tL(t){let e=iu(t),r=wI(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+XC)/gI;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 wI(t){if(t<lI)throw new Error("sqrt is not defined for small field");let e=t-tr,r=0;for(;e%wc===ur;)e/=wc,r++;let n=wc,i=iu(t);for(;fI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return mI;let o=i.pow(n,e),s=(e+tr)/wc;return function(a,u){if(a.is0(u))return u;if(fI(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=tr<<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 rL(t){return t%hI===lI?mI:t%yI===pI?eL:t%gI===QC?tL(t):wI(t)}var nL=["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=nL.reduce((n,i)=>(n[i]="function",n),e);return Qu(t,r),t}function iL(t,e,r){if(r<ur)throw new Error("invalid exponent, negatives unsupported");if(r===ur)return t.ONE;if(r===tr)return e;let n=t.ONE,i=e;for(;r>ur;)r&tr&&(n=t.mul(n,i)),i=t.sqr(i),r>>=tr;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 fI(t,e){let r=(t.ORDER-tr)/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 oL(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=ur;ONE=tr;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ur)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}=oL(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 ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&tr)===tr}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 iL(this,e,r)}div(e,r){return Nn(e*dI(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 dI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=rL(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 bI(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=bI(t);return e+Math.ceil(e/2)}function Fp(t,e,r=!1){Se(t);let n=t.length,i=bI(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-tr)+tr;return r?W0(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 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 SI(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){SI(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 xI(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,AI=new WeakMap;function $b(t){return AI.get(t)||1}function EI(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}=xI(n,c,s);n=a,d?o=o.add(pf(h,r[p])):i=i.add(pf(f,r[u]))}return EI(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}=xI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return EI(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){SI(r,this.bits),AI.set(e,r),Kb.delete(e)}hasCache(e){return $b(e)!==1}};function TI(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 vI(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 _I(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=vI(e.p,r.Fp,n),o=vI(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 II=(t,e)=>(t+(t>=0?e:-e)/BI)/e;function sL(t,e,r){let[[n,i],[o,s]]=e,c=II(s*t,r),a=II(-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(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 Ju(r.lowS,"lowS"),Ju(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=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),BI=BigInt(2),zp=BigInt(3),cL=BigInt(4);function RI(t,e={}){let r=_I("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=OI(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 hr(UI(N),L)}else return hr(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),cL),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 sL(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),_=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=>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}=TI($,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 UI(t){return Uint8Array.of(t?2:3)}function OI(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function aL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(OI(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(!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 DI(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)=>Vb(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=aL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*BI<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){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(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(hr(UI((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"?(I(),hr(Uint8Array.of(this.assertRecovery()),N,R)):hr(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 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=hr(...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),!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}=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")},uL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},dL=BigInt(0),Wb=BigInt(2);function fL(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,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,Wb,e);if(!Yp.eql(Yp.sqr(M),t))throw new Error("Cannot find square root");return M}var Yp=iu(Zp.p,{sqrt:fL}),xc=RI(Zp,{Fp:Yp,endo:uL}),ln=DI(xc,Vp),kI={};function Jp(t,...e){let r=kI[t];if(r===void 0){let n=Vp(Fv(t));r=hr(n,n),kI[t]=r}return Vp(hr(r,...e))}var zb=t=>t.toBytes(!0).slice(1),Yb=t=>t%Wb===dL;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 CI(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 yf=Oo;function LI(...t){return xc.Fn.create(yf(Jp("BIP0340/challenge",...t)))}function NI(t){return Gb(t).bytes}function lL(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^yf(Jp("BIP0340/aux",c))),u=Jp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Gb(u),h=LI(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!PI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function PI(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=CI(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=LI(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,NI),getPublicKey:NI,sign:lL,verify:PI,Point:xc,utils:{randomSecretKey:r,taggedHash:Jp,lift_x:CI,pointToBytes:zb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function hL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function KI(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 $I(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Zb(t){if(!Array.isArray(t))throw new Error("array expected")}function HI(t,e){if(!KI(!0,e))throw new Error(`${t}: array of strings expected`)}function pL(t,e){if(!KI(!1,e))throw new Error(`${t}: array of numbers expected`)}function yL(...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 gL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;HI("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 mL(t=""){return Jb("join",t),{encode:e=>(HI("join.decode",e),e.join(t)),decode:e=>(Jb("join.decode",e),e.split(t))}}function MI(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($I(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 wL(t){$I(t);let e=2**8;return{encode:r=>{if(!hL(r))throw new Error("radix.encode input should be Uint8Array");return MI(Array.from(r),e,t)},decode:r=>(pL("radix.decode",r),Uint8Array.from(MI(r,t,e)))}}var bL=t=>yL(wL(58),gL(t),mL("")),cu=bL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var VI=new Uint8Array([231,1]),pt=class t{#e;#t={prefix:VI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Tr(e);if(!r||r.length!==33)throw new Is("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!ln.utils.isValidPublicKey(r))throw new Is("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 Is("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 Lt(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(VI);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 Is(`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 qI=new Uint8Array([129,38]),xL=Lt(ke(qI)),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 Lt(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(qI);return r.push(...e),"z"+cu.encode(Uint8Array.from(r))}equals(e){return ia(this.bytes,e.bytes)}computePublicKey(){return new pt(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(Lt(ke(n))!==xL)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 pt?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new pt(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:pt.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 Lt(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 dr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in Bo))throw new wt('Expected "idType" to be "KEY" or "EXTERNAL"',Pt,{idType:n});if(i!==1)throw new wt('Expected "version" to be 1',Pt,{version:i});if(typeof o!="string")throw new wt('Expected "network" to be a known network name',Pt,{network:o});let s=Wu[o];if(s===void 0)throw new wt('Invalid "network" name',Pt,{network:o});if(n==="KEY")try{new pt(e)}catch{throw new wt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Pt,{genesisBytes:e})}else if(e.length!==32)throw new wt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Pt,{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 wt(`Invalid did: ${e}`,Pt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new wt(`Invalid did: ${e}`,Pt,{identifier:e});if(i!=="btcr2")throw new wt(`Invalid did method: ${i}`,xl,{identifier:e});if(!o)throw new wt(`Invalid method-specific id: ${e}`,Pt,{identifier:e});let{prefix:s,bytes:c}=Fc.decodeToBytes(o);if(!["x","k"].includes(s))throw new wt(`Invalid hrp: ${s}`,Pt,{identifier:e});if(!c||c.length<1)throw new wt(`Failed to decode id: ${o}`,Pt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new wt(`Invalid btcr2_version (expected 0): ${u}`,Pt,{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 wt(`Invalid network: ${f}`,Pt,{identifier:e});let g=c.slice(1);if(a==="KEY")try{new pt(g)}catch{throw new wt(`Invalid genesisBytes: ${g}`,Pt,{identifier:e})}else if(g.length!==32)throw new wt(`Invalid genesisBytes: ${g}`,Pt,{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 wt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Pt,{did:e,idType:r});return new pt(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!(!ot.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 Yt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=dr.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 Yt("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 zt("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 Yt("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 EL=/^6a20([0-9a-f]{64})$/i;function Xb(t){if(!t)return null;let e=EL.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 ere=new Uint8Array(0);function FI(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 vL(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 SL=vL,AL=SL,jI=AL;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 WI(this,e)}},rx=class{decoders;constructor(e){this.decoders=e}or(e){return WI(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 WI(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 TL({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}=jI(r,t);return TL({prefix:e,name:t,encode:n,decode:o=>FI(i(o))})}var gf=ix({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dre=ix({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function GI(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=GI(i),d=GI(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=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 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 nr(e)}generateHash(e,r){let n=ke(ws(e)),i=ke(ws(r)),o=dt(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 nr(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 pt(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 pt(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 zI=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Ec="Multikey",vc="zQ3s",qr="did:btcr2:_",_L="",YI=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function JI(t){if(!ot.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")?Bo.KEY:Bo.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===Bo.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:zI.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return dr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(JI)}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"||ot.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,YI,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 pt(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 Io(nr(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:Wn(e)},o=ea.apply(e,r);if(o.id!==e.id)throw new St(`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 St("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 St(`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 St(`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=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new St(`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:d});let f={"@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:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,f)}static async announce(e,r,n,i,o,s){return Cs.establish(e,r).broadcastSignal(n,i,o,s)}#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,did:this.#t.id}]};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 St(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,De,{phase:this.#e.phase});if(!r)throw new St("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 St(`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 St(`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 St(`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 wf=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 dr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=dr.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}){let s=ot.relationshipMethodId(i,e.id);if(!(s!==void 0&&e.capabilityInvocation?.some(f=>ot.relationshipMethodId(f,e.id)===s)))throw new St("Invalid verificationMethodId: not authorized for capabilityInvocation",Oe,e);let a=this.getSigningMethod(e,i);if(!a)throw new St("Invalid verificationMethod: not found in source document",Oe,{sourceDocument:e,verificationMethodId:i});if(a.type!==Ec)throw new St(`Invalid verificationMethod: verificationMethod.type must be "${Ec}"`,Oe,a);if(!a.publicKeyMultibase?.startsWith(vc))throw new St(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${vc}"`,Oe,a);let u=ot.absoluteDidUrl(o,e.id),d=e.service.filter(f=>u!==void 0&&ot.absoluteDidUrl(f.id,e.id)===u).filter(f=>!!f).shift();if(!d)throw new St("No beacon service found for provided beaconId",De,{sourceDocument:e,beaconId:o});return new mf({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:a,beaconService:d})}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=ot.absoluteDidUrl(r,e.id)??ot.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:e.verificationMethod?.find(s=>ot.absoluteDidUrl(s.id,e.id)===i);if(!(o&&o.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o}};function bf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function IL(t){return bf(t)&&Object.values(t).every(e=>typeof e=="string")}function BL(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 RL(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=dr.encode(r,e),{multibase:i}=new pt(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 Ve("Initial document mismatch: genesisBytes !== genesisDocumentHash",Oe,{genesisBytes:Qr(e.genesisBytes,"hex"),genesisDocumentHash:Qr(n,"hex")});let i=dr.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(Bs(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=Bs(d.sourceHash,"base64urlnopad");if(!Tu(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(!Tu(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=ot.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=ot.relationshipMethodId(c,e.id);if(!(a!==void 0&&e.capabilityInvocation?.some(A=>ot.relationshipMethodId(A,e.id)===a)))throw new Ve("Invalid update: verificationMethod is not authorized for capabilityInvocation",De,{verificationMethodId:c,capabilityInvocation:e.capabilityInvocation});let d=wf.getSigningMethod(e,c),f=as.fromVerificationMethod(d),h=new uu(f),p=nr(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),I=Bs(r.targetHash);if(!Tu(I,S))throw new Ve("Invalid update: update.targetHash !== currentDocumentHash",De,{updateTargetHash:I,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,this.#i.id).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(!bf(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(!BL(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(!RL(r))throw new Ve("Provided data for NeedSMTProof is not an SMT proof.",De,{kind:e.kind});let n=Qr(Bs(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 ZI(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=ot.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>ot.absoluteDidUrl(i.id,t.id)===r):e;if(!n)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(n).publicKey}function UL(t,e){try{let r=dr.decode(t);if(r.idType==="KEY")return new pt(r.genesisBytes);if(e?.genesisDocument){let n=fo.external(r,e.genesisDocument);return ZI(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 vB(OL);})();
|
|
1
|
+
"use strict";var BTCR2=(()=>{var bB=Object.create;var Uf=Object.defineProperty;var xB=Object.getOwnPropertyDescriptor;var EB=Object.getOwnPropertyNames;var vB=Object.getPrototypeOf,SB=Object.prototype.hasOwnProperty;var AB=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),vu=(t,e)=>{for(var r in e)Uf(t,r,{get:e[r],enumerable:!0})},yx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of EB(e))!SB.call(t,i)&&i!==r&&Uf(t,i,{get:()=>e[i],enumerable:!(n=xB(e,i))||n.enumerable});return t};var Mn=(t,e,r)=>(r=t!=null?bB(vB(t)):{},yx(e||!t||!t.__esModule?Uf(r,"default",{value:t,enumerable:!0}):r,t)),TB=t=>yx(Uf({},"__esModule",{value:!0}),t);var wx=oe(Of=>{"use strict";l();Of.byteLength=IB;Of.toByteArray=RB;Of.fromByteArray=DB;var Kn=[],Yr=[],_B=typeof Uint8Array<"u"?Uint8Array:Array,sy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ys=0,gx=sy.length;ys<gx;++ys)Kn[ys]=sy[ys],Yr[sy.charCodeAt(ys)]=ys;var ys,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 IB(t){var e=mx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function BB(t,e,r){return(e+r)*3/4-r}function RB(t){var e,r=mx(t),n=r[0],i=r[1],o=new _B(BB(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 UB(t){return Kn[t>>18&63]+Kn[t>>12&63]+Kn[t>>6&63]+Kn[t&63]}function OB(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(UB(n));return i.join("")}function DB(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(OB(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push(Kn[e>>2]+Kn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Kn[e>>10]+Kn[e>>4&63]+Kn[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 Tr=oe(Nc=>{"use strict";l();var ay=wx(),kc=bx(),xx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nc.Buffer=F;Nc.SlowBuffer=MB;Nc.INSPECT_MAX_BYTES=50;var Df=2147483647;Nc.kMaxLength=Df;F.TYPED_ARRAY_SUPPORT=kB();!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 kB(){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>Df)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 CB(t,e);if(ArrayBuffer.isView(t))return LB(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($n(t,ArrayBuffer)||t&&$n(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&($n(t,SharedArrayBuffer)||t&&$n(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=PB(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 NB(t,e,r){return Ax(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 NB(t,e,r)};function ly(t){return Ax(t),wi(t<0?0:hy(t)|0)}F.allocUnsafe=function(t){return ly(t)};F.allocUnsafeSlow=function(t){return ly(t)};function CB(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=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 LB(t){if($n(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 PB(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>=Df)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Df.toString(16)+" bytes");return t|0}function MB(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($n(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),$n(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($n(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)||$n(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 KB(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 YB(this,e,r);case"utf8":case"utf-8":return Ix(this,e,r);case"ascii":return GB(this,e,r);case"latin1":case"binary":return zB(this,e,r);case"base64":return jB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return JB(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function gs(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)gs(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)gs(this,r,r+3),gs(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)gs(this,r,r+7),gs(this,r+1,r+6),gs(this,r+2,r+5),gs(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?Ix(this,0,e):KB.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=Nc.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($n(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 $B(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 HB(t,e,r,n){return kf(fy(e,t.length-r),t,r,n)}function VB(t,e,r,n){return kf(QB(e),t,r,n)}function qB(t,e,r,n){return kf(Ox(e),t,r,n)}function FB(t,e,r,n){return kf(e8(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 $B(this,e,r,n);case"utf8":case"utf-8":return HB(this,e,r,n);case"ascii":case"latin1":case"binary":return VB(this,e,r,n);case"base64":return qB(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return FB(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 jB(t,e,r){return e===0&&r===t.length?ay.fromByteArray(t):ay.fromByteArray(t.slice(e,r))}function Ix(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 WB(n)}var vx=4096;function WB(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 GB(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 zB(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 YB(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+=t8[t[o]];return i}function JB(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 Ut(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||Ut(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||Ut(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||Ut(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(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||Ut(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||Ut(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||Ut(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||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(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||Ut(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||Ut(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||Ut(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||Ut(e,4,this.length),kc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),kc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),kc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),kc.read(this,e,!1,52,8)};function lr(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;lr(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;lr(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||lr(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||lr(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||lr(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||lr(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||lr(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);lr(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);lr(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||lr(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||lr(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||lr(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||lr(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||lr(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 Rx(t,e,r,n,i){return e=+e,r=r>>>0,i||Bx(t,e,r,4,34028234663852886e22,-34028234663852886e22),kc.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||Bx(t,e,r,8,17976931348623157e292,-17976931348623157e292),kc.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 ZB=/[^+/0-9A-Za-z-_]/g;function XB(t){if(t=t.split("=")[0],t=t.trim().replace(ZB,""),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 QB(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function e8(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(XB(t))}function kf(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 $n(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 t8=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((XL,Cx)=>{l();var dt=Cx.exports={},Hn,Vn;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"?Hn=setTimeout:Hn=yy}catch{Hn=yy}try{typeof clearTimeout=="function"?Vn=clearTimeout:Vn=gy}catch{Vn=gy}})();function Dx(t){if(Hn===setTimeout)return setTimeout(t,0);if((Hn===yy||!Hn)&&setTimeout)return Hn=setTimeout,setTimeout(t,0);try{return Hn(t,0)}catch{try{return Hn.call(null,t,0)}catch{return Hn.call(this,t,0)}}}function r8(t){if(Vn===clearTimeout)return clearTimeout(t);if((Vn===gy||!Vn)&&clearTimeout)return Vn=clearTimeout,clearTimeout(t);try{return Vn(t)}catch{try{return Vn.call(null,t)}catch{return Vn.call(this,t)}}}var bi=[],Cc=!1,ms,Nf=-1;function n8(){!Cc||!ms||(Cc=!1,ms.length?bi=ms.concat(bi):Nf=-1,bi.length&&kx())}function kx(){if(!Cc){var t=Dx(n8);Cc=!0;for(var e=bi.length;e;){for(ms=bi,bi=[];++Nf<e;)ms&&ms[Nf].run();Nf=-1,e=bi.length}ms=null,Cc=!1,r8(t)}}dt.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 Nx(t,e)),bi.length===1&&!Cc&&Dx(kx)};function Nx(t,e){this.fun=t,this.array=e}Nx.prototype.run=function(){this.fun.apply(null,this.array)};dt.title="browser";dt.browser=!0;dt.env={};dt.argv=[];dt.version="";dt.versions={};function xi(){}dt.on=xi;dt.addListener=xi;dt.once=xi;dt.off=xi;dt.removeListener=xi;dt.removeAllListeners=xi;dt.emit=xi;dt.prependListener=xi;dt.prependOnceListener=xi;dt.listeners=function(t){return[]};dt.binding=function(t){throw new Error("process.binding is not supported")};dt.cwd=function(){return"/"};dt.chdir=function(t){throw new Error("process.chdir is not supported")};dt.umask=function(){return 0}});var b,w,eP,l=AB(()=>{b=Mn(Tr()),w=Mn(Ei()),eP=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 i1=oe((kH,n1)=>{l();var l6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Vl=()=>l6.now(),h6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),eg=t=>t===1/0||h6(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-Vl());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(Vl()+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-Vl())):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(Vl());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()}};n1.exports=tg});var E1=oe(x1=>{"use strict";l();x1.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 vn=oe((nq,v1)=>{"use strict";l();v1.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((oq,S1)=>{"use strict";l();var yg=null;S1.exports=function(){return yg===null&&(yg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),yg}});var bg=oe(A1=>{"use strict";l();var mg=vn(),W6=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"||!W6.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"})}};A1.Encoding=wg});var Sg=oe(Fl=>{"use strict";l();var{Buffer:Eg}=Tr()||{},{Encoding:vg}=bg(),G6=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}=G6();return new ud({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Fl.BufferFormat=ad;Fl.ViewFormat=ud;Fl.UTF8Format=xg});var B1=oe(Vs=>{"use strict";l();var{Buffer:Zt}=Tr()||{Buffer:{isBuffer:()=>!1}},{textEncoder:_1,textDecoder:T1}=gg()(),{BufferFormat:dd,ViewFormat:Ag,UTF8Format:I1}=Sg(),jl=t=>t;Vs.utf8=new I1({encode:function(t){return Zt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?T1.decode(t):String(t)},decode:jl,name:"utf8",createViewTranscoder(){return new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:_1.encode(t)},decode:function(t){return T1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new dd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Vs.json=new I1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Vs.buffer=new dd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:jl,name:"buffer",createViewTranscoder(){return new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:Zt.from(String(t),"utf8")},decode:function(t){return Zt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Vs.view=new Ag({encode:function(t){return ArrayBuffer.isView(t)?t:_1.encode(t)},decode:jl,name:"view",createBufferTranscoder(){return new dd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:jl,name:`${this.name}+buffer`})}});Vs.hex=new dd({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Vs.base64=new dd({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var O1=oe(U1=>{"use strict";l();var R1=vn(),Gl=B1(),{Encoding:z6}=bg(),{BufferFormat:Y6,ViewFormat:J6,UTF8Format:Z6}=Sg(),fd=Symbol("formats"),Wl=Symbol("encodings"),X6=new Set(["buffer","view","utf8"]),Tg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>X6.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[Wl]=new Map,this[fd]=new Set(e);for(let r in Gl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Wl].values()))}encoding(e){let r=this[Wl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=rU[e],!r)throw new R1(`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=Q6(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 R1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Wl].set(o,r)}return r}};U1.Transcoder=Tg;function Q6(t){if(t instanceof z6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${nU++}`;switch(eU(t)){case"view":return new J6({...t,name:r});case"utf8":return new Z6({...t,name:r});case"buffer":return new Y6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function eU(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 tU={binary:Gl.buffer,"utf-8":Gl.utf8},rU={...Gl,...tU},nU=0});var pa=oe((yq,_g)=>{"use strict";l();var ha=typeof Reflect=="object"?Reflect:null,D1=ha&&typeof ha.apply=="function"?ha.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},zl;ha&&typeof ha.ownKeys=="function"?zl=ha.ownKeys:Object.getOwnPropertySymbols?zl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zl=function(e){return Object.getOwnPropertyNames(e)};function iU(t){console&&console.warn&&console.warn(t)}var N1=Number.isNaN||function(e){return e!==e};function Pe(){Pe.init.call(this)}_g.exports=Pe;_g.exports.once=aU;Pe.EventEmitter=Pe;Pe.prototype._events=void 0;Pe.prototype._eventsCount=0;Pe.prototype._maxListeners=void 0;var k1=10;function Yl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Pe,"defaultMaxListeners",{enumerable:!0,get:function(){return k1},set:function(t){if(typeof t!="number"||t<0||N1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");k1=t}});Pe.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};Pe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||N1(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 C1(t){return t._maxListeners===void 0?Pe.defaultMaxListeners:t._maxListeners}Pe.prototype.getMaxListeners=function(){return C1(this)};Pe.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")D1(a,this,r);else for(var u=a.length,d=$1(a,u),n=0;n<u;++n)D1(d[n],this,r);return!0};function L1(t,e,r,n){var i,o,s;if(Yl(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=C1(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,iU(c)}return t}Pe.prototype.addListener=function(e,r){return L1(this,e,r,!1)};Pe.prototype.on=Pe.prototype.addListener;Pe.prototype.prependListener=function(e,r){return L1(this,e,r,!0)};function oU(){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 P1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=oU.bind(n);return i.listener=r,n.wrapFn=i,i}Pe.prototype.once=function(e,r){return Yl(r),this.on(e,P1(this,e,r)),this};Pe.prototype.prependOnceListener=function(e,r){return Yl(r),this.prependListener(e,P1(this,e,r)),this};Pe.prototype.removeListener=function(e,r){var n,i,o,s,c;if(Yl(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():sU(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Pe.prototype.off=Pe.prototype.removeListener;Pe.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 M1(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?cU(i):$1(i,i.length)}Pe.prototype.listeners=function(e){return M1(this,e,!0)};Pe.prototype.rawListeners=function(e){return M1(this,e,!1)};Pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):K1.call(t,e)};Pe.prototype.listenerCount=K1;function K1(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}Pe.prototype.eventNames=function(){return this._eventsCount>0?zl(this._events):[]};function $1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function sU(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function cU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function aU(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))}H1(t,e,o,{once:!0}),e!=="error"&&uU(t,i,{once:!0})})}function uU(t,e,r){typeof t.on=="function"&&H1(t,"error",e,r)}function H1(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 q1=oe((mq,V1)=>{l();V1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var ld=oe(Ig=>{"use strict";l();var F1=q1();Ig.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};Ig.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){F1(()=>e(null,r))}).catch(function(r){F1(()=>e(r))})}});var Jl=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 $o=oe(eh=>{"use strict";l();var{fromCallback:Rg}=ld(),kr=vn(),{getOptions:Ug,getCallback:j1}=Jl(),qs=Symbol("promise"),ya=Symbol("callback"),Xn=Symbol("working"),Fs=Symbol("handleOne"),$i=Symbol("handleMany"),Og=Symbol("autoClose"),Mo=Symbol("finishWork"),Qn=Symbol("returnMany"),Co=Symbol("closing"),hd=Symbol("handleClose"),Zl=Symbol("closed"),pd=Symbol("closeCallbacks"),Po=Symbol("keyEncoding"),js=Symbol("valueEncoding"),Dg=Symbol("abortOnClose"),Xl=Symbol("legacy"),kg=Symbol("keys"),Ng=Symbol("values"),Lo=Symbol("limit"),tn=Symbol("count"),Ql=Object.freeze({}),dU=()=>{},W1=!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[Zl]=!1,this[pd]=[],this[Xn]=!1,this[Co]=!1,this[Og]=!1,this[ya]=null,this[Fs]=this[Fs].bind(this),this[$i]=this[$i].bind(this),this[hd]=this[hd].bind(this),this[Po]=r[Po],this[js]=r[js],this[Xl]=n,this[Lo]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[tn]=0,this[Dg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[tn]}get limit(){return this[Lo]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[Xl]?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[Co]?this.nextTick(e,new kr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(e,new kr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ya]=e,this[tn]>=this[Lo]?this.nextTick(this[Fs],null):this._next(this[Fs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=j1(r,n),n=Rg(n,qs),r=Ug(r,Ql),Number.isInteger(e)?(this[Co]?this.nextTick(n,new kr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(n,new kr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[Lo]<1/0&&(e=Math.min(e,this[Lo]-this[tn])),this[Xn]=!0,this[ya]=n,e<=0?this.nextTick(this[$i],null,[]):this._nextv(e,r,this[$i])),n[qs]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[qs])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[Xl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[Xl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=j1(e,r),r=Rg(r,qs),e=Ug(e,Ql),this[Co]?this.nextTick(r,new kr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(r,new kr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ya]=r,this[Og]=!0,this[tn]>=this[Lo]?this.nextTick(this[$i],null,[]):this._all(e,this[$i])),r[qs]}_all(e,r){let n=this[tn],i=[],o=()=>{let c=this[Lo]<1/0?Math.min(1e3,this[Lo]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Ql,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Mo](){let e=this[ya];return this[Dg]&&e===null?dU:(this[Xn]=!1,this[ya]=null,this[Co]&&this._close(this[hd]),e)}[Qn](e,r,n){this[Og]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=Ug(r,Ql),!this[Co]){if(this[Xn])throw new kr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Po]),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 kr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=Rg(e,qs),this[Zl]?this.nextTick(e):this[Co]?this[pd].push(e):(this[Co]=!0,this[pd].push(e),this[Xn]?this[Dg]&&this[Mo]()(new kr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[hd])),e[qs]}_close(e){this.nextTick(e)}[hd](){this[Zl]=!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[Zl]||await this.close()}}},ga=class extends yd{constructor(e,r){super(e,r,!0),this[kg]=r.keys!==!1,this[Ng]=r.values!==!1}[Fs](e,r,n){let i=this[Mo]();if(e)return i(e);try{r=this[kg]&&r!==void 0?this[Po].decode(r):void 0,n=this[Ng]&&n!==void 0?this[js].decode(n):void 0}catch(o){return i(new Ko("entry",o))}r===void 0&&n===void 0||this[tn]++,i(null,r,n)}[$i](e,r){let n=this[Mo]();if(e)return this[Qn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[kg]&&o!==void 0?this[Po].decode(o):void 0,i[1]=this[Ng]&&s!==void 0?this[js].decode(s):void 0}}catch(i){return this[Qn](n,new Ko("entries",i))}this[tn]+=r.length,this[Qn](n,null,r)}end(e){return!W1&&typeof console<"u"&&(W1=!0,console.warn(new kr("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)}[Fs](e,r){let n=this[Mo]();if(e)return n(e);try{r=r!==void 0?this[Po].decode(r):void 0}catch(i){return n(new Ko("key",i))}r!==void 0&&this[tn]++,n(null,r)}[$i](e,r){let n=this[Mo]();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[Po].decode(o):void 0}}catch(i){return this[Qn](n,new Ko("keys",i))}this[tn]+=r.length,this[Qn](n,null,r)}},Lg=class extends yd{constructor(e,r){super(e,r,!1)}[Fs](e,r){let n=this[Mo]();if(e)return n(e);try{r=r!==void 0?this[js].decode(r):void 0}catch(i){return n(new Ko("value",i))}r!==void 0&&this[tn]++,n(null,r)}[$i](e,r){let n=this[Mo]();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[js].decode(o):void 0}}catch(i){return this[Qn](n,new Ko("values",i))}this[tn]+=r.length,this[Qn](n,null,r)}},Ko=class extends kr{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(ga.prototype,t.split(" ")[0],{get(){throw new kr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new kr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});ga.keyEncoding=Po;ga.valueEncoding=js;eh.AbstractIterator=ga;eh.AbstractKeyIterator=Cg;eh.AbstractValueIterator=Lg});var G1=oe(Pg=>{"use strict";l();var{AbstractKeyIterator:fU,AbstractValueIterator:lU}=$o(),Ws=Symbol("iterator"),gd=Symbol("callback"),ma=Symbol("handleOne"),Gs=Symbol("handleMany"),md=class extends fU{constructor(e,r){super(e,r),this[Ws]=e.iterator({...r,keys:!0,values:!1}),this[ma]=this[ma].bind(this),this[Gs]=this[Gs].bind(this)}},th=class extends lU{constructor(e,r){super(e,r),this[Ws]=e.iterator({...r,keys:!1,values:!0}),this[ma]=this[ma].bind(this),this[Gs]=this[Gs].bind(this)}};for(let t of[md,th]){let e=t===md,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[gd]=n,this[Ws].next(this[ma])},t.prototype[ma]=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[Ws].nextv(n,i,this[Gs])},t.prototype._all=function(n,i){this[gd]=i,this[Ws].all(n,this[Gs])},t.prototype[Gs]=function(n,i){let o=this[gd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[Ws].seek(n,i)},t.prototype._close=function(n){this[Ws].close(n)}}Pg.DefaultKeyIterator=md;Pg.DefaultValueIterator=th});var z1=oe(ch=>{"use strict";l();var{AbstractIterator:hU,AbstractKeyIterator:pU,AbstractValueIterator:yU}=$o(),Mg=vn(),gr=Symbol("nut"),oh=Symbol("undefer"),sh=Symbol("factory"),rh=class extends hU{constructor(e,r){super(e,r),this[gr]=null,this[sh]=()=>e.iterator(r),this.db.defer(()=>this[oh]())}},nh=class extends pU{constructor(e,r){super(e,r),this[gr]=null,this[sh]=()=>e.keys(r),this.db.defer(()=>this[oh]())}},ih=class extends yU{constructor(e,r){super(e,r),this[gr]=null,this[sh]=()=>e.values(r),this.db.defer(()=>this[oh]())}};for(let t of[rh,nh,ih])t.prototype[oh]=function(){this.db.status==="open"&&(this[gr]=this[sh]())},t.prototype._next=function(e){this[gr]!==null?this[gr].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[gr]!==null?this[gr].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[gr]!==null?this[gr].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[gr]!==null?this[gr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[gr]!==null?this[gr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};ch.DeferredIterator=rh;ch.DeferredKeyIterator=nh;ch.DeferredValueIterator=ih});var $g=oe(J1=>{"use strict";l();var{fromCallback:Y1}=ld(),ah=vn(),{getCallback:gU,getOptions:mU}=Jl(),uh=Symbol("promise"),rn=Symbol("status"),wa=Symbol("operations"),wd=Symbol("finishClose"),ba=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[wa]=[],this[ba]=[],this[rn]="open",this[wd]=this[wd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[wa].length}put(e,r,n){if(this[rn]!=="open")throw new ah("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[wa].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[rn]!=="open")throw new ah("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[wa].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[rn]!=="open")throw new ah("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[wa]=[],this}_clear(){}write(e,r){return r=gU(e,r),r=Y1(r,uh),e=mU(e),this[rn]!=="open"?this.nextTick(r,new ah("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[ba].push(()=>r(n)),n||this.db.emit("batch",this[wa]),this._close(this[wd])})),r[uh]}_write(e,r){}close(e){return e=Y1(e,uh),this[rn]==="closing"?this[ba].push(e):this[rn]==="closed"?this.nextTick(e):(this[ba].push(e),this[rn]!=="writing"&&(this[rn]="closing",this._close(this[wd]))),e[uh]}_close(e){this.nextTick(e)}[wd](){this[rn]="closed",this.db.detachResource(this);let e=this[ba];this[ba]=[];for(let r of e)r()}};J1.AbstractChainedBatch=Kg});var X1=oe(Z1=>{"use strict";l();var{AbstractChainedBatch:wU}=$g(),bU=vn(),xa=Symbol("encoded"),Hg=class extends wU{constructor(e){super(e),this[xa]=[]}_put(e,r,n){this[xa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[xa].push({...r,type:"del",key:e})}_clear(){this[xa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[xa].length===0?this.nextTick(r):this.db._batch(this[xa],e,r):this.nextTick(r,new bU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};Z1.DefaultChainedBatch=Hg});var t2=oe((kq,e2)=>{"use strict";l();var Q1=vn(),xU=Object.prototype.hasOwnProperty,EU=new Set(["lt","lte","gt","gte"]);e2.exports=function(t,e){let r={};for(let n in t)if(xU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new Q1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new Q1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});EU.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((Cq,n2)=>{l();var r2;n2.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(r2||(r2=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var s2=oe((Pq,o2)=>{"use strict";l();var i2=Vg();o2.exports=function(t,...e){e.length===0?i2(t):i2(()=>t(...e))}});var c2=oe(dh=>{"use strict";l();var{AbstractIterator:vU,AbstractKeyIterator:SU,AbstractValueIterator:AU}=$o(),Ea=Symbol("unfix"),Sn=Symbol("iterator"),zs=Symbol("handleOne"),Ho=Symbol("handleMany"),Hi=Symbol("callback"),bd=class extends vU{constructor(e,r,n,i){super(e,r),this[Sn]=n,this[Ea]=i,this[zs]=this[zs].bind(this),this[Ho]=this[Ho].bind(this),this[Hi]=null}[zs](e,r,n){let i=this[Hi];if(e)return i(e);r!==void 0&&(r=this[Ea](r)),i(e,r,n)}[Ho](e,r){let n=this[Hi];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[Ea](o))}n(e,r)}},xd=class extends SU{constructor(e,r,n,i){super(e,r),this[Sn]=n,this[Ea]=i,this[zs]=this[zs].bind(this),this[Ho]=this[Ho].bind(this),this[Hi]=null}[zs](e,r){let n=this[Hi];if(e)return n(e);r!==void 0&&(r=this[Ea](r)),n(e,r)}[Ho](e,r){let n=this[Hi];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[Ea](o))}n(e,r)}},Ed=class extends AU{constructor(e,r,n){super(e,r),this[Sn]=n}};for(let t of[bd,xd])t.prototype._next=function(e){this[Hi]=e,this[Sn].next(this[zs])},t.prototype._nextv=function(e,r,n){this[Hi]=n,this[Sn].nextv(e,r,this[Ho])},t.prototype._all=function(e,r){this[Hi]=r,this[Sn].all(e,this[Ho])};for(let t of[Ed])t.prototype._next=function(e){this[Sn].next(e)},t.prototype._nextv=function(e,r,n){this[Sn].nextv(e,r,n)},t.prototype._all=function(e,r){this[Sn].all(e,r)};for(let t of[bd,xd,Ed])t.prototype._seek=function(e,r){this[Sn].seek(e,r)},t.prototype._close=function(e){this[Sn].close(e)};dh.AbstractSublevelIterator=bd;dh.AbstractSublevelKeyIterator=xd;dh.AbstractSublevelValueIterator=Ed});var f2=oe((Hq,d2)=>{"use strict";l();var qg=vn(),{Buffer:Wg}=Tr()||{},{AbstractSublevelIterator:TU,AbstractSublevelKeyIterator:_U,AbstractSublevelValueIterator:IU}=c2(),Vi=Symbol("prefix"),a2=Symbol("upperBound"),vd=Symbol("prefixRange"),Nr=Symbol("parent"),Fg=Symbol("unfix"),u2=new TextEncoder,BU={separator:"!"};d2.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?BU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=UU(i,s);let u=s.charCodeAt(0)+1,d=n[Nr]||n;if(!u2.encode(i).every(p=>p>u&&p<127))throw new qg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(RU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Nr]=d,this[Vi]=new fh(f),this[a2]=new fh(h),this[Fg]=new Gg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Vi].utf8+n;if(n.byteLength===0)return this[Vi][i];if(i==="view"){let o=this[Vi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Vi].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[Vi][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[a2][i]}get prefix(){return this[Vi].utf8}get db(){return this[Nr]}_open(n,i){this[Nr].open({passive:!0},i)}_put(n,i,o,s){this[Nr].put(n,i,o,s)}_get(n,i,o){this[Nr].get(n,i,o)}_getMany(n,i,o){this[Nr].getMany(n,i,o)}_del(n,i,o){this[Nr].del(n,i,o)}_batch(n,i,o){this[Nr].batch(n,i,o)}_clear(n,i){this[vd](n,n.keyEncoding),this[Nr].clear(n,i)}_iterator(n){this[vd](n,n.keyEncoding);let i=this[Nr].iterator(n),o=this[Fg].get(this[Vi].utf8.length,n.keyEncoding);return new TU(this,n,i,o)}_keys(n){this[vd](n,n.keyEncoding);let i=this[Nr].keys(n),o=this[Fg].get(this[Vi].utf8.length,n.keyEncoding);return new _U(this,n,i,o)}_values(n){this[vd](n,n.keyEncoding);let i=this[Nr].values(n);return new IU(this,n,i)}}return{AbstractSublevel:e}};var RU=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},fh=class{constructor(e){this.utf8=e,this.view=u2.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}},UU=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:OU}=E1(),{Transcoder:DU}=O1(),{EventEmitter:kU}=pa(),{fromCallback:Vo}=ld(),An=vn(),{AbstractIterator:Ys}=$o(),{DefaultKeyIterator:NU,DefaultValueIterator:CU}=G1(),{DeferredIterator:LU,DeferredKeyIterator:PU,DeferredValueIterator:MU}=z1(),{DefaultChainedBatch:l2}=X1(),{getCallback:Js,getOptions:qo}=Jl(),lh=t2(),pe=Symbol("promise"),qi=Symbol("landed"),Zs=Symbol("resources"),zg=Symbol("closeResources"),Sd=Symbol("operations"),Ad=Symbol("undefer"),hh=Symbol("deferOpen"),h2=Symbol("options"),be=Symbol("status"),Xs=Symbol("defaultOptions"),va=Symbol("transcoder"),ph=Symbol("keyEncoding"),Yg=Symbol("valueEncoding"),KU=()=>{},Td=class extends kU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=qo(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Zs]=new Set,this[Sd]=[],this[hh]=!0,this[h2]=s,this[be]="opening",this.supports=OU(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[va]=new DU($U(this)),this[ph]=this[va].encoding(n||"utf8"),this[Yg]=this[va].encoding(i||"utf8");for(let c of this[va].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Xs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[ph].commonName,valueEncoding:this[Yg].commonName}),key:Object.freeze({keyEncoding:this[ph].commonName})},this.nextTick(()=>{this[hh]&&this.open({passive:!1},KU)})}get status(){return this[be]}keyEncoding(e){return this[va].encoding(e??this[ph])}valueEncoding(e){return this[va].encoding(e??this[Yg])}open(e,r){r=Js(e,r),r=Vo(r,pe),e={...this[h2],...qo(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[be]==="closing"||this[be]==="opening"?this.once(qi,i?()=>n(i):n):this[be]!=="open"?r(new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[be]==="opening"?this.once(qi,n):this.nextTick(n):this[be]==="closed"||this[hh]?(this[hh]=!1,this[be]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[be]="closed",this[zg](()=>{this.emit(qi),n(i)}),this[Ad]();return}this[be]="open",this[Ad](),this.emit(qi),this[be]==="open"&&this.emit("open"),this[be]==="open"&&this.emit("ready"),n()})):this[be]==="open"?this.nextTick(n):this.once(qi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=Vo(e,pe);let r=n=>{this[be]==="opening"||this[be]==="closing"?this.once(qi,n?r(n):r):this[be]!=="closed"?e(new An("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(qi),r(i)};this[zg](()=>{this._close(i=>{if(i)return n(i);this[be]="closed",this[Ad](),this.emit(qi),this[be]==="closed"&&this.emit("closed"),r()})})}else this[be]==="closed"?this.nextTick(r):this.once(qi,()=>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=Js(r,n),n=Vo(n,pe),r=qo(r,this[Xs].entry),this[be]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(Sa(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 An("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=Js(r,n),n=Vo(n,pe),r=qo(r,this[Xs].entry),this[be]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(Sa(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 An(`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=Js(n,i),i=Vo(i,pe),n=qo(n,this[Xs].entry),this[be]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(Sa(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=Js(r,n),n=Vo(n,pe),r=qo(r,this[Xs].key),this[be]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(Sa(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 l2(this);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Js(r,n),n=Vo(n,pe),r=qo(r,this[Xs].empty),this[be]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(Sa(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=Js(e,r),r=Vo(r,pe),e=qo(e,this[Xs].empty),this[be]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(Sa(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=lh(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=lh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new LU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Ys(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=lh(e,r),e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new PU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new NU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=lh(e,r),e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new MU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new CU(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 l2(this)}_checkKey(e){if(e==null)return new An("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new An("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};Td.prototype.nextTick=s2();var{AbstractSublevel:Jg}=f2()({AbstractLevel:Td});Zg.AbstractLevel=Td;Zg.AbstractSublevel=Jg;var Sa=function(t,e){return t[be]!=="open"?(t.nextTick(e,new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},$U=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var Qg=oe(Qs=>{"use strict";l();Qs.AbstractLevel=Xg().AbstractLevel;Qs.AbstractSublevel=Xg().AbstractSublevel;Qs.AbstractIterator=$o().AbstractIterator;Qs.AbstractKeyIterator=$o().AbstractKeyIterator;Qs.AbstractValueIterator=$o().AbstractValueIterator;Qs.AbstractChainedBatch=$g().AbstractChainedBatch});var y2=oe((Gq,p2)=>{l();p2.exports=VU;var HU=Vg();function VU(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?HU(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(x,S){f(y,x,S)})):(y=u,u+=1,t[y](function(x,S){f(y,x,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((Yq,g2)=>{"use strict";l();g2.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((Zq,m2)=>{"use strict";l();var qU=new TextEncoder;m2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):qU.encode(t)}});var v2=oe(E2=>{"use strict";l();var{AbstractIterator:FU}=Qg(),w2=em(),yh=tm(),ei=Symbol("cache"),Fi=Symbol("finished"),Cr=Symbol("options"),ji=Symbol("currentOptions"),ec=Symbol("position"),rm=Symbol("location"),Aa=Symbol("first"),b2={},nm=class extends FU{constructor(e,r,n){super(e,n),this[ei]=[],this[Fi]=this.limit===0,this[Cr]=n,this[ji]={...n},this[ec]=void 0,this[rm]=r,this[Aa]=!0}_nextv(e,r,n){if(this[Aa]=!1,this[Fi])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[ec]!==void 0&&(this[Cr].reverse?(this[ji].lt=this[ec],this[ji].lte=void 0):(this[ji].gt=this[ec],this[ji].gte=void 0));let i;try{i=w2(this[ji])}catch{return this[Fi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[rm]],"readonly"),s=o.objectStore(this[rm]),c=[];if(this[Cr].reverse){let a=!this[Cr].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[ec]=f,c.push([this[Cr].keys&&f!==void 0?yh(f):void 0,this[Cr].values&&h!==void 0?yh(h):void 0]),c.length<e?d.continue():x2(o)}else this[Fi]=!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[Fi]=!0:this[ec]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Cr].keys&&p!==void 0?yh(p):void 0,this[Cr].values&&g!==void 0?yh(g):void 0]}x2(o)};this[Cr].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[Cr].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[Fi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[Aa]&&(this[Aa]=!1,r=1),this._nextv(r,b2,(n,i)=>{if(n)return e(n);this[ei]=i,this._next(e)})}}_all(e,r){this[Aa]=!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,b2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[Aa]=!0,this[ei]=[],this[Fi]=!1,this[ec]=void 0,this[ji]={...this[Cr]};let n;try{n=w2(this[Cr])}catch{this[Fi]=!0;return}n!==null&&!n.includes(e)?this[Fi]=!0:this[Cr].reverse?this[ji].lte=e:this[ji].gte=e}};E2.Iterator=nm;function x2(t){typeof t.commit=="function"&&t.commit()}});var A2=oe((tF,S2)=>{"use strict";l();S2.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 U2=oe(R2=>{"use strict";l();var{AbstractLevel:jU}=Qg(),T2=vn(),WU=y2(),{fromCallback:GU}=ld(),{Iterator:zU}=v2(),_2=tm(),YU=A2(),JU=em(),B2="level-js-",_d=Symbol("idb"),im=Symbol("namePrefix"),Wi=Symbol("location"),om=Symbol("version"),tc=Symbol("store"),Id=Symbol("onComplete"),I2=Symbol("promise"),gh=class extends jU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new T2("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[Wi]=e,this[im]=i??B2,this[om]=parseInt(o||1,10),this[_d]=null}get location(){return this[Wi]}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[Wi],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[Wi])||o.createObjectStore(this[Wi])}}[tc](e){return this[_d].transaction([this[Wi]],e).objectStore(this[Wi])}[Id](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[tc]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[Id](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new T2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,_2(c))})}_getMany(e,r,n){let i=this[tc]("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:_2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});WU(o,16,n)}_del(e,r,n){let i=this[tc]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[Id](o,n)}_put(e,r,n,i){let o=this[tc]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[Id](s,i)}_iterator(e){return new zU(this,this[Wi],e)}_batch(e,r,n){let i=this[tc]("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=JU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return YU(this,this[Wi],n,e,r);try{let o=this[tc]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[Id](i,r)}_close(e){this[_d].close(),this.nextTick(e)}};gh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=B2),r=GU(r,I2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[I2]};R2.BrowserLevel=gh});var sm=oe(O2=>{l();O2.Level=U2().BrowserLevel});var nt=oe((lF,D2)=>{"use strict";l();D2.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 Ta=oe((pF,wh)=>{"use strict";l();var{AbortController:k2,AbortSignal:XU}=typeof self<"u"?self:typeof window<"u"?window:void 0;wh.exports=k2;wh.exports.AbortSignal=XU;wh.exports.default=k2});var Xt=oe((gF,am)=>{"use strict";l();var QU=Tr(),{kResistStopPropagation:eO,SymbolDispose:tO}=nt(),rO=globalThis.AbortSignal||Ta().AbortSignal,nO=globalThis.AbortController||Ta().AbortController,iO=Object.getPrototypeOf(async function(){}).constructor,N2=globalThis.Blob||QU.Blob,oO=typeof N2<"u"?function(e){return e instanceof N2}:function(e){return!1},C2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},sO=(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 iO},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:oO,deprecate(t,e){return t},addAbortListener:pa().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);C2(e,"signal"),sO(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[eO]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[tO](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:rO.any||function(e){if(e.length===1)return e[0];let r=new nO,n=()=>r.abort();return e.forEach(i=>{C2(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 sr=oe((wF,M2)=>{"use strict";l();var{format:cO,inspect:bh,AggregateError:aO}=Xt(),uO=globalThis.AggregateError||aO,dO=Symbol("kIsNodeError"),fO=["string","function","number","object","Function","Object","boolean","bigint","symbol"],lO=/^([A-Z][a-z0-9]*)+$/,hO="__node_internal_",xh={};function nc(t,e){if(!t)throw new xh.ERR_INTERNAL_ASSERTION(e)}function L2(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 pO(t,e,r){if(typeof e=="function")return nc(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 nc(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:cO(e,...r)}function Kt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(pO(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[dO]=!0,xh[t]=n}function P2(t){let e=hO+t.name;return Object.defineProperty(t,"name",{value:e}),t}function yO(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new uO([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 xh.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Kt("ERR_ASSERTION","%s",Error);Kt("ERR_INVALID_ARG_TYPE",(t,e,r)=>{nc(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)nc(typeof a=="string","All expected entries have to be of type string"),fO.includes(a)?i.push(a.toLowerCase()):lO.test(a)?o.push(a):(nc(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=bh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=bh(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Kt("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=bh(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Kt("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);Kt("ERR_MISSING_ARGS",(...t)=>{nc(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);Kt("ERR_OUT_OF_RANGE",(t,e,r)=>{nc(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=L2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=L2(n)),n+="n"):n=bh(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Kt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Kt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Kt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Kt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Kt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Kt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Kt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Kt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Kt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Kt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Kt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);M2.exports={AbortError:um,aggregateTwoErrors:P2(yO),hideStackFrames:P2,codes:xh}});var Ia=oe((xF,z2)=>{"use strict";l();var{ArrayIsArray:fm,ArrayPrototypeIncludes:V2,ArrayPrototypeJoin:q2,ArrayPrototypeMap:gO,NumberIsInteger:lm,NumberIsNaN:mO,NumberMAX_SAFE_INTEGER:wO,NumberMIN_SAFE_INTEGER:bO,NumberParseInt:xO,ObjectPrototypeHasOwnProperty:EO,RegExpPrototypeExec:F2,String:vO,StringPrototypeToUpperCase:SO,StringPrototypeTrim:AO}=nt(),{hideStackFrames:nn,codes:{ERR_SOCKET_BAD_PORT:TO,ERR_INVALID_ARG_TYPE:Qt,ERR_INVALID_ARG_VALUE:_a,ERR_OUT_OF_RANGE:ic,ERR_UNKNOWN_SIGNAL:K2}}=sr(),{normalizeEncoding:_O}=Xt(),{isAsyncFunction:IO,isArrayBufferView:BO}=Xt().types,$2={};function RO(t){return t===(t|0)}function UO(t){return t===t>>>0}var OO=/^[0-7]+$/,DO="must be a 32-bit unsigned integer or an octal string";function kO(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(F2(OO,t)===null)throw new _a(e,t,DO);t=xO(t,8)}return j2(t,e),t}var NO=nn((t,e,r=bO,n=wO)=>{if(typeof t!="number")throw new Qt(e,"number",t);if(!lm(t))throw new ic(e,"an integer",t);if(t<r||t>n)throw new ic(e,`>= ${r} && <= ${n}`,t)}),CO=nn((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Qt(e,"number",t);if(!lm(t))throw new ic(e,"an integer",t);if(t<r||t>n)throw new ic(e,`>= ${r} && <= ${n}`,t)}),j2=nn((t,e,r=!1)=>{if(typeof t!="number")throw new Qt(e,"number",t);if(!lm(t))throw new ic(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ic(e,`>= ${n} && <= ${i}`,t)});function hm(t,e){if(typeof t!="string")throw new Qt(e,"string",t)}function LO(t,e,r=void 0,n){if(typeof t!="number")throw new Qt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&mO(t))throw new ic(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var PO=nn((t,e,r)=>{if(!V2(r,t)){let i="must be one of: "+q2(gO(r,o=>typeof o=="string"?`'${o}'`:vO(o)),", ");throw new _a(e,t,i)}});function W2(t,e){if(typeof t!="boolean")throw new Qt(e,"boolean",t)}function dm(t,e,r){return t==null||!EO(t,e)?r:t[e]}var MO=nn((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 Qt(e,"Object",t)}),KO=nn((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Qt(e,"a dictionary",t)}),Eh=nn((t,e,r=0)=>{if(!fm(t))throw new Qt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new _a(e,t,n)}});function $O(t,e){Eh(t,e);for(let r=0;r<t.length;r++)hm(t[r],`${e}[${r}]`)}function HO(t,e){Eh(t,e);for(let r=0;r<t.length;r++)W2(t[r],`${e}[${r}]`)}function VO(t,e){Eh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Qt(i,"AbortSignal",n);G2(n,i)}}function qO(t,e="signal"){if(hm(t,e),$2[t]===void 0)throw $2[SO(t)]!==void 0?new K2(t+" (signals must use all capital letters)"):new K2(t)}var FO=nn((t,e="buffer")=>{if(!BO(t))throw new Qt(e,["Buffer","TypedArray","DataView"],t)});function jO(t,e){let r=_O(e),n=t.length;if(r==="hex"&&n%2!==0)throw new _a("encoding",e,`is invalid for data of length ${n}`)}function WO(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&AO(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new TO(e,t,r);return t|0}var G2=nn((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Qt(e,"AbortSignal",t)}),GO=nn((t,e)=>{if(typeof t!="function")throw new Qt(e,"Function",t)}),zO=nn((t,e)=>{if(typeof t!="function"||IO(t))throw new Qt(e,"Function",t)}),YO=nn((t,e)=>{if(t!==void 0)throw new Qt(e,"undefined",t)});function JO(t,e,r){if(!V2(r,t))throw new Qt(e,`('${q2(r,"|")}')`,t)}var ZO=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function H2(t,e){if(typeof t>"u"||!F2(ZO,t))throw new _a(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function XO(t){if(typeof t=="string")return H2(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];H2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new _a("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}z2.exports={isInt32:RO,isUint32:UO,parseFileMode:kO,validateArray:Eh,validateStringArray:$O,validateBooleanArray:HO,validateAbortSignalArray:VO,validateBoolean:W2,validateBuffer:FO,validateDictionary:KO,validateEncoding:jO,validateFunction:GO,validateInt32:CO,validateInteger:NO,validateNumber:LO,validateObject:MO,validateOneOf:PO,validatePlainFunction:zO,validatePort:WO,validateSignalName:qO,validateString:hm,validateUint32:j2,validateUndefined:YO,validateUnion:JO,validateAbortSignal:G2,validateLinkHeaderValue:XO}});var ri=oe((vF,uS)=>{"use strict";l();var{SymbolAsyncIterator:Y2,SymbolIterator:J2,SymbolFor:oc}=nt(),Z2=oc("nodejs.stream.destroyed"),X2=oc("nodejs.stream.errored"),pm=oc("nodejs.stream.readable"),ym=oc("nodejs.stream.writable"),Q2=oc("nodejs.stream.disturbed"),QO=oc("nodejs.webstream.isClosedPromise"),e5=oc("nodejs.webstream.controllerErrorFunction");function vh(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 Sh(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 t5(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 eS(t){return!!(t&&!ti(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function tS(t){return!!(t&&!ti(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function rS(t){return!!(t&&!ti(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function r5(t){return eS(t)||tS(t)||rS(t)}function n5(t,e){return t==null?!1:e===!0?typeof t[Y2]=="function":e===!1?typeof t[J2]=="function":typeof t[Y2]=="function"||typeof t[J2]=="function"}function Ah(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 nS(t){if(!Sh(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 i5(t,e){if(!Sh(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 o5(t){if(!vh(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 iS(t,e){if(!vh(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 oS(t){return t&&t[pm]!=null?t[pm]:typeof t?.readable!="boolean"?null:Ah(t)?!1:vh(t)&&t.readable&&!iS(t)}function sS(t){return t&&t[ym]!=null?t[ym]:typeof t?.writable!="boolean"?null:Ah(t)?!1:Sh(t)&&t.writable&&!nS(t)}function s5(t,e){return ti(t)?Ah(t)?!0:!(e?.readable!==!1&&oS(t)||e?.writable!==!1&&sS(t)):null}function c5(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 a5(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 u5(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"&&cS(t)?t._closed:null}function cS(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function aS(t){return typeof t._sent100=="boolean"&&cS(t)}function d5(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 f5(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&aS(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function l5(t){var e;return!!(t&&((e=t[Q2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function h5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[X2])!==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))}uS.exports={isDestroyed:Ah,kIsDestroyed:Z2,isDisturbed:l5,kIsDisturbed:Q2,isErrored:h5,kIsErrored:X2,isReadable:oS,kIsReadable:pm,kIsClosedPromise:QO,kControllerErrorFunction:e5,kIsWritable:ym,isClosed:u5,isDuplexNodeStream:t5,isFinished:s5,isIterable:n5,isReadableNodeStream:vh,isReadableStream:eS,isReadableEnded:o5,isReadableFinished:iS,isReadableErrored:a5,isNodeStream:ti,isWebStream:r5,isWritable:sS,isWritableNodeStream:Sh,isWritableStream:tS,isWritableEnded:nS,isWritableFinished:i5,isWritableErrored:c5,isServerRequest:d5,isServerResponse:aS,willEmitClose:f5,isTransformStream:rS}});var Gi=oe((AF,xm)=>{l();var Fo=Ei(),{AbortError:wS,codes:p5}=sr(),{ERR_INVALID_ARG_TYPE:y5,ERR_STREAM_PREMATURE_CLOSE:dS}=p5,{kEmptyObject:mm,once:wm}=Xt(),{validateAbortSignal:g5,validateFunction:m5,validateObject:w5,validateBoolean:b5}=Ia(),{Promise:x5,PromisePrototypeThen:E5,SymbolDispose:bS}=nt(),{isClosed:v5,isReadable:fS,isReadableNodeStream:gm,isReadableStream:S5,isReadableFinished:lS,isReadableErrored:hS,isWritable:pS,isWritableNodeStream:yS,isWritableStream:A5,isWritableFinished:gS,isWritableErrored:mS,isNodeStream:T5,willEmitClose:_5,kIsClosedPromise:I5}=ri(),Ba;function B5(t){return t.setHeader&&typeof t.abort=="function"}var bm=()=>{};function xS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=mm):e==null?e=mm:w5(e,"options"),m5(r,"callback"),g5(e.signal,"options.signal"),r=wm(r),S5(t)||A5(t))return R5(t,e,r);if(!T5(t))throw new y5("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:yS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=_5(t)&&gm(t)===o&&yS(t)===s,f=gS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=lS(t,!1),g=()=>{p=!0,t.destroyed&&(d=!1),!(d&&(!t.writable||s))&&(!s||f)&&r.call(t)},y=T=>{r.call(t,T)},x=v5(t),S=()=>{x=!0;let T=mS(t)||hS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&gm(t,!0)&&!lS(t,!1))return r.call(t,new dS);if(s&&!f&&!gS(t,!1))return r.call(t,new dS);r.call(t)},_=()=>{x=!0;let T=mS(t)||hS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};B5(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),x?Fo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Fo.nextTick(_):(!o&&(!d||fS(t))&&(f||pS(t)===!1)||!s&&(!d||pS(t))&&(p||fS(t)===!1)||a&&t.req&&t.aborted)&&Fo.nextTick(_);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&&!x){let T=()=>{let M=r;O(),M.call(t,new wS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Fo.nextTick(T);else{Ba=Ba||Xt().addAbortListener;let M=Ba(e.signal,T),q=r;r=wm((...j)=>{M[bS](),q.apply(t,j)})}}return O}function R5(t,e,r){let n=!1,i=bm;if(e.signal)if(i=()=>{n=!0,r.call(t,new wS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Fo.nextTick(i);else{Ba=Ba||Xt().addAbortListener;let s=Ba(e.signal,i),c=r;r=wm((...a)=>{s[bS](),c.apply(t,a)})}let o=(...s)=>{n||Fo.nextTick(()=>r.apply(t,s))};return E5(t[I5].promise,o,o),bm}function U5(t,e){var r;let n=!1;return e===null&&(e=mm),(r=e)!==null&&r!==void 0&&r.cleanup&&(b5(e.cleanup,"cleanup"),n=e.cleanup),new x5((i,o)=>{let s=xS(t,e,c=>{n&&s(),c?o(c):i()})})}xm.exports=xS;xm.exports.finished=U5});var sc=oe((_F,BS)=>{"use strict";l();var ni=Ei(),{aggregateTwoErrors:O5,codes:{ERR_MULTIPLE_CALLBACK:D5},AbortError:k5}=sr(),{Symbol:SS}=nt(),{kIsDestroyed:N5,isDestroyed:C5,isFinished:L5,isServerRequest:P5}=ri(),AS=SS("kDestroy"),Em=SS("kConstruct");function TS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function M5(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):(TS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?ES(this,t,e):this.once(AS,function(o){ES(this,O5(o,t),e)}),this)}function ES(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;TS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ni.nextTick(K5,t,o):ni.nextTick(_S,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function K5(t,e){vm(t,e),_S(t)}function _S(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 $5(){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?ni.nextTick(vm,t,e):vm(t,e))}function H5(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)&&ni.nextTick(V5,t)}function V5(t){let e=!1;function r(n){if(e){Sm(t,n??new D5);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(AS,n):n?Sm(t,n,!0):ni.nextTick(q5,t)}try{t._construct(n=>{ni.nextTick(r,n)})}catch(n){ni.nextTick(r,n)}}function q5(t){t.emit(Em)}function vS(t){return t?.setHeader&&typeof t.abort=="function"}function IS(t){t.emit("close")}function F5(t,e){t.emit("error",e),ni.nextTick(IS,t)}function j5(t,e){!t||C5(t)||(!e&&!L5(t)&&(e=new k5),P5(t)?(t.socket=null,t.destroy(e)):vS(t)?t.abort():vS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ni.nextTick(F5,t,e):ni.nextTick(IS,t),t.destroyed||(t[N5]=!0))}BS.exports={construct:H5,destroyer:j5,destroy:M5,undestroy:$5,errorOrDestroy:Sm}});var Ih=oe((BF,US)=>{"use strict";l();var{ArrayIsArray:W5,ObjectSetPrototypeOf:RS}=nt(),{EventEmitter:Th}=pa();function _h(t){Th.call(this,t)}RS(_h.prototype,Th.prototype);RS(_h,Th);_h.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(),Th.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):W5(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}US.exports={Stream:_h,prependListener:Am}});var Bd=oe((UF,Bh)=>{"use strict";l();var{SymbolDispose:G5}=nt(),{AbortError:OS,codes:z5}=sr(),{isNodeStream:DS,isWebStream:Y5,kControllerErrorFunction:J5}=ri(),Z5=Gi(),{ERR_INVALID_ARG_TYPE:kS}=z5,Tm,X5=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new kS(e,"AbortSignal",t)};Bh.exports.addAbortSignal=function(e,r){if(X5(e,"signal"),!DS(r)&&!Y5(r))throw new kS("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=DS(e)?()=>{e.destroy(new OS(void 0,{cause:t.reason}))}:()=>{e[J5](new OS(void 0,{cause:t.reason}))};if(t.aborted)r();else{Tm=Tm||Xt().addAbortListener;let n=Tm(t,r);Z5(e,n[G5])}return e}});var LS=oe((kF,CS)=>{"use strict";l();var{StringPrototypeSlice:NS,SymbolIterator:Q5,TypedArrayPrototypeSet:Rh,Uint8Array:e3}=nt(),{Buffer:_m}=Tr(),{inspect:t3}=Xt();CS.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;)Rh(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}*[Q5](){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+=NS(o,0,e),this.head=n,n.data=NS(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)Rh(r,s,n-e),e-=s.length;else{e===s.length?(Rh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Rh(r,new e3(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 t3(this,{...r,depth:0,customInspect:!1})}}});var Rd=oe((CF,$S)=>{"use strict";l();var{MathFloor:r3,NumberIsInteger:n3}=nt(),{validateInteger:i3}=Ia(),{ERR_INVALID_ARG_VALUE:o3}=sr().codes,PS=16*1024,MS=16;function s3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function KS(t){return t?MS:PS}function c3(t,e){i3(e,"value",0),t?MS=e:PS=e}function a3(t,e,r,n){let i=s3(e,n,r);if(i!=null){if(!n3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new o3(o,i)}return r3(i)}return KS(t.objectMode)}$S.exports={getHighWaterMark:a3,getDefaultHighWaterMark:KS,setDefaultHighWaterMark:c3}});var qS=oe((Im,VS)=>{l();var Uh=Tr(),ii=Uh.Buffer;function HS(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?VS.exports=Uh:(HS(Uh,Im),Im.Buffer=cc);function cc(t,e,r){return ii(t,e,r)}cc.prototype=Object.create(ii.prototype);HS(ii,cc);cc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};cc.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};cc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};cc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Uh.SlowBuffer(t)}});var WS=oe(jS=>{"use strict";l();var Rm=qS().Buffer,FS=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 u3(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 d3(t){var e=u3(t);if(typeof e!="string"&&(Rm.isEncoding===FS||!FS(t)))throw new Error("Unknown encoding: "+t);return e||t}jS.StringDecoder=Ud;function Ud(t){this.encoding=d3(t);var e;switch(this.encoding){case"utf16le":this.text=g3,this.end=m3,e=4;break;case"utf8":this.fillLast=h3,e=4;break;case"base64":this.text=w3,this.end=b3,e=3;break;default:this.write=x3,this.end=E3;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=y3;Ud.prototype.text=p3;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 Bm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function f3(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 l3(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 h3(t){var e=this.lastTotal-this.lastNeed,r=l3(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 p3(t,e){var r=f3(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 y3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function g3(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 m3(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 w3(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 b3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function x3(t){return t.toString(this.encoding)}function E3(t){return t&&t.length?this.write(t):""}});var Um=oe(($F,JS)=>{"use strict";l();var GS=Ei(),{PromisePrototypeThen:v3,SymbolAsyncIterator:zS,SymbolIterator:YS}=nt(),{Buffer:S3}=Tr(),{ERR_INVALID_ARG_TYPE:A3,ERR_STREAM_NULL_VALUES:T3}=sr().codes;function _3(t,e,r){let n;if(typeof e=="string"||e instanceof S3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[zS])i=!0,n=e[zS]();else if(e&&e[YS])i=!1,n=e[YS]();else throw new A3("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){v3(c(u),()=>GS.nextTick(d,u),f=>GS.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 T3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}JS.exports=_3});var Dd=oe((VF,pA)=>{l();var Tn=Ei(),{ArrayPrototypeIndexOf:I3,NumberIsInteger:B3,NumberIsNaN:R3,NumberParseInt:U3,ObjectDefineProperties:Mm,ObjectKeys:O3,ObjectSetPrototypeOf:QS,Promise:eA,SafeSet:D3,SymbolAsyncDispose:k3,SymbolAsyncIterator:N3,Symbol:C3}=nt();pA.exports=ye;ye.ReadableState=Nh;var{EventEmitter:L3}=pa(),{Stream:jo,prependListener:P3}=Ih(),{Buffer:Om}=Tr(),{addAbortSignal:M3}=Bd(),tA=Gi(),Ee=Xt().debuglog("stream",t=>{Ee=t}),K3=LS(),Oa=sc(),{getHighWaterMark:$3,getDefaultHighWaterMark:H3}=Rd(),{aggregateTwoErrors:ZS,codes:{ERR_INVALID_ARG_TYPE:V3,ERR_METHOD_NOT_IMPLEMENTED:q3,ERR_OUT_OF_RANGE:F3,ERR_STREAM_PUSH_AFTER_EOF:j3,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:W3},AbortError:G3}=sr(),{validateObject:z3}=Ia(),ac=C3("kPaused"),{StringDecoder:rA}=WS(),Y3=Um();QS(ye.prototype,jo.prototype);QS(ye,jo);var Dm=()=>{},{errorOrDestroy:Ra}=Oa,Ua=1,J3=2,nA=4,Od=8,iA=16,Oh=32,Dh=64,oA=128,Z3=256,X3=512,Q3=1024,Lm=2048,Pm=4096,eD=8192,tD=16384,rD=32768,sA=65536,nD=1<<17,iD=1<<18;function At(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Mm(Nh.prototype,{objectMode:At(Ua),ended:At(J3),endEmitted:At(nA),reading:At(Od),constructed:At(iA),sync:At(Oh),needReadable:At(Dh),emittedReadable:At(oA),readableListening:At(Z3),resumeScheduled:At(X3),errorEmitted:At(Q3),emitClose:At(Lm),autoDestroy:At(Pm),destroyed:At(eD),closed:At(tD),closeEmitted:At(rD),multiAwaitDrain:At(sA),readingMore:At(nD),dataEmitted:At(iD)});function Nh(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.state=Lm|Pm|iA|Oh,t&&t.objectMode&&(this.state|=Ua),r&&t&&t.readableObjectMode&&(this.state|=Ua),this.highWaterMark=t?$3(this,t,"readableHighWaterMark",r):H3(!1),this.buffer=new K3,this.length=0,this.pipes=[],this.flowing=null,this[ac]=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 rA(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 Nh(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&&M3(t.signal,this)),jo.call(this,t),Oa.construct(this,()=>{this._readableState.needReadable&&kh(this,this._readableState)})}ye.prototype.destroy=Oa.destroy;ye.prototype._undestroy=Oa.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[L3.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[k3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new G3,this.destroy(t)),new eA((e,r)=>tA(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return cA(this,t,e,!1)};ye.prototype.unshift=function(t,e){return cA(this,t,e,!0)};function cA(t,e,r,n){Ee("readableAddChunk",e);let i=t._readableState,o;if(i.state&Ua||(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="":jo._isUint8Array(e)?(e=jo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new V3("chunk",["string","Buffer","Uint8Array"],e))),o)Ra(t,o);else if(e===null)i.state&=~Od,cD(t,i);else if(i.state&Ua||e&&e.length>0)if(n)if(i.state&nA)Ra(t,new W3);else{if(i.destroyed||i.errored)return!1;km(t,i,e,!0)}else if(i.ended)Ra(t,new j3);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):kh(t,i)):km(t,i,e,!1)}else n||(i.state&=~Od,kh(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&sA?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&Dh&&Ch(t)),kh(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[ac]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new rA(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 oD=1073741824;function sD(t){if(t>oD)throw new F3("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function XS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Ua?1:R3(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){Ee("read",t),t===void 0?t=NaN:B3(t)||(t=U3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=sD(t)),t!==0&&(e.state&=~oA),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ee("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Nm(this):Ch(this),null;if(t=XS(t,e),t===0&&e.ended)return e.length===0&&Nm(this),null;let n=(e.state&Dh)!==0;if(Ee("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,Ee("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,Ee("reading, ended or constructing",n);else if(n){Ee("do read"),e.state|=Od|Oh,e.length===0&&(e.state|=Dh);try{this._read(e.highWaterMark)}catch(o){Ra(this,o)}e.state&=~Oh,e.reading||(t=XS(r,e))}let i;return t>0?i=lA(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 cD(t,e){if(Ee("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?Ch(t):(e.needReadable=!1,e.emittedReadable=!0,aA(t))}}function Ch(t){let e=t._readableState;Ee("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ee("emitReadable",e.flowing),e.emittedReadable=!0,Tn.nextTick(aA,t))}function aA(t){let e=t._readableState;Ee("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,dA(t)}function kh(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,Tn.nextTick(aD,t,e))}function aD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(Ee("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new q3("_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 D3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),Ee("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==Tn.stdout&&t!==Tn.stderr?c:x;n.endEmitted?Tn.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,_){Ee("onunpipe"),S===r&&_&&_.hasUnpiped===!1&&(_.hasUnpiped=!0,d())}function c(){Ee("onend"),t.end()}let a,u=!1;function d(){Ee("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",x),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?(Ee("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(Ee("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=uD(r,t),t.on("drain",a))}r.on("data",h);function h(S){Ee("ondata");let _=t.write(S);Ee("dest.write",_),_===!1&&f()}function p(S){if(Ee("onerror",S),x(),t.removeListener("error",p),t.listenerCount("error")===0){let _=t._writableState||t._readableState;_&&!_.errorEmitted?Ra(t,S):t.emit("error",S)}}P3(t,"error",p);function g(){t.removeListener("finish",y),x()}t.once("close",g);function y(){Ee("onfinish"),t.removeListener("close",g),x()}t.once("finish",y);function x(){Ee("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(Ee("pipe resume"),r.resume()),t};function uD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(Ee("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(Ee("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=I3(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=jo.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,Ee("on readable",n.length,n.reading),n.length?Ch(this):n.reading||Tn.nextTick(dD,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=jo.prototype.removeListener.call(this,t,e);return t==="readable"&&Tn.nextTick(uA,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=jo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&Tn.nextTick(uA,this),e};function uA(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[ac]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function dD(t){Ee("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(Ee("resume"),t.flowing=!t.readableListening,fD(this,t)),t[ac]=!1,this};function fD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,Tn.nextTick(lD,t,e))}function lD(t,e){Ee("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),dA(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return Ee("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ee("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[ac]=!0,this};function dA(t){let e=t._readableState;for(Ee("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=>{Ra(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=O3(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[N3]=function(){return fA(this)};ye.prototype.iterator=function(t){return t!==void 0&&z3(t,"options"),fA(this,t)};function fA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=hD(t,e);return r.stream=t,r}async function*hD(t,e){let r=Dm;function n(s){this===t?(r(),r=Dm):r=s}t.on("readable",n);let i,o=tA(t,{writable:!1},s=>{i=s?ZS(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 eA(n)}}}catch(s){throw i=ZS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Oa.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(Nh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[ac]!==!1},set(t){this[ac]=!!t}}});ye._fromList=lA;function lA(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;Ee("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,Tn.nextTick(pD,e,t))}function pD(t,e){if(Ee("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)Tn.nextTick(yD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function yD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return Y3(ye,t,e)};var Cm;function hA(){return Cm===void 0&&(Cm={}),Cm}ye.fromWeb=function(t,e){return hA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return hA().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){Oa.destroyer(t,i),o(i)}}).wrap(t)}});var $h=oe((FF,_A)=>{l();var uc=Ei(),{ArrayPrototypeSlice:mA,Error:gD,FunctionPrototypeSymbolHasInstance:wA,ObjectDefineProperty:bA,ObjectDefineProperties:mD,ObjectSetPrototypeOf:xA,StringPrototypeToLowerCase:wD,Symbol:bD,SymbolHasInstance:xD}=nt();_A.exports=it;it.WritableState=Cd;var{EventEmitter:ED}=pa(),kd=Ih().Stream,{Buffer:Lh}=Tr(),Kh=sc(),{addAbortSignal:vD}=Bd(),{getHighWaterMark:SD,getDefaultHighWaterMark:AD}=Rd(),{ERR_INVALID_ARG_TYPE:TD,ERR_METHOD_NOT_IMPLEMENTED:_D,ERR_MULTIPLE_CALLBACK:EA,ERR_STREAM_CANNOT_PIPE:ID,ERR_STREAM_DESTROYED:Nd,ERR_STREAM_ALREADY_FINISHED:BD,ERR_STREAM_NULL_VALUES:RD,ERR_STREAM_WRITE_AFTER_END:UD,ERR_UNKNOWN_ENCODING:vA}=sr().codes,{errorOrDestroy:Da}=Kh;xA(it.prototype,kd.prototype);xA(it,kd);function Hm(){}var ka=bD("kOnFinished");function Cd(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?SD(this,t,"writableHighWaterMark",r):AD(!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=DD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Mh(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[ka]=[]}function Mh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Cd.prototype.getBuffer=function(){return mA(this.buffered,this.bufferedIndex)};bA(Cd.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof oi();if(!e&&!wA(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&&vD(t.signal,this)),kd.call(this,t),Kh.construct(this,()=>{let r=this._writableState;r.writing||qm(this,r),Fm(this,r)})}bA(it,xD,{__proto__:null,value:function(t){return wA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Cd}});it.prototype.pipe=function(){Da(this,new ID)};function SA(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"&&!Lh.isEncoding(r))throw new vA(r);typeof n!="function"&&(n=Hm)}if(e===null)throw new RD;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Lh.from(e,r),r="buffer");else if(e instanceof Lh)r="buffer";else if(kd._isUint8Array(e))e=kd._uint8ArrayToBuffer(e),r="buffer";else throw new TD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new UD:i.destroyed&&(o=new Nd("write")),o?(uc.nextTick(n,o),Da(t,o,!0),o):(i.pendingcb++,OD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return SA(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=wD(e)),!Lh.isEncoding(e))throw new vA(e);return this._writableState.defaultEncoding=e,this};function OD(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 yA(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 gA(t,e,r,n){--e.pendingcb,n(r),Vm(e),Da(t,r)}function DD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Da(t,new EA);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?uc.nextTick(gA,t,r,e,i):gA(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},uc.nextTick(kD,r.afterWriteTickInfo)):AA(t,r,1,i))}function kD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,AA(t,e,r,n)}function AA(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[ka].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"))}Mh(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:mA(r,s);a.allBuffers=e.allBuffers,yA(t,e,!0,e.length,a,"",c),Mh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;yA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Mh(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 _D("_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=SA(this,t,e);o instanceof gD&&(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 BD("end"):n.destroyed&&(i=new Nd("end"))),typeof r=="function"&&(i||n.finished?uc.nextTick(r,i):n[ka].push(r)),this};function Ph(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 ND(t,e){let r=!1;function n(i){if(r){Da(t,i??EA());return}if(r=!0,e.pendingcb--,i){let o=e[ka].splice(0);for(let s=0;s<o.length;s++)o[s](i);Da(t,i,e.sync)}else Ph(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,uc.nextTick($m,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function CD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,ND(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Fm(t,e,r){Ph(e)&&(CD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,uc.nextTick((n,i)=>{Ph(i)?$m(n,i):i.pendingcb--},t,e)):Ph(e)&&(e.pendingcb++,$m(t,e))))}function $m(t,e){e.pendingcb--,e.finished=!0;let r=e[ka].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()}}mD(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 LD=Kh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[ka].length)&&uc.nextTick(Vm,r),LD.call(this,t,e),this};it.prototype._undestroy=Kh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[ED.captureRejectionSymbol]=function(t){this.destroy(t)};var Km;function TA(){return Km===void 0&&(Km={}),Km}it.fromWeb=function(t,e){return TA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return TA().newWritableStreamFromStreamWritable(t)}});var HA=oe((WF,$A)=>{l();var jm=Ei(),PD=Tr(),{isReadable:MD,isWritable:KD,isIterable:IA,isNodeStream:$D,isReadableNodeStream:BA,isWritableNodeStream:RA,isDuplexNodeStream:HD,isReadableStream:UA,isWritableStream:OA}=ri(),DA=Gi(),{AbortError:MA,codes:{ERR_INVALID_ARG_TYPE:VD,ERR_INVALID_RETURN_VALUE:kA}}=sr(),{destroyer:Ca}=sc(),qD=oi(),KA=Dd(),FD=$h(),{createDeferredPromise:NA}=Xt(),CA=Um(),LA=globalThis.Blob||PD.Blob,jD=typeof LA<"u"?function(e){return e instanceof LA}:function(e){return!1},WD=globalThis.AbortController||Ta().AbortController,{FunctionPrototypeCall:PA}=nt(),Wo=class extends qD{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)}};$A.exports=function t(e,r){if(HD(e))return e;if(BA(e))return Na({readable:e});if(RA(e))return Na({writable:e});if($D(e))return Na({writable:!1,readable:!1});if(UA(e))return Na({readable:KA.fromWeb(e)});if(OA(e))return Na({writable:FD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=GD(e);if(IA(i))return CA(Wo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=PA(a,i,f=>{if(f!=null)throw new kA("nully","body",f)},f=>{Ca(u,f)});return u=new Wo({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 kA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(jD(e))return t(e.arrayBuffer());if(IA(e))return CA(Wo,e,{objectMode:!0,writable:!1});if(UA(e?.readable)&&OA(e?.writable))return Wo.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?RA(e?.writable)?e?.writable:t(e.writable):void 0;return Na({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return PA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Ca(i,o)}),i=new Wo({objectMode:!0,writable:!1,read(){}})}throw new VD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function GD(t){let{promise:e,resolve:r}=NA(),n=new WD,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 MA(void 0,{cause:i.reason});({promise:e,resolve:r}=NA()),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 Na(t){let e=t.readable&&typeof t.readable.read!="function"?KA.wrap(t.readable):t.readable,r=t.writable,n=!!MD(e),i=!!KD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new Wo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(DA(r,f=>{i=!1,f&&Ca(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&&(DA(e,f=>{n=!1,f&&Ca(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 MA),c=null,o=null,s=null,a===null?h(f):(a=h,Ca(r,f),Ca(e,f))},u}});var oi=oe((zF,FA)=>{"use strict";l();var{ObjectDefineProperties:zD,ObjectGetOwnPropertyDescriptor:zi,ObjectKeys:YD,ObjectSetPrototypeOf:VA}=nt();FA.exports=_n;var zm=Dd(),on=$h();VA(_n.prototype,zm.prototype);VA(_n,zm);{let t=YD(on.prototype);for(let e=0;e<t.length;e++){let r=t[e];_n.prototype[r]||(_n.prototype[r]=on.prototype[r])}}function _n(t){if(!(this instanceof _n))return new _n(t);zm.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}zD(_n.prototype,{writable:{__proto__:null,...zi(on.prototype,"writable")},writableHighWaterMark:{__proto__:null,...zi(on.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...zi(on.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...zi(on.prototype,"writableBuffer")},writableLength:{__proto__:null,...zi(on.prototype,"writableLength")},writableFinished:{__proto__:null,...zi(on.prototype,"writableFinished")},writableCorked:{__proto__:null,...zi(on.prototype,"writableCorked")},writableEnded:{__proto__:null,...zi(on.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...zi(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 Wm;function qA(){return Wm===void 0&&(Wm={}),Wm}_n.fromWeb=function(t,e){return qA().newStreamDuplexFromReadableWritablePair(t,e)};_n.toWeb=function(t){return qA().newReadableWritablePairFromDuplex(t)};var Gm;_n.from=function(t){return Gm||(Gm=HA()),Gm(t,"body")}});var Zm=oe((JF,WA)=>{"use strict";l();var{ObjectSetPrototypeOf:jA,Symbol:JD}=nt();WA.exports=Yi;var{ERR_METHOD_NOT_IMPLEMENTED:ZD}=sr().codes,Jm=oi(),{getHighWaterMark:XD}=Rd();jA(Yi.prototype,Jm.prototype);jA(Yi,Jm);var Ld=JD("kCallback");function Yi(t){if(!(this instanceof Yi))return new Yi(t);let e=t?XD(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",QD)}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 QD(){this._final!==Ym&&Ym.call(this)}Yi.prototype._final=Ym;Yi.prototype._transform=function(t,e,r){throw new ZD("_transform()")};Yi.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})};Yi.prototype._read=function(){if(this[Ld]){let t=this[Ld];this[Ld]=null,t()}}});var Qm=oe((XF,zA)=>{"use strict";l();var{ObjectSetPrototypeOf:GA}=nt();zA.exports=La;var Xm=Zm();GA(La.prototype,Xm.prototype);GA(La,Xm);function La(t){if(!(this instanceof La))return new La(t);Xm.call(this,t)}La.prototype._transform=function(t,e,r){r(null,t)}});var Fh=oe((ej,QA)=>{l();var Pd=Ei(),{ArrayIsArray:ek,Promise:tk,SymbolAsyncIterator:rk,SymbolDispose:nk}=nt(),qh=Gi(),{once:ik}=Xt(),ok=sc(),YA=oi(),{aggregateTwoErrors:sk,codes:{ERR_INVALID_ARG_TYPE:aw,ERR_INVALID_RETURN_VALUE:ew,ERR_MISSING_ARGS:ck,ERR_STREAM_DESTROYED:ak,ERR_STREAM_PREMATURE_CLOSE:uk},AbortError:dk}=sr(),{validateFunction:fk,validateAbortSignal:lk}=Ia(),{isIterable:dc,isReadable:tw,isReadableNodeStream:Vh,isNodeStream:JA,isTransformStream:Pa,isWebStream:hk,isReadableStream:rw,isReadableFinished:pk}=ri(),yk=globalThis.AbortController||Ta().AbortController,nw,iw,ow;function ZA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=qh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,ok.destroyer(t,o||new ak("pipe")))},cleanup:i}}function gk(t){return fk(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function sw(t){if(dc(t))return t;if(Vh(t))return mk(t);throw new aw("val",["Readable","Iterable","AsyncIterable"],t)}async function*mk(t){iw||(iw=Dd()),yield*iw.prototype[rk].call(t)}async function Hh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new tk((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=qh(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?sk(i,u):u)}finally{a(),e.off("drain",s)}}async function cw(t,e,r,{end:n}){Pa(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 wk(...t){return XA(t,ik(gk(t)))}function XA(t,e,r){if(t.length===1&&ek(t[0])&&(t=t[0]),t.length<2)throw new ck("streams");let n=new yk,i=n.signal,o=r?.signal,s=[];lk(o,"options.signal");function c(){g(new dk)}ow=ow||Xt().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[nk](),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(JA(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var _=$;if(q){let{destroy:X,cleanup:Q}=ZA(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}),!dc(y))throw new ew("Iterable, AsyncIterable or Stream","source",y)}else dc(O)||Vh(O)||Pa(O)?y=O:y=YA.from(O);else if(typeof O=="function"){if(Pa(y)){var x;y=sw((x=y)===null||x===void 0?void 0:x.readable)}else y=sw(y);if(y=O(y,{signal:i}),T){if(!dc(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,I=>{d=I,I!=null&&$.write(I),q&&$.end(),Pd.nextTick(p)},I=>{$.destroy(I),Pd.nextTick(p,I)});else if(dc(y,!0))h++,Hh(y,$,p,{end:q});else if(rw(y)||Pa(y)){let I=y.readable||y;h++,Hh(I,$,p,{end:q})}else throw new ew("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=ZA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(JA(O)){if(Vh(y)){h+=2;let $=bk(y,O,p,{end:q});tw(O)&&j&&s.push($)}else if(Pa(y)||rw(y)){let $=y.readable||y;h++,Hh($,O,p,{end:q})}else if(dc(y))h++,Hh(y,O,p,{end:q});else throw new aw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(hk(O)){if(Vh(y))h++,cw(sw(y),O,p,{end:q});else if(rw(y)||dc(y))h++,cw(y,O,p,{end:q});else if(Pa(y))h++,cw(y.readable,O,p,{end:q});else throw new aw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=YA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Pd.nextTick(c),y}function bk(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new uk)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;pk(t)?Pd.nextTick(s):t.once("end",s)}else r();return qh(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)}),qh(e,{readable:!1,writable:!0},r)}QA.exports={pipelineImpl:XA,pipeline:wk}});var dw=oe((rj,oT)=>{"use strict";l();var{pipeline:xk}=Fh(),jh=oi(),{destroyer:Ek}=sc(),{isNodeStream:Wh,isReadable:eT,isWritable:tT,isWebStream:uw,isTransformStream:fc,isWritableStream:rT,isReadableStream:nT}=ri(),{AbortError:vk,codes:{ERR_INVALID_ARG_VALUE:iT,ERR_MISSING_ARGS:Sk}}=sr(),Ak=Gi();oT.exports=function(...e){if(e.length===0)throw new Sk("streams");if(e.length===1)return jh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=jh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=jh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Wh(e[p])&&!uw(e[p]))){if(p<e.length-1&&!(eT(e[p])||nT(e[p])||fc(e[p])))throw new iT(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(tT(e[p])||rT(e[p])||fc(e[p])))throw new iT(`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=xk(e,a),f=!!(tT(u)||rT(u)||fc(u)),h=!!(eT(d)||nT(d)||fc(d));if(c=new jh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Wh(u))c._write=function(g,y,x){u.write(g,y)?x():n=x},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=(fc(u)?u.writable:u).getWriter();c._write=async function(x,S,_){try{await y.ready,y.write(x).catch(()=>{}),_()}catch(A){_(A)}},c._final=async function(x){try{await y.ready,y.close().catch(()=>{}),i=x}catch(S){x(S)}}}let p=fc(d)?d.readable:d;Ak(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Wh(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=(fc(d)?d.readable:d).getReader();c._read=async function(){for(;;)try{let{value:y,done:x}=await g.read();if(!c.push(y))return;if(x){c.push(null);return}}catch{return}}}}return c._destroy=function(p,g){!p&&s!==null&&(p=new vk),o=null,n=null,i=null,s===null?g(p):(s=g,Wh(d)&&Ek(d,p))},c}});var yT=oe((ij,hw)=>{"use strict";l();var Tk=globalThis.AbortController||Ta().AbortController,{codes:{ERR_INVALID_ARG_VALUE:_k,ERR_INVALID_ARG_TYPE:Md,ERR_MISSING_ARGS:Ik,ERR_OUT_OF_RANGE:Bk},AbortError:si}=sr(),{validateAbortSignal:lc,validateInteger:sT,validateObject:hc}=Ia(),Rk=nt().Symbol("kWeak"),Uk=nt().Symbol("kResistStopPropagation"),{finished:Ok}=Gi(),Dk=dw(),{addAbortSignalNoValidate:kk}=Bd(),{isWritable:Nk,isNodeStream:Ck}=ri(),{deprecate:Lk}=Xt(),{ArrayPrototypePush:Pk,Boolean:Mk,MathFloor:cT,Number:Kk,NumberIsNaN:$k,Promise:aT,PromiseReject:uT,PromiseResolve:Hk,PromisePrototypeThen:dT,Symbol:lT}=nt(),Gh=lT("kEmpty"),fT=lT("kEof");function Vk(t,e){if(e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),Ck(t)&&!Nk(t))throw new _k("stream",t,"must be writable");let r=Dk(this,t);return e!=null&&e.signal&&kk(e.signal,r),r}function zh(t,e){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=cT(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=cT(e.highWaterMark)),sT(r,"options.concurrency",1),sT(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Xt().AbortSignalAny([e?.signal].filter(Mk)),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 x(){try{for await(let S of s){if(f)return;if(o.aborted)throw new si;try{if(S=t(S,a),S===Gh)continue;S=Hk(S)}catch(_){S=uT(_)}h+=1,dT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new aT(_=>{d=_})}c.push(fT)}catch(S){let _=uT(S);dT(_,g,p),c.push(_)}finally{f=!0,u&&(u(),u=null)}}x();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===fT)return;if(o.aborted)throw new si;S!==Gh&&(yield S),c.shift(),y()}await new aT(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function qk(t=void 0){return t!=null&&hc(t,"options"),t?.signal!=null&&lc(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 hT(t,e=void 0){for await(let r of lw.call(this,t,e))return!0;return!1}async function Fk(t,e=void 0){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);return!await hT.call(this,async(...r)=>!await t(...r),e)}async function jk(t,e){for await(let r of lw.call(this,t,e))return r}async function Wk(t,e){if(typeof t!="function")throw new Md("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Gh}for await(let n of zh.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:Gh}return zh.call(this,r,e)}var fw=class extends Ik{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function Gk(t,e,r){var n;if(typeof t!="function")throw new Md("reducer",["Function","AsyncFunction"],t);r!=null&&hc(r,"options"),r?.signal!=null&&lc(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 Ok(this.destroy(u)),u}let o=new Tk,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[Rk]:this,[Uk]:!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 fw}finally{o.abort()}return e}async function zk(t){t!=null&&hc(t,"options"),t?.signal!=null&&lc(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});Pk(e,n)}return e}function Yk(t,e){let r=zh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function pT(t){if(t=Kk(t),$k(t))return 0;if(t<0)throw new Bk("number",">= 0",t);return t}function Jk(t,e=void 0){return e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),t=pT(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 Zk(t,e=void 0){return e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),t=pT(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)}hw.exports.streamReturningOperators={asIndexedPairs:Lk(qk,"readable.asIndexedPairs will be removed in a future version."),drop:Jk,filter:lw,flatMap:Yk,map:zh,take:Zk,compose:Vk};hw.exports.promiseReturningOperators={every:Fk,forEach:Wk,reduce:Gk,toArray:zk,some:hT,find:jk}});var pw=oe((sj,gT)=>{"use strict";l();var{ArrayPrototypePop:Xk,Promise:Qk}=nt(),{isIterable:e4,isNodeStream:t4,isWebStream:r4}=ri(),{pipelineImpl:n4}=Fh(),{finished:i4}=Gi();yw();function o4(...t){return new Qk((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!t4(o)&&!e4(o)&&!r4(o)){let s=Xk(t);n=s.signal,i=s.end}n4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}gT.exports={finished:i4,pipeline:o4}});var yw=oe((aj,TT)=>{l();var{Buffer:s4}=Tr(),{ObjectDefineProperty:Ji,ObjectKeys:bT,ReflectApply:xT}=nt(),{promisify:{custom:ET}}=Xt(),{streamReturningOperators:mT,promiseReturningOperators:wT}=yT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:vT}}=sr(),c4=dw(),{setDefaultHighWaterMark:a4,getDefaultHighWaterMark:u4}=Rd(),{pipeline:ST}=Fh(),{destroyer:d4}=sc(),AT=Gi(),gw=pw(),Kd=ri(),We=TT.exports=Ih().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 bT(mT)){let r=function(...n){if(new.target)throw vT();return We.Readable.from(xT(e,this,n))};mw=r;let e=mT[t];Ji(r,"name",{__proto__:null,value:e.name}),Ji(r,"length",{__proto__:null,value:e.length}),Ji(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var mw;for(let t of bT(wT)){let r=function(...i){if(new.target)throw vT();return xT(e,this,i)};mw=r;let e=wT[t];Ji(r,"name",{__proto__:null,value:e.name}),Ji(r,"length",{__proto__:null,value:e.length}),Ji(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var mw;We.Writable=$h();We.Duplex=oi();We.Transform=Zm();We.PassThrough=Qm();We.pipeline=ST;var{addAbortSignal:f4}=Bd();We.addAbortSignal=f4;We.finished=AT;We.destroy=d4;We.compose=c4;We.setDefaultHighWaterMark=a4;We.getDefaultHighWaterMark=u4;Ji(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return gw}});Ji(ST,ET,{__proto__:null,enumerable:!0,get(){return gw.pipeline}});Ji(AT,ET,{__proto__:null,enumerable:!0,get(){return gw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return s4.from(e.buffer,e.byteOffset,e.byteLength)}});var ww=oe((dj,yt)=>{"use strict";l();var Tt=yw(),l4=pw(),h4=Tt.Readable.destroy;yt.exports=Tt.Readable;yt.exports._uint8ArrayToBuffer=Tt._uint8ArrayToBuffer;yt.exports._isUint8Array=Tt._isUint8Array;yt.exports.isDisturbed=Tt.isDisturbed;yt.exports.isErrored=Tt.isErrored;yt.exports.isReadable=Tt.isReadable;yt.exports.Readable=Tt.Readable;yt.exports.Writable=Tt.Writable;yt.exports.Duplex=Tt.Duplex;yt.exports.Transform=Tt.Transform;yt.exports.PassThrough=Tt.PassThrough;yt.exports.addAbortSignal=Tt.addAbortSignal;yt.exports.finished=Tt.finished;yt.exports.destroy=Tt.destroy;yt.exports.destroy=h4;yt.exports.pipeline=Tt.pipeline;yt.exports.compose=Tt.compose;Object.defineProperty(Tt,"promises",{configurable:!0,enumerable:!0,get(){return l4}});yt.exports.Stream=Tt.Stream;yt.exports.default=yt.exports});var G_=oe((Lp,W_)=>{l();(function(t,e){typeof Lp=="object"&&typeof W_<"u"?e(Lp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Lp,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]",Se="[\\x20]",Oe=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),gt="[\\:\\/\\?\\#\\[\\]\\@]",ve="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(gt,ve),mt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=B?"[\\uE000-\\uF8FF]":"[]",Te=e(v,K,"[\\-\\.\\_\\~]",mt),rt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(Oe+"|"+e(Te,ve,"[\\:]"))+"*"),ls=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Sr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Gr=r(Sr+"\\."+Sr+"\\."+Sr+"\\."+Sr),$e=r(te+"{1,4}"),Ar=r(r($e+"\\:"+$e)+"|"+Gr),zr=r(r($e+"\\:")+"{6}"+Ar),Pn=r("\\:\\:"+r($e+"\\:")+"{5}"+Ar),hs=r(r($e)+"?\\:\\:"+r($e+"\\:")+"{4}"+Ar),yi=r(r(r($e+"\\:")+"{0,1}"+$e)+"?\\:\\:"+r($e+"\\:")+"{3}"+Ar),mu=r(r(r($e+"\\:")+"{0,2}"+$e)+"?\\:\\:"+r($e+"\\:")+"{2}"+Ar),If=r(r(r($e+"\\:")+"{0,3}"+$e)+"?\\:\\:"+$e+"\\:"+Ar),Bf=r(r(r($e+"\\:")+"{0,4}"+$e)+"?\\:\\:"+Ar),Ic=r(r(r($e+"\\:")+"{0,5}"+$e)+"?\\:\\:"+$e),Bc=r(r(r($e+"\\:")+"{0,6}"+$e)+"?\\:\\:"),gi=r([zr,Pn,hs,yi,mu,If,Bf,Ic,Bc].join("|")),Rc=r(r(Te+"|"+Oe)+"+"),iy=r(gi+"\\%25"+Rc),ps=r(gi+r("\\%25|\\%(?!"+te+"{2})")+Rc),lB=r("[vV]"+te+"+\\."+e(Te,ve,"[\\:]")+"+"),hB=r("\\["+r(ps+"|"+gi+"|"+lB)+"\\]"),fx=r(r(Oe+"|"+e(Te,ve))+"*"),wu=r(hB+"|"+Gr+"(?!"+fx+")|"+fx),bu=r(K+"*"),lx=r(r(Ne+"@")+"?"+wu+r("\\:"+bu)+"?"),xu=r(Oe+"|"+e(Te,ve,"[\\:\\@]")),pB=r(xu+"*"),hx=r(xu+"+"),yB=r(r(Oe+"|"+e(Te,ve,"[\\@]"))+"+"),mi=r(r("\\/"+pB)+"*"),Uc=r("\\/"+r(hx+mi)+"?"),oy=r(yB+mi),Rf=r(hx+mi),Oc="(?!"+xu+")",PL=r(mi+"|"+Uc+"|"+oy+"|"+Rf+"|"+Oc),Dc=r(r(xu+"|"+e("[\\/\\?]",Ze))+"*"),Eu=r(r(xu+"|[\\/\\?]")+"*"),px=r(r("\\/\\/"+lx+mi)+"|"+Uc+"|"+Rf+"|"+Oc),gB=r(rt+"\\:"+px+r("\\?"+Dc)+"?"+r("\\#"+Eu)+"?"),mB=r(r("\\/\\/"+lx+mi)+"|"+Uc+"|"+oy+"|"+Oc),wB=r(mB+r("\\?"+Dc)+"?"+r("\\#"+Eu)+"?"),ML=r(gB+"|"+wB),KL=r(rt+"\\:"+px+r("\\?"+Dc)+"?"),$L="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+wu+")"+r("\\:("+bu+")")+"?)")+"?("+mi+"|"+Uc+"|"+Rf+"|"+Oc+")")+r("\\?("+Dc+")")+"?"+r("\\#("+Eu+")")+"?$",HL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+wu+")"+r("\\:("+bu+")")+"?)")+"?("+mi+"|"+Uc+"|"+oy+"|"+Oc+")")+r("\\?("+Dc+")")+"?"+r("\\#("+Eu+")")+"?$",VL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+wu+")"+r("\\:("+bu+")")+"?)")+"?("+mi+"|"+Uc+"|"+Rf+"|"+Oc+")")+r("\\?("+Dc+")")+"?$",qL="^"+r("\\#("+Eu+")")+"?$",FL="^"+r("("+Ne+")@")+"?("+wu+")"+r("\\:("+bu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Te,ve),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Te,ve),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Te,ve),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Te,ve),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Te,ve,"[\\:\\@\\/\\?]",Ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Te,ve,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Te,ve),"g"),UNRESERVED:new RegExp(Te,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Te,tt),"g"),PCT_ENCODED:new RegExp(Oe,"g"),IPV4ADDRESS:new RegExp("^("+Gr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+gi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Rc+")")+"?\\]?$")}}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 Se=v[Symbol.iterator](),Oe;!(H=(Oe=Se.next()).done)&&(K.push(Oe.value),!(k&&K.length===k));H=!0);}catch(gt){te=!0,fe=gt}finally{try{!H&&Se.return&&Se.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,x=38,S=700,_=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 I(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=I(H,v).join(".");return K+te}function E(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+x))},C=function(v){var k=[],K=v.length,H=0,te=A,fe=_,Se=v.lastIndexOf(O);Se<0&&(Se=0);for(var Oe=0;Oe<Se;++Oe)v.charCodeAt(Oe)>=128&&G("not-basic"),k.push(v.charCodeAt(Oe));for(var gt=Se>0?Se+1:0;gt<K;){for(var ve=H,tt=1,mt=p;;mt+=p){gt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(gt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Te=mt<=fe?g:mt>=fe+y?y:mt-fe;if(Ze<Te)break;var rt=p-Te;tt>X(h/rt)&&G("overflow"),tt*=rt}var Ne=k.length+1;fe=R(H-ve,Ne,ve==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=E(v);var K=v.length,H=A,te=0,fe=_,Se=!0,Oe=!1,gt=void 0;try{for(var ve=v[Symbol.iterator](),tt;!(Se=(tt=ve.next()).done);Se=!0){var mt=tt.value;mt<128&&k.push(Q(mt))}}catch(ps){Oe=!0,gt=ps}finally{try{!Se&&ve.return&&ve.return()}finally{if(Oe)throw gt}}var Ze=k.length,Te=Ze;for(Ze&&k.push(O);Te<K;){var rt=h,Ne=!0,ls=!1,Sr=void 0;try{for(var Gr=v[Symbol.iterator](),$e;!(Ne=($e=Gr.next()).done);Ne=!0){var Ar=$e.value;Ar>=H&&Ar<rt&&(rt=Ar)}}catch(ps){ls=!0,Sr=ps}finally{try{!Ne&&Gr.return&&Gr.return()}finally{if(ls)throw Sr}}var zr=Te+1;rt-H>X((h-te)/zr)&&G("overflow"),te+=(rt-H)*zr,H=rt;var Pn=!0,hs=!1,yi=void 0;try{for(var mu=v[Symbol.iterator](),If;!(Pn=(If=mu.next()).done);Pn=!0){var Bf=If.value;if(Bf<H&&++te>h&&G("overflow"),Bf==H){for(var Ic=te,Bc=p;;Bc+=p){var gi=Bc<=fe?g:Bc>=fe+y?y:Bc-fe;if(Ic<gi)break;var Rc=Ic-gi,iy=p-gi;k.push(Q(N(gi+Rc%iy,0))),Ic=X(Rc/iy)}k.push(Q(N(Ic,0))),fe=R(te,zr,Te==Ze),te=0,++Te}}}catch(ps){hs=!0,yi=ps}finally{try{!Pn&&mu.return&&mu.return()}finally{if(hs)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:E,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),Se=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|Se&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 Ue(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(),Se=d(fe,2),Oe=Se[0],gt=Se[1],ve=gt?gt.split(":").map(ee):[],tt=Oe.split(":").map(ee),mt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=mt?7:8,Te=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=ve[Ne]||tt[Te+Ne]||"";mt&&(rt[Ze-1]=ce(rt[Ze-1],v));var ls=rt.reduce(function(zr,Pn,hs){if(!Pn||Pn==="0"){var yi=zr[zr.length-1];yi&&yi.index+yi.length===hs?yi.length++:zr.push({index:hs,length:1})}return zr},[]),Sr=ls.sort(function(zr,Pn){return Pn.length-zr.length})[0],Gr=void 0;if(Sr&&Sr.length>1){var $e=rt.slice(0,Sr.index),Ar=rt.slice(Sr.index+Sr.length);Gr=$e.join(":")+"::"+Ar.join(":")}else Gr=rt.join(":");return te&&(Gr+="%"+te),Gr}else return B}var Ke=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function bt(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(Ke);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=Ue(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(Ue(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 ho=/^\.\.?\//,hu=/^\/\.(\/|$)/,Ef=/^\/\.\.(\/|$)/,ty=/^\/?(?:.|\n)*?(?=\/|$)/;function po(B){for(var v=[];B.length;)if(B.match(ho))B=B.replace(ho,"");else if(B.match(hu))B=B.replace(hu,"/");else if(B.match(Ef))B=B.replace(Ef,"/"),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(Se){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Se}}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=po(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 pu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=bt(jr(B,k),k),v=bt(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=po(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=po(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=po(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=po(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 vf(B,v,k){var K=s({scheme:"null"},k);return jr(pu(bt(B,K),bt(v,K),K,!0),K)}function yu(B,v){return typeof B=="string"?B=jr(bt(B,v),v):n(B)==="object"&&(B=bt(jr(B,v),v)),B}function Sf(B,v,k){return typeof B=="string"?B=jr(bt(B,k),k):n(B)==="object"&&(B=jr(B,k)),typeof v=="string"?v=jr(bt(v,k),k):n(v)==="object"&&(v=jr(v,k)),B===v}function Af(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 yo={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}},gu={scheme:"https",domainHost:yo.domainHost,parse:yo.parse,serialize:yo.serialize};function Tf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var fs={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=Tf(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===(Tf(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}},_f={scheme:"wss",domainHost:fs.domainHost,parse:fs.parse,serialize:fs.serialize},ry={},tB=!0,sx="[A-Za-z0-9\\-\\.\\_\\~"+(tB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Ln="[0-9A-Fa-f]",rB=r(r("%[EFef]"+Ln+"%"+Ln+Ln+"%"+Ln+Ln)+"|"+r("%[89A-Fa-f]"+Ln+"%"+Ln+Ln)+"|"+r("%"+Ln+Ln)),nB="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",iB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",oB=e(iB,'[\\"\\\\]'),sB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",cB=new RegExp(sx,"g"),_c=new RegExp(rB,"g"),aB=new RegExp(e("[^]",nB,"[\\.]",'[\\"]',oB),"g"),cx=new RegExp(e("[^]",sx,sB),"g"),uB=cx;function ny(B){var v=Z(B);return v.match(cB)?v:B}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={},Se=K.query.split("&"),Oe=0,gt=Se.length;Oe<gt;++Oe){var ve=Se[Oe].split("=");switch(ve[0]){case"to":for(var tt=ve[1].split(","),mt=0,Ze=tt.length;mt<Ze;++mt)H.push(tt[mt]);break;case"subject":K.subject=Wr(ve[1],k);break;case"body":K.body=Wr(ve[1],k);break;default:te=!0,fe[Wr(ve[0],k)]=Wr(ve[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Te=0,rt=H.length;Te<rt;++Te){var Ne=H[Te].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(ls){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ls}H[Te]=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 Se=String(H[te]),Oe=Se.lastIndexOf("@"),gt=Se.slice(0,Oe).replace(_c,ny).replace(_c,i).replace(aB,Y),ve=Se.slice(Oe+1);try{ve=k.iri?z.toUnicode(ve):z.toASCII(Wr(ve,k).toLowerCase())}catch(Te){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Te}H[te]=gt+"@"+ve}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var mt=[];for(var Ze in tt)tt[Ze]!==ry[Ze]&&mt.push(Ze.replace(_c,ny).replace(_c,i).replace(cx,Y)+"="+tt[Ze].replace(_c,ny).replace(_c,i).replace(uB,Y));return mt.length&&(K.query=mt.join("&")),K}},dB=/^([^\:]+)\:(.*)/,ux={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(dB),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),Se=K[2],Oe=te+":"+(k.nid||fe),gt=W[Oe];H.nid=fe,H.nss=Se,H.path=void 0,gt&&(H=gt.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 Se=v,Oe=v.nss;return Se.path=(H||k.nid)+":"+Oe,Se}},fB=/^[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(fB))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[yo.scheme]=yo,W[gu.scheme]=gu,W[fs.scheme]=fs,W[_f.scheme]=_f,W[ax.scheme]=ax,W[ux.scheme]=ux,W[dx.scheme]=dx,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=bt,t.removeDotSegments=po,t.serialize=jr,t.resolveComponents=pu,t.resolve=vf,t.normalize=yu,t.equal=Sf,t.escapeComponent=Af,t.unescapeComponent=Wr,Object.defineProperty(t,"__esModule",{value:!0})})});var Y_=oe((LZ,z_)=>{"use strict";l();z_.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 aI=oe((KQ,cI)=>{l();var nu=1e3,iu=nu*60,ou=iu*60,xc=ou*24,zC=xc*7,YC=xc*365.25;cI.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return JC(t);if(r==="number"&&isFinite(t))return e.long?XC(t):ZC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function JC(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*YC;case"weeks":case"week":case"w":return r*zC;case"days":case"day":case"d":return r*xc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ou;case"minutes":case"minute":case"mins":case"min":case"m":return r*iu;case"seconds":case"second":case"secs":case"sec":case"s":return r*nu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function ZC(t){var e=Math.abs(t);return e>=xc?Math.round(t/xc)+"d":e>=ou?Math.round(t/ou)+"h":e>=iu?Math.round(t/iu)+"m":e>=nu?Math.round(t/nu)+"s":t+"ms"}function XC(t){var e=Math.abs(t);return e>=xc?Hp(t,e,xc,"day"):e>=ou?Hp(t,e,ou,"hour"):e>=iu?Hp(t,e,iu,"minute"):e>=nu?Hp(t,e,nu,"second"):t+" ms"}function Hp(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var LL={};vu(LL,{AggregateBeaconError:()=>U0,Appendix:()=>ot,BECH32M_CHARS:()=>TL,BTCR2_DID_DOCUMENT_CONTEXT:()=>jI,BeaconError:()=>Yt,BeaconFactory:()=>Ms,BeaconSignalDiscovery:()=>Qb,BeaconUtils:()=>Fr,CASBeacon:()=>zu,CASBeaconError:()=>O0,CHANGE_OUTPUT_VBYTES:()=>L0,DEFAULT_FEE_ESTIMATOR:()=>Dl,DEFAULT_MIN_CONF:()=>QI,DID_REGEX:()=>WI,DUST_LIMIT_SATS:()=>P0,DidBtcr2:()=>bf,DidDocument:()=>qr,DidDocumentBuilder:()=>ox,DidVerificationMethod:()=>ey,GenesisDocument:()=>du,ID_PLACEHOLDER_VALUE:()=>rr,Identifier:()=>fr,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>Tc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Ac,P2PKH_BEACON_TX_VSIZE:()=>Ov,P2TR_BEACON_TX_VSIZE:()=>Rv,P2WPKH_BEACON_TX_VSIZE:()=>Uv,Resolver:()=>lo,SINGLETON_BEACON_TX_VSIZE:()=>Dv,SMTBeacon:()=>rd,SMTBeaconError:()=>na,SPENDABLE_DUST_LIMIT_SATS:()=>kl,SinglePartyBeacon:()=>Ci,SingletonBeacon:()=>Yu,SingletonBeaconError:()=>R0,StaticFeeEstimator:()=>ia,Updater:()=>wf,beaconTxVsize:()=>M0,buildAggregationBeaconTx:()=>i6,deriveSingletonAddress:()=>kv,detectSingletonScriptKind:()=>K0,extractOpReturnSignalHash:()=>Xb,getAggregationCommunicationKey:()=>eB,isMultikeyVerificationMethod:()=>GI,opReturnScript:()=>H0,resolveBtcr2SenderPk:()=>CL,resolveChangeAddress:()=>$0,selectSpendableUtxo:()=>Cv});l();l();l();l();var ws=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Su(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function pn(t,...e){if(!bs(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 Cf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Su(t.outputLen),Su(t.blockLen)}function Pc(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){pn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function qn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Lf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function yn(t,e){return t<<32-e|t>>>e}function Au(t,e){return t<<e|t>>>32-e>>>0}var Mx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pt(t){if(pn(t),Mx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=i8[t[r]];return e}var vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lx(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 _r(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 xs(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Tu(t){return typeof t=="string"&&(t=xs(t)),pn(t),t}function ft(...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 Lc=class{};function Pf(t){let e=n=>t().update(Tu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ir(t=32){if(ws&&typeof ws.getRandomValues=="function")return ws.getRandomValues(new Uint8Array(t));if(ws&&typeof ws.randomBytes=="function")return Uint8Array.from(ws.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function o8(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 Mc=class extends Lc{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=Lf(this.buffer)}update(e){Pc(this),e=Tu(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=Lf(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){Pc(this),Px(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,qn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;o8(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Lf(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 s8=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]),go=new Uint32Array(64),by=class extends Mc{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)go[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=go[f-15],p=go[f-2],g=yn(h,7)^yn(h,18)^h>>>3,y=yn(p,17)^yn(p,19)^p>>>10;go[f]=y+go[f-7]+g+go[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)+s8[f]+go[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(){qn(go)}destroy(){this.set(0,0,0,0,0,0,0,0),qn(this.buffer)}};var ke=Pf(()=>new by);l();l();l();var Mf=class extends Lc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Cf(e);let n=Tu(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),qn(o)}update(e){return Pc(this),this.iHash.update(e),this}digestInto(e){Pc(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 Mf(t,e).update(r).digest();xy.create=(t,e)=>new Mf(t,e);l();var Sy=BigInt(0),vy=BigInt(1);function _u(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function mo(t,e,r=""){let n=bs(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 Iu(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 Ai(t){return Kx(Pt(t))}function Ay(t){return pn(t),Kx(Pt(Uint8Array.from(t).reverse()))}function Kc(t,e){return _r(t.toString(16).padStart(e*2,"0"))}function Ty(t,e){return Kc(t,e).reverse()}function st(t,e,r){let n;if(typeof e=="string")try{n=_r(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(bs(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 wo(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 Kf(t){let e;for(e=0;t>Sy;t>>=vy,e+=1);return e}var bo=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 ft(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Ru(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 nr=BigInt(0),Ft=BigInt(1),Es=BigInt(2),Fx=BigInt(3),jx=BigInt(4),Wx=BigInt(5),c8=BigInt(7),Gx=BigInt(8),a8=BigInt(9),zx=BigInt(16);function Br(t,e){let r=t%e;return r>=nr?r:e+r}function Rr(t,e,r){let n=t;for(;e-- >nr;)n*=n,n%=r;return n}function Vx(t,e){if(t===nr)throw new Error("invert: expected non-zero number");if(e<=nr)throw new Error("invert: expected positive modulus, got "+e);let r=Br(t,e),n=e,i=nr,o=Ft,s=Ft,c=nr;for(;r!==nr;){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!==Ft)throw new Error("invert: does not exist");return Br(i,e)}function Iy(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+Ft)/jx,n=t.pow(e,r);return Iy(t,n,e),n}function u8(t,e){let r=(t.ORDER-Wx)/Gx,n=t.mul(e,Es),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,Es),i),c=t.mul(o,t.sub(s,t.ONE));return Iy(t,c,e),c}function d8(t){let e=xo(t),r=Jx(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+c8)/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),x=c.cmov(u,d,y);return Iy(c,x,a),x}}function Jx(t){if(t<Fx)throw new Error("sqrt is not defined for small field");let e=t-Ft,r=0;for(;e%Es===nr;)e/=Es,r++;let n=Es,i=xo(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+Ft)/Es;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 x=Ft<<BigInt(d-g-1),S=a.pow(f,x);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function f8(t){return t%jx===Fx?Yx:t%Gx===Wx?u8:t%zx===a8?d8(t):Jx(t)}var l8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function By(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=l8.reduce((n,i)=>(n[i]="function",n),e);return Ru(t,r),t}function h8(t,e,r){if(r<nr)throw new Error("invalid exponent, negatives unsupported");if(r===nr)return t.ONE;if(r===Ft)return e;let n=t.ONE,i=e;for(;r>nr;)r&Ft&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ft;return n}function $f(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-Ft)/Es,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 Hf(t,e){e!==void 0&&Su(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function xo(t,e,r=!1,n={}){if(t<=nr)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}=Hf(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:bo(a),ZERO:nr,ONE:Ft,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 nr<=h&&h<t},is0:h=>h===nr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ft)===Ft,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)=>h8(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=f8(t)),d(f,h))),toBytes:h=>r?Ty(h,u):Kc(h,u),fromBytes:(h,p=!0)=>{if(c){if(!c.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+h.length);let y=new Uint8Array(u);y.set(h,r?0:y.length-h.length),h=y}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let g=r?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=>$f(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 Vf(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):Ai(t),c=Br(s,e-Ft)+Ft;return r?Ty(c,i):Kc(c,i)}var $c=BigInt(0),vs=BigInt(1);function Uu(t,e){let r=e.negate();return t?r:e}function Ff(t,e){let r=$f(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=bo(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+=vs);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 p8(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 y8(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!==$c)throw new Error("invalid wNAF")}var qf=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>$c;)r&vs&&(n=n.add(i)),i=i.double(),r>>=vs;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(Uu(h,r[p])):i=i.add(Uu(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!==$c;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>$c||n>$c;)r&vs&&(o=o.add(i)),n&vs&&(s=s.add(i)),i=i.double(),r>>=vs,n>>=vs;return{p1:o,p2:s}}function iE(t,e,r,n){p8(r,t),y8(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=Kf(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=bo(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 x=n[y],S=Number(x>>BigInt(p)&u);d[S]=d[S].add(r[y])}let g=s;for(let y=d.length-1,x=s;y>0;y--)x=x.add(d[y]),g=g.add(x);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 By(e),e}else return xo(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>$c))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 g8(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<_i,h=d<_i;f&&(u=-u),h&&(d=-d);let p=bo(Math.ceil(Kf(r)/2))+Hc;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 _u(r.lowS,"lowS"),_u(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=Iu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Iu(i.length/2|128):"";return Iu(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=Iu(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=st("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),Hc=BigInt(1),cE=BigInt(2),jf=BigInt(3),m8=BigInt(4);function Eo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=st("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 w8(t,e={}){let r=oE("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ru(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,I,D){let{x:E,y:U}=I.toAffine(),L=n.toBytes(E);if(_u(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ft(aE(N),L)}else return ft(Uint8Array.of(4),L,n.toBytes(U))}function h(G){mo(G,void 0,"Point");let{publicKey:I,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===I&&(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(E===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!x(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${E}, expected compressed=${I} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let I=n.sqr(G),D=n.mul(I,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function x(G,I){let D=n.sqr(I),E=y(G);return n.eql(D,E)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,jf),m8),_=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function A(G,I,D=!1){if(!n.isValid(I)||D&&n.is0(I))throw new Error(`bad point coordinate ${G}`);return I}function O(G){if(!(G instanceof $))throw new Error("ProjectivePoint expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return g8(G,a.basises,i.ORDER)}let M=_y((G,I)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();I==null&&(I=L?n.ONE:n.inv(U));let N=n.mul(D,I),R=n.mul(E,I),C=n.mul(U,I);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:I,y:D}=G.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!x(I,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,I,D,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),I=Uu(E,I),D=Uu(U,D),I.add(D)}class ${constructor(I,D,E){this.X=A("x",I),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:D,y:E}=I||{};if(!I||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(I instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(I){let D=$.fromAffine(g(mo(I,void 0,"point")));return D.assertValidity(),D}static fromHex(I){return $.fromBytes(st("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,D=!0){return Q.createCache(this,I),D||this.multiply(jf),this}assertValidity(){q(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(E,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:D}=o,E=n.mul(D,jf),{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(I,P),C=n.mul(E,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(E,P),z=n.mul(I,z),W=n.sub(V,z),W=n.mul(I,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(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,jf),W=n.mul(D,L),Y=n.mul(E,N),Z=n.mul(U,R),ue=n.add(D,E),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(E,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(I){return this.add(I.negate())}is0(){return this.equals($.ZERO)}multiply(I){let{endo:D}=e;if(!i.isValidNot0(I))throw new Error("invalid scalar: out of range");let E,U,L=N=>Q.cached(this,N,R=>Ff($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(I),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(I);E=N,U=R}return Ff($,[E,U])[0]}multiplyUnsafe(I){let{endo:D}=e,E=this;if(!i.isValid(I))throw new Error("invalid scalar: out of range");if(I===_i||E.is0())return $.ZERO;if(I===Hc)return E;if(Q.hasCache(this))return this.multiply(I);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(I),{p1:C,p2:P}=nE($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,I)}multiplyAndAddUnsafe(I,D,E){let U=this.multiplyUnsafe(D).add(I.multiplyUnsafe(E));return U.is0()?void 0:U}toAffine(I){return M(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===Hc?!0:I?I($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===Hc?this:I?I($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return _u(I,"isCompressed"),this.assertValidity(),p($,this,I)}toHex(I=!0){return Pt(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Ff($,I)}static msm(I,D){return iE($,i,I,D)}static fromPrivateKey(I){return $.BASE.multiply(Eo(i,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 qf($,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 b8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ir,i=Object.assign(uE(t.Fp,r),{seed:Ry(r.ORDER)});function o(p){try{return!!Eo(r,p)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:x}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==x?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Vf(mo(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(Eo(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:x}=i;if(r.allowedLengths||g===y)return;let S=st("key",p).length;return S===y||S===x}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 x=Eo(r,p);return t.fromHex(g).multiply(x).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=>Eo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function x8(t,e,r={}){Cf(e),Ru(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Ir,i=r.hmac||((D,...E)=>xy(e,D,ft(...E))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=b8(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function x(D){let E=c>>Hc;return D>E}function S(D,E){if(!s.isValidNot0(E))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return E}function _(D,E){Ny(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return mo(D,L,`${E} signature`)}class A{constructor(E,U,L){this.r=S("r",E),this.s=S("s",U),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(E,U=y){_(E,U);let L;if(U==="der"){let{r:P,s:V}=Ti.toSig(mo(E));return new A(P,V)}U==="recovered"&&(L=E[0],U="compact",E=E.subarray(1));let N=s.BYTES,R=E.subarray(0,N),C=E.subarray(N,N*2);return new A(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(E,U){return this.fromBytes(_r(E),U)}addRecoveryBit(E){return new A(this.r,this.s,E)}recoverPublicKey(E){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(ft(aE((R&1)===0),V)),z=s.inv(P),W=T(st("msgHash",E)),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 x(this.s)}toBytes(E=y){if(Ny(E),E==="der")return _r(Ti.hexFromSig(this));let U=s.toBytes(this.r),L=s.toBytes(this.s);if(E==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ft(Uint8Array.of(this.recovery),U,L)}return ft(U,L)}toHex(E){return Pt(this.toBytes(E))}assertValidity(){}static fromCompact(E){return A.fromBytes(st("sig",E),"compact")}static fromDER(E){return A.fromBytes(st("sig",E),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Pt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Pt(this.toBytes("compact"))}}let O=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=Ai(E),L=E.length*8-a;return L>0?U>>BigInt(L):U},T=r.bits2int_modN||function(E){return s.create(O(E))},M=bo(a);function q(D){return $x("num < 2^"+a,D,_i,M),s.toBytes(D)}function j(D,E){return mo(D,void 0,"message"),E?mo(e(D),void 0,"prehashed message"):D}function $(D,E,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=Eo(s,E),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(st("extraEntropy",Y))}let J=ft(...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 Ue=s.create(ue*s.create(z+ce*P));if(Ue===_i)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&Hc),Je=Ue;return L&&x(Ue)&&(Je=s.neg(Ue),Ke^=1),new A(ce,Je,Ke)}return{seed:J,k2sig:W}}function X(D,E,U={}){D=st("message",D);let{seed:L,k2sig:N}=$(D,E,U);return Hx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let E,U=typeof D=="string"||bs(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)E=new A(D.r,D.s);else if(U){try{E=A.fromBytes(st("sig",D),"der")}catch(N){if(!(N instanceof Ti.Err))throw N}if(!E)try{E=A.fromBytes(st("sig",D),"compact")}catch{return!1}}return E||!1}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=ky(L,g);if(U=st("publicKey",U),E=j(st("message",E),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(st("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(E),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 I(D,E,U={}){let{prehash:L}=ky(U,g);return E=j(E,L),A.fromBytes(D,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:X,verify:G,recoverPublicKey:I,Signature:A,hash:e})}function E8(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=xo(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 v8(t){let{CURVE:e,curveOpts:r}=E8(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function S8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Hf(r.Fn.ORDER,r.Fn.BITS))})}function dE(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=v8(t),o=w8(e,r),s=x8(o,n,i);return S8(t,s)}function fE(t,e){let r=n=>dE({...t,hash:n});return{...r(e),create:r}}var Vc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},A8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},T8=BigInt(0),lE=BigInt(1),Ly=BigInt(2);function _8(t){let e=Vc.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=Rr(d,r,e)*d%e,h=Rr(f,r,e)*d%e,p=Rr(h,Ly,e)*u%e,g=Rr(p,i,e)*p%e,y=Rr(g,o,e)*g%e,x=Rr(y,c,e)*y%e,S=Rr(x,a,e)*x%e,_=Rr(S,c,e)*y%e,A=Rr(_,r,e)*d%e,O=Rr(A,s,e)*g%e,T=Rr(O,n,e)*u%e,M=Rr(T,Ly,e);if(!Wf.eql(Wf.sqr(M),t))throw new Error("Cannot find square root");return M}var Wf=xo(Vc.p,{sqrt:_8}),vo=fE({...Vc,Fp:Wf,lowS:!0,endo:A8},ke),hE={};function Gf(t,...e){let r=hE[t];if(r===void 0){let n=ke(xs(t));r=ft(n,n),hE[t]=r}return ke(ft(r,...e))}var My=t=>t.toBytes(!0).slice(1),qc=vo.Point,Ky=t=>t%Ly===T8;function Py(t){let{Fn:e,BASE:r}=qc,n=Eo(e,t),i=r.multiply(n);return{scalar:Ky(i.y)?n:e.neg(n),bytes:My(i)}}function yE(t){let e=Wf;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=qc.fromAffine({x:t,y:i});return o.assertValidity(),o}var Ou=Ai;function gE(...t){return qc.Fn.create(Ou(Gf("BIP0340/challenge",...t)))}function pE(t){return Py(t).bytes}function I8(t,e,r=Ir(32)){let{Fn:n}=qc,i=st("message",t),{bytes:o,scalar:s}=Py(e),c=st("auxRand",r,32),a=n.toBytes(s^Ou(Gf("BIP0340/aux",c))),u=Gf("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}=qc,o=st("signature",t,64),s=st("message",e),c=st("publicKey",r,32);try{let a=yE(Ou(c)),u=Ou(o.subarray(0,32));if(!Bu(u,lE,Vc.p))return!1;let d=Ou(o.subarray(32,64));if(!Bu(d,lE,Vc.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 Ur=(()=>{let r=(i=Ir(48))=>Vf(i,Vc.n);vo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:pE(o)}}return{keygen:n,getPublicKey:pE,sign:I8,verify:mE,Point:qc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Gf,lift_x:yE,pointToBytes:My,numberToBytesBE:Kc,bytesToNumberBE:Ai,mod:Br},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var B8=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)),R8=bE.map(t=>(9*t+5)%16),xE=(()=>{let r=[[bE],[R8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>B8[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)),U8=EE.map((t,e)=>t.map(r=>SE[e][r])),O8=vE.map((t,e)=>t.map(r=>SE[e][r])),D8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),k8=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 zf=new Uint32Array(16),$y=class extends Mc{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)zf[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=D8[p],x=k8[p],S=EE[p],_=vE[p],A=U8[p],O=O8[p];for(let T=0;T<16;T++){let M=Au(n+wE(p,o,c,u)+zf[S[T]]+y,A[T])+f|0;n=f,f=u,u=Au(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=Au(i+wE(g,s,a,d)+zf[_[T]]+x,O[T])+h|0;i=h,h=d,d=Au(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(){qn(zf)}destroy(){this.destroyed=!0,qn(this.buffer),this.set(0,0,0,0,0)}},AE=Pf(()=>new $y);l();l();function Fc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function N8(t,...e){if(!Fc(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 jc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function ku(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Jf(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 Nu(...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 Xf(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=>(Jf(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=>(Jf(i),i.map(o=>{jc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Qf(t=""){return jc("join",t),{encode:e=>(UE("join.decode",e),e.join(t)),decode:e=>(jc("join.decode",e),e.split(t))}}function C8(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(Jf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(ku(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),Zf=(t,e)=>t+(e-OE(t,e)),Yf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Hy(t,e,r,n){if(Jf(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(Zf(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Zf(e,r)}`);let i=0,o=0,s=Yf[e],c=Yf[r]-1,a=[];for(let u of t){if(ku(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=Yf[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 L8(t){ku(t);let e=2**8;return{encode:r=>{if(!Fc(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(ku(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Zf(8,t)>32||Zf(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Fc(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 P8(t,e){return ku(t),qy(e),{encode(r){if(!Fc(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(!Fc(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 Wc=Nu(jy(6),Xf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Qf("")),M8=t=>Nu(L8(58),Xf(t),Qf("")),el=M8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var DE=t=>Nu(P8(4,e=>t(t(e))),el);var Vy=Nu(Xf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Qf("")),IE=[996825010,642813549,513874426,1027748829,705979059];function Du(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<IE.length;n++)(e>>n&1)===1&&(r^=IE[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=Du(i)^s>>5}i=Du(i);for(let o=0;o<n;o++)i=Du(i)^t.charCodeAt(o)&31;for(let o of e)i=Du(i)^o;for(let o=0;o<6;o++)i=Du(i);return i^=r,Vy.encode(Hy([i%Yf[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){jc("bech32.encode prefix",f),Fc(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 x=f.toLowerCase(),S=BE(x,h,e);return`${x}1${Vy.encode(h)}${S}`}function c(f,h=90){jc("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 x=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 _=Vy.decode(S).slice(0,-6),A=BE(x,_,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:x,words:_}}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 tl=kE("bech32"),Ss=kE("bech32m"),NE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},K8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$8={encode(t){return N8(t),t.toHex()},decode(t){return jc("hex",t),Uint8Array.fromHex(t)}},xe=K8?$8:Nu(jy(4),Xf("0123456789abcdef"),Qf(""),C8(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 Ve=new Uint8Array,Yy=new Uint8Array([0]);function Gc(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 H8(...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 zc(t){return Object.prototype.toString.call(t)==="[object Object]"}function Fn(t){return Number.isSafeInteger(t)}var rl={equalBytes:Gc,isBytes:Jr,isCoder:Or,checkBounds:LE,concatBytes:H8,createView:Jy,isPlainObject:zc},CE=t=>{if(t!==null&&typeof t!="string"&&!Or(t)&&!Jr(t)&&!Fn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Or(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Ii.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(Or(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Ii.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Ot={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ot.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(Ot.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ot.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)=>{Ot.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ot,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)=>`[${Ot.range(Ot.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ot.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ot,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 Ot.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ot.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(!Ot.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ot.set(t,u,o<<s-a%s,i))}},Ii={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}(${Ii.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=Ot.create(this.data.length),Ot.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:Ot.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 Ii.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: ${xe.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Ot.indices(this.bs,this.data.length,!0);if(e.length){let r=Ot.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${xe.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: ${xe.encode(this.data.slice(this.pos))}`)}}err(e){return Ii.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(Gc(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 Ii.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!Fn(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 Ii.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 jt(t,e){if(!Or(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 Wt=t=>{let e=PE(t);return t.validate?jt(e,t.validate):e},nl=t=>zc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Or(t){return zc(t)&&nl(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||Fn(t.size))}function V8(){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(!zc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var q8={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(!Fn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function F8(t){if(!zc(t))throw new Error("plain object expected");return{encode:e=>{if(!Fn(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 j8(t,e=!1){if(!Fn(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 W8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!nl(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(!nl(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Bi={dict:V8,numberBigint:q8,tsEnum:F8,decimal:j8,match:W8,reverse:ME};var Zy=(t,e=!1,r=!1,n=!0)=>{if(!Fn(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 Wt({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 Yc=Zy(8,!0);var $E=Zy(8,!0,!0);var G8=(t,e)=>Wt({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}}),Cu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!Fn(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(!Fn(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 G8(t,{write:r.write,read:r.read,validate:e?o:c})},_e=Cu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),HE=Cu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),So=Cu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Xy=Cu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var mn=Cu(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 Wt({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(!Or(e))throw new Error(`prefix: invalid inner value ${e}`);return gn(Fe(t),ME(e))}var il=(t,e=!1)=>jt(gn(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=gn(Fe(t,e.isLE),xe),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(!Or(t))throw new Error(`apply: invalid inner value ${t}`);if(!nl(e))throw new Error(`apply: invalid base value ${t}`);return Wt({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 Wt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=Gc(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(!Or(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Or(e))throw new Error(`flagged: wrong path=${t}`);return Wt({encodeStream:(n,i)=>{typeof t=="string"?Ii.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=!!Ii.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function ol(t,e,r=!0){if(!Or(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return Wt({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)&&!Gc(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(!Fn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function xt(t){if(!zc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Or(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return Wt({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(!Or(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return Wt({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 Gt(t,e){if(!Or(e))throw new Error(`array: invalid inner value ${e}`);let r=CE(typeof t=="string"?`../${t}`:t);return Wt({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(Gc(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(Gc(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 al=vo.ProjectivePoint,cl=vo.CURVE.n,Ce=rl.isBytes,jn=rl.concatBytes,ct=rl.equalBytes;var Jc=t=>AE(ke(t)),Ri=(...t)=>ke(ke(jn(...t))),dM=Ur.utils.randomPrivateKey,ul=Ur.getPublicKey,Qy=vo.getPublicKey,zE=t=>t.r<cl/2n;function YE(t,e,r=!1){let n=vo.sign(t,e);if(r&&!zE(n)){let i=new Uint8Array(32),o=0;for(;!zE(n);)if(i.set(_e.encode(o++)),n=vo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var e0=Ur.sign,Lu=Ur.utils.taggedHash,Et;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(Et||(Et={}));function Ao(t,e){let r=t.length;if(e===Et.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return al.fromHex(t),t}else if(e===Et.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Ur.utils.lift_x(Ur.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function JE(t,e){let r=Ur.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=cl)throw new Error("tweak higher than curve order");return i}function ZE(t,e=Uint8Array.of()){let r=Ur.utils,n=r.bytesToNumberBE(t),i=al.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,cl),s=r.pointToBytes(i),c=JE(s,e);return r.numberToBytesBE(r.mod(o+c,cl),32)}function Pu(t,e){let r=Ur.utils,n=JE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(al.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var dl=ke(al.BASE.toRawBytes(!1)),Zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},t0={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function Mu(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 wt;(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"})(wt||(wt={}));function r0(t=6,e=!1){return Wt({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=Wt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(wt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(wt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(wt.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<wt.PUSHDATA1?t.byte(n):n<=255?(t.byte(wt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(wt.PUSHDATA2),t.bytes(Xy.encode(n))):(t.byte(wt.PUSHDATA4),t.bytes(_e.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(wt.OP_0<r&&r<=wt.PUSHDATA4){let n;if(r<wt.PUSHDATA1)n=r;else if(r===wt.PUSHDATA1)n=mn.decodeStream(t);else if(r===wt.PUSHDATA2)n=Xy.decodeStream(t);else if(r===wt.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(wt.OP_1<=r&&r<=wt.OP_16)e.push(r-(wt.OP_1-1));else{let n=wt[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]},Zc=Wt({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}}),Dr=gn(Zc,Bi.numberBigint),hr=Fe(Zc),Xc=Gt(Dr,hr),fl=t=>Gt(Zc,t),tv=xt({txid:Fe(32,!0),index:_e,finalScriptSig:hr,sequence:_e}),Ui=xt({amount:Yc,script:hr}),z8=xt({version:So,segwitFlag:FE(new Uint8Array([0,1])),inputs:fl(tv),outputs:fl(Ui),witnesses:jE("segwitFlag",Gt("inputs/length",Xc)),lockTime:_e});function Y8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Oi=jt(z8,Y8),As=xt({version:So,inputs:fl(tv),outputs:fl(Ui),lockTime:_e});var i0=jt(Fe(null),t=>Ao(t,Et.ecdsa)),ll=jt(Fe(32),t=>Ao(t,Et.schnorr)),rv=jt(Fe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),hl=xt({fingerprint:HE,path:Gt(null,_e)}),ov=xt({hashes:Gt(Dr,Fe(32)),der:hl}),J8=Fe(78),Z8=xt({pubKey:ll,leafHash:Fe(32)}),X8=xt({version:mn,internalKey:Fe(32),merklePath:Gt(null,Fe(32))}),Di=jt(X8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),Q8=Gt(null,xt({depth:mn,version:mn,script:hr})),vt=Fe(null),nv=Fe(20),Ku=Fe(32),pl={unsignedTx:[0,!1,As,[0],[0],!1],xpub:[1,J8,hl,[],[0,2],!1],txVersion:[2,!1,_e,[2],[2],!1],fallbackLocktime:[3,!1,_e,[],[2],!1],inputCount:[4,!1,Dr,[2],[2],!1],outputCount:[5,!1,Dr,[2],[2],!1],txModifiable:[6,!1,mn,[],[2],!1],version:[251,!1,_e,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},$u={nonWitnessUtxo:[0,!1,Oi,[],[0,2],!1],witnessUtxo:[1,!1,Ui,[],[0,2],!1],partialSig:[2,i0,vt,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,vt,[],[0,2],!1],witnessScript:[5,!1,vt,[],[0,2],!1],bip32Derivation:[6,i0,hl,[],[0,2],!1],finalScriptSig:[7,!1,vt,[],[0,2],!1],finalScriptWitness:[8,!1,Xc,[],[0,2],!1],porCommitment:[9,!1,vt,[],[0,2],!1],ripemd160:[10,nv,vt,[],[0,2],!1],sha256:[11,Ku,vt,[],[0,2],!1],hash160:[12,nv,vt,[],[0,2],!1],hash256:[13,Ku,vt,[],[0,2],!1],txid:[14,!1,Ku,[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,Z8,rv,[],[0,2],!1],tapLeafScript:[21,Di,vt,[],[0,2],!1],tapBip32Derivation:[22,Ku,ov,[],[0,2],!1],tapInternalKey:[23,!1,ll,[],[0,2],!1],tapMerkleRoot:[24,!1,Ku,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},sv=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],cv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Hu={redeemScript:[0,!1,vt,[],[0,2],!1],witnessScript:[1,!1,vt,[],[0,2],!1],bip32Derivation:[2,i0,hl,[],[0,2],!1],amount:[3,!1,$E,[2],[2],!0],script:[4,!1,vt,[2],[2],!0],tapInternalKey:[5,!1,ll,[],[0,2],!1],tapTree:[6,!1,Q8,[],[0,2],!1],tapBip32Derivation:[7,ll,ov,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},av=[],iv=Gt(Yy,xt({key:VE(Dr,xt({type:Dr,key:Fe(null)})),value:Fe(Dr)}));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 wM=xt({type:Dr,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 Wt({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:Ve},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>Mu(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)=>Mu(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=${xe.encode(a)} value=${xe.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 yl=jt(s0($u),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)Ao(e,Et.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Ao(e,Et.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}),gl=jt(s0(Hu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Ao(e,Et.ecdsa);return t}),uv=jt(s0(pl),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}),eR=xt({magic:ol(il(new Uint8Array([255])),"psbt"),global:uv,inputs:Gt("global/unsignedTx/inputs/length",yl),outputs:Gt(null,gl)}),tR=xt({magic:ol(il(new Uint8Array([255])),"psbt"),global:uv,inputs:Gt("global/inputCount",yl),outputs:Gt("global/outputCount",gl)}),bM=xt({magic:ol(il(new Uint8Array([255])),"psbt"),items:Gt(null,gn(Gt(Yy,GE([qE(Dr),Fe(Zc)])),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,pl,t.global);for(let s of t.inputs)n0(e,$u,s);for(let s of t.outputs)n0(e,Hu,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 ml(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(x=>{if(x.length!==2)throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);return[typeof x[0]=="string"?u.decode(xe.decode(x[0])):x[0],typeof x[1]=="string"?d.decode(xe.decode(x[1])):x[1]]});let g={},y=(x,S,_)=>{if(g[x]===void 0){g[x]=[S,_];return}let A=xe.encode(d.encode(g[x][1])),O=xe.encode(d.encode(_));if(A!==O)throw new Error(`keyMap(${c}): same key=${x} oldVal=${A} newVal=${O}`)};for(let[x,S]of h){let _=xe.encode(u.encode(x));y(_,x,S)}for(let[x,S]of p){let _=xe.encode(u.encode(x));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${x}`);delete g[_]}else y(_,x,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(xe.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!ct(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=jt(eR,dv),u0=jt(tR,dv);var nR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||xe.encode(t[1])!=="4e73"))return{type:"p2a",script:Xe.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,xe.decode("4e73")]}};function To(t,e){try{return Ao(t,e),!0}catch{return!1}}var iR={encode(t){if(!(t.length!==2||!Ce(t[0])||!To(t[0],Et.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},oR={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},sR={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},cR={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},aR={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},uR={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},dR={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},fR={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}},lR={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}},hR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},pR=[nR,iR,oR,sR,cR,aR,uR,dR,fR,lR,hR],yR=gn(Xe,Bi.match(pR)),Qe=jt(yR,t=>{if(t.type==="pk"&&!To(t.pubkey,Et.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)||!To(t.pubkey,Et.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(!To(r,Et.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(!To(e,Et.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(!ct(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(!ct(n.hash,Jc(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 ki=(t,e=Zr)=>{if(!To(t,Et.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=Jc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Xr(e).encode({type:"pkh",hash:r}),hash:r}};var Ts=(t,e=Zr)=>{if(!To(t,Et.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=Jc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Xr(e).encode({type:"wpkh",hash:r}),hash:r}};function gR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=gn(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(ct(s,dl))throw new Error("Unspendable taproot key in leaf script");if(ct(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&&!ct(t.tapMerkleRoot,Ve))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?xe.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return gR(d,e,r,n),{type:"leaf",version:a,script:d,hash:Vu(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 Mu(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Lu("TapBranch",s,c)}}var p0=192,Vu=(t,e=p0)=>Lu("TapLeaf",new Uint8Array([e]),hr.encode(t));function _s(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"?xe.decode(t):t||dl;if(!To(o,Et.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=f0(h0(e,o,n,i)),c=s.hash,[a,u]=Pu(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),jn(f.script,new Uint8Array([f.version||p0]))]),tapMerkleRoot:c}}else{let s=Pu(o,Ve)[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?tl:Ss;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function lv(t,e){return pv.encode(jn(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=tl.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Ss.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=tl.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 wl=new Uint8Array(32),mR={amount:0xffffffffffffffffn,script:Ve},wR=t=>Math.ceil(t/4),bR=8,xR=2,Is=0,b0=4294967295,ER=Bi.decimal(bR),Fu=(t,e)=>t===void 0?e:t;function xl(t){if(Array.isArray(t))return t.map(e=>xl(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,xl(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 _o;(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"})(_o||(_o={}));function vR(t,e,r,n=Ve){return ct(r,e)&&(t=ZE(t,n),e=ul(t)),{privKey:t,pubKey:e}}function Bs(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 qu(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:Fu(t.sequence,b0),finalScriptSig:Fu(t.finalScriptSig,Ve)}}function g0(t){for(let e in t){let r=e;sv.includes(r)||delete t[r]}}var m0=xt({txid:Fe(32,!0),index:_e});function SR(t){if(typeof t!="number"||typeof _o[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 AR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Fu(t.version,xR),lockTime:Fu(t.lockTime,0),PSBTVersion:Fu(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&&(!ct(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=Rs.fromRaw(Oi.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=xe.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function bl(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=xe.decode(o)),Ce(o)&&(o=Oi.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=xe.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=ml($u,c,e,r,i),yl.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=bl(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 Rs=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=AR(e);r.lockTime!==Is&&(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)=>mv({finalScriptSig:Ve,...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!==Is&&(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,$u,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,Hu,o)),i={...this.global};return e===0?(i.unsignedTx=As.decode(As.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(qu).map(o=>({...o,finalScriptSig:Ve})),outputs:this.outputs.map(Bs)})),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===Is&&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=Is,r=0,n=Is,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!==Is?n:this.global.fallbackLocktime||Is}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(Bs);e+=4*Dr.encode(this.outputs.length).length;for(let n of r)e+=32+4*hr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Dr.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*hr.encode(n.finalScriptSig||Ve).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Xc.encode(n.finalScriptWitness).length);return e}get vsize(){return wR(this.weight)}toBytes(e=!1,r=!1){return Oi.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(qu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||Ve})),outputs:this.outputs.map(Bs),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return xe.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return xe.encode(Ri(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return xe.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),xl(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),xl(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=xe.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=ml(Hu,s,r,n,this.opts.allowUnknown),gl.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=bl(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Bs);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(qu).map((d,f)=>({...d,finalScriptSig:f===e?r:Ve}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Bs);o?a=[]:s&&(a=a.slice(0,e).fill(mR).concat([a[e]]));let u=Oi.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ri(u,So.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=gv(n),a=wl,u=wl,d=wl,f=this.inputs.map(qu),h=this.outputs.map(Bs);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(So.encode(this.version),a,u,Fe(32,!0).encode(p.txid),_e.encode(p.index),hr.encode(r),Yc.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),So.encode(this.version),_e.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(qu),p=this.outputs.map(Bs);f!==je.ANYONECANPAY&&u.push(...[h.map(m0.encode),i.map(Yc.encode),r.map(hr.encode),h.map(y=>_e.encode(y.sequence))].map(y=>ke(jn(...y)))),d===je.ALL&&u.push(ke(jn(...p.map(Ui.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),Yc.encode(i[e]),hr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(ke(hr.encode(a||Ve))),d===je.SINGLE&&u.push(e<p.length?ke(Ui.encode(p[e])):wl),s&&u.push(Vu(s,c),mn.encode(0),So.encode(o)),Lu("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(!ct(g.publicKey,h))throw new Error("bip32Derivation: wrong pubKey");if(!g.privateKey)throw new Error("bip32Derivation: no privateKey");return g});if(!d.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let f=!1;for(let h of d)this.signIdx(h.privateKey,r)&&(f=!0);return f}n?n.forEach(SR):n=[s.defaultSighash];let c=s.sighash;if(!n.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${n.join(", ")}`);let{sigOutputs:a}=this.inputSighash(r);if(a===je.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=bl(o);if(s.txType==="taproot"){let d=this.inputs.map(bl),f=d.map(x=>x.script),h=d.map(x=>x.amount),p=!1,g=ul(e),y=o.tapMerkleRoot||Ve;if(o.tapInternalKey){let{pubKey:x,privKey:S}=vR(e,g,o.tapInternalKey,y),[_,A]=Pu(o.tapInternalKey,y);if(ct(_,x)){let O=this.preimageWitnessV1(r,f,c,h),T=jn(e0(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[x,S]of o.tapLeafScript){let _=S.subarray(0,-1),A=Xe.decode(_),O=S[S.length-1],T=Vu(_,O);if(A.findIndex($=>Ce($)&&ct($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,_,O),j=jn(e0(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);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=Jc(d);for(let y of Xe.decode(s.lastScript))Ce(y)&&(ct(y,d)||ct(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,jn(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=Vu(f,h),y=r.tapScriptSig.filter(S=>ct(S[0].leafHash,g)),x=[];if(p.type==="tr_ms"){let S=p.m,_=p.pubkeys,A=0;for(let O of _){let T=y.findIndex(M=>ct(M[0].pubKey,O));if(A===S||T===-1){x.push(Ve);continue}x.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let _=y.findIndex(A=>ct(A[0].pubKey,S));_!==-1&&x.push(y[_][1])}if(x.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Xe.decode(f);if(x=y.map(([{pubKey:_},A])=>{let O=S.findIndex(T=>Ce(T)&&ct(T,_));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((_,A)=>_.pos-A.pos).map(_=>_.signature),!x.length)continue}else{let S=this.opts.customScripts;if(S)for(let _ of S){if(!_.finalizeTaproot)continue;let A=Xe.decode(f),O=_.encode(A);if(O===void 0)continue;let T=_.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Di.encode(u)),r.finalScriptSig=Ve,g0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=x.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=Ve,g0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=Ve,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=>ct(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=Ve,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 Ve;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?As.encode(this.global.unsignedTx):Ve,n=e.global.unsignedTx?As.encode(e.global.unsignedTx):Ve;if(!ct(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=ml(pl,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,_){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+_+"]")}),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.includes(_)||(g&&(r+=","),g=!0,r+=JSON.stringify(_),r+=":",u(d[_],f+"."+_))};if(f===""&&n)n.forEach(function(_){d.hasOwnProperty(_)&&y(_)});else{var x=Object.keys(d);c&&(x=x.filter(function(_){return d[_]!==void 0})),x.sort(),x.forEach(function(_){y(_)})}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",t.INVALID_OPTIONS="INVALID_OPTIONS"})(x0||(x0={}));var{INVALID_DID:Dt,METHOD_NOT_SUPPORTED:El,INTERNAL_ERROR:Ev,INVALID_DID_DOCUMENT:De,INVALID_DID_UPDATE:Ie,INVALID_DID_URL:aK,INVALID_PREVIOUS_DID_PROOF:uK,INVALID_PUBLIC_KEY:dK,INVALID_PUBLIC_KEY_MULTIBASE:fK,INVALID_PUBLIC_KEY_LENGTH:lK,INVALID_PUBLIC_KEY_TYPE:hK,INVALID_SIGNATURE:pK,PROOF_VERIFICATION_ERROR:Ni,PROOF_GENERATION_ERROR:Bo,PROOF_SERIALIZATION_ERROR:vv,PROOF_PARSING_ERROR:yK,VERIFICATION_METHOD_ERROR:vl,LATE_PUBLISHING_ERROR:Sl,INVALID_SIDECAR_DATA:gK,MISSING_UPDATE_DATA:mK,MISSING_RESOLUTION_OPTIONS:wK,INVALID_OPTIONS:Sv}=x0,zt=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 zt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var lt=class extends zt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},St=class extends zt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},Le=class extends zt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var qe=class extends zt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},Io=class extends zt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},wn=class extends zt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},bn=class extends zt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},Wn=class extends zt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Us=class extends zt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},xn=class extends zt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var Qc=class extends zt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var TR=new Set(["jcs"]),_R=new Set(["hex","base58","base64urlnopad"]);function E0(t){let e=t.toLowerCase();if(!TR.has(e))throw new Qc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function v0(t){let e=t.toLowerCase();if(!_R.has(e))throw new Qc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function ir(t,e="jcs"){switch(E0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return xv(n)}default:throw new Qc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function Ro(t){return ke(t)}function Qr(t,e="base64urlnopad"){switch(v0(e)){case"hex":return xe.encode(t);case"base58":return el.encode(t);case"base64urlnopad":return Wc.encode(t)}}function Os(t,e="base64urlnopad"){switch(v0(e)){case"hex":return xe.decode(t);case"base58":return el.decode(t);case"base64urlnopad":return Wc.decode(t)}}function Uo(t,e="jcs"){return Ro(ir(t,E0(e)))}function Gn(t,e){let r=E0(e?.algorithm??"jcs"),n=v0(e?.encoding??"base64urlnopad");return Qr(Ro(ir(t,r)),n)}l();l();var S0={};vu(S0,{JsonPatchError:()=>at,_areEquals:()=>Gu,applyOperation:()=>Ds,applyPatch:()=>Ul,applyReducer:()=>OR,deepClone:()=>RR,getValueByPointer:()=>Bl,validate:()=>Tv,validator:()=>Rl});l();l();var IR=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)}}(),BR=Object.prototype.hasOwnProperty;function Tl(t,e){return BR.call(t,e)}function _l(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)Tl(t,i)&&n.push(i);return n}function Mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Il(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 ju(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Al(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Al(t[e]))return!0}else if(typeof t=="object"){for(var n=_l(t),i=n.length,o=0;o<i;o++)if(Al(t[n[o]]))return!0}}return!1}function Av(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 Wu=function(t){IR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,Av(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=Av(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var at=Wu,RR=Mt,ea={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=Mt(n));var i=Ds(r,{op:"remove",path:this.from}).removed;return Ds(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=Bl(r,this.from);return Ds(r,{op:"add",path:this.path,value:Mt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Gu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},UR={add:function(t,e,r){return Il(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:ea.move,copy:ea.copy,test:ea.test,_get:ea._get};function Bl(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ds(t,r),r.value}function Ds(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):Rl(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=Gu(t,e.value),s.test===!1)throw new at("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 at("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Mt(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=Rl;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=ju(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&&!Il(p))throw new at("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);Il(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new at("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=UR[e.op].call(e,u,p,t);if(s.test===!1)throw new at("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=ea[e.op].call(e,u,p,t);if(s.test===!1)throw new at("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new at("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function Ul(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new at("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Mt(t));for(var o=new Array(e.length),s=0,c=e.length;s<c;s++)o[s]=Ds(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function OR(t,e,r){var n=Ds(t,e);if(n.test===!1)throw new at("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Rl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new at("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(ea[t.op]){if(typeof t.path!="string")throw new at("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new at('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 at("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 at("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")&&Al(t.value))throw new at("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 at("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 at("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=Tv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new at("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new at("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Tv(t,e,r){try{if(!Array.isArray(t))throw new at("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ul(Mt(e),Mt(t),r||!0);else{r=r||Rl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof at)return i;throw i}}function Gu(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(!Gu(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],!Gu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var I0={};vu(I0,{compare:()=>KR,generate:()=>A0,observe:()=>MR,unobserve:()=>PR});l();var T0=new WeakMap,DR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),kR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function NR(t){return T0.get(t)}function CR(t,e){return t.observers.get(e)}function LR(t,e){t.observers.delete(e.callback)}function PR(t,e){e.unobserve()}function MR(t,e){var r=[],n,i=NR(t);if(!i)i=new DR(t),T0.set(t,i);else{var o=CR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Mt(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),LR(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 kR(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&&Ul(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=_l(e),s=_l(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(Tl(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:Mt(f)}),r.push({op:"replace",path:n+"/"+zn(d),value:Mt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+zn(d),value:Mt(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];!Tl(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+zn(d),value:Mt(e[d])})}}}function KR(t,e,r){r===void 0&&(r=!1);var n=[];return _0(t,e,n,"",r),n}var _v=Object.assign({},S0,I0,{JsonPatchError:Wu,deepClone:Mt,escapePathComponent:zn,unescapePathComponent:ju});var{applyPatch:$R,compare:HR,deepClone:VR}=_v,qR=new Set(["__proto__","constructor","prototype"]);function Iv(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>qR.has(e))}var ta=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??VR,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=$R(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=HR(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=Iv(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=Iv(r.from);if(i)return new we(`Operation.from traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var en;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(en||(en={}));var Ol;(function(t){t.k="k",t.x="x"})(Ol||(Ol={}));var ra;(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"})(ra||(ra={}));l();var Oo=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),x=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],_=f%4===0&&f%100!==0||f%400===0,A=h===2&&_?29:S[h-1];if(p<1||p>A)return!1;if(g===24){if(y!==0||x!==0)return!1}else if(g>23)return!1;if(y>59||x>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 B0(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}var ks=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)||B0(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&&B0(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))B0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var Yt=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)}},na=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 QR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Do(t){switch(t){case"bitcoin":return Zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return t0;case"regtest":return QR;default:throw new Error(`Unknown network "${t}"`)}}l();var ia=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 Dl=new ia(5);var Rv=160,Uv=155,Ov=240,Dv={p2pkh:Ov,p2wpkh:Uv,p2tr:Rv},L0={p2pkh:34,p2wpkh:31,p2tr:43},P0={p2pkh:546,p2wpkh:294,p2tr:330};function M0(t,e){return Dv[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 Yt(`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 kv(t,e,r){return t==="p2pkh"?ki(e,r).address:t==="p2wpkh"?Ts(e,r).address:_s(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 Yt(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Nv(t,e){try{return K0(t,e)}catch{return"p2tr"}}function H0(t){return Xe.encode(["RETURN",t])}var kl=546;function r6(t){return t.status.confirmed===!0}function n6(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 Cv(t,e){if(!t.length)throw new Yt("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(r6),n=r.filter(i=>i.value>kl);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 ${kl}-sat dust limit`;throw new Yt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:kl})}return[...n].sort(n6)[0]}async function Lv(t,e){let r=await e.rest.address.getUtxos(t),n=Cv(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:_r(i)}}async function i6(t){let e=t.feeEstimator??Dl,{utxo:r,prevTxBytes:n}=await Lv(t.beaconAddress,t.bitcoin),i=$0(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Xr(t.network).decode(t.beaconAddress)),s=Nv(i,t.network),c=await e.estimateFee(M0("p2tr",s));if(BigInt(r.value)<=c)throw new Yt(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new Rs({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 o6(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=_o.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ft(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 Yt(`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=_o.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ft(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],_o.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ci=class{service;did;constructor(e,r){this.service=e,this.did=r}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??Dl,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await Lv(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=kv(i,n,r);if(s!==e.beaconAddress)throw new Yt(`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=Nv(o,r),a=await e.feeEstimator.estimateFee(M0(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new Yt(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new Rs({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=Ts(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=_s(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 o6(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 Ci{constructor(e,r){super({...e,type:"CASBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;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(Os(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.did,s=Gn(e),c={[o]:s},a=Ro(ir(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 Ci{constructor(e,r){super({...e,type:"SingletonBeacon"},r)}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=Ro(ir(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var s6=new Uint8Array(32),V0=1n<<BigInt(256),Pv=(()=>{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 Yn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function Ae(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 Nl(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 oa(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 Kv(t,e){Ae(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 Ns(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Cl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function En(t,e){return t<<32-e|t>>>e}var $v=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",c6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cs(t){if(Ae(t),$v)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=c6[t[r]];return e}var Li={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mv(t){if(t>=Li._0&&t<=Li._9)return t-Li._0;if(t>=Li.A&&t<=Li.F)return t-(Li.A-10);if(t>=Li.a&&t<=Li.f)return t-(Li.a-10)}function Ls(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if($v)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=Mv(t.charCodeAt(o)),c=Mv(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 pr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Ae(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 Hv(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 Ps(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 Vv=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 qv(t){if(typeof t=="bigint"){if(!Ll(t))throw new Error("positive bigint expected, got "+t)}else Yn(t);return t}function Xu(t){let e=qv(t).toString(16);return e.length&1?"0"+e:e}function Fv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?F0:BigInt("0x"+t)}function ko(t){return Fv(Cs(t))}function j0(t){return Fv(Cs(a6(Ae(t)).reverse()))}function Pl(t,e){Yn(e),t=qv(t);let r=Ls(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function W0(t,e){return Pl(t,e).reverse()}function sa(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 a6(t){return Uint8Array.from(t)}function jv(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 Ll=t=>typeof t=="bigint"&&F0<=t;function u6(t,e,r){return Ll(t)&&Ll(e)&&Ll(r)&&e<=t&&t<r}function Wv(t,e,r,n){if(!u6(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 Gv(t,e,r){if(Yn(t,"hashLen"),Yn(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),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=(...x)=>r(u,pr(a,...x)),p=(x=i)=>{u=h(o,x),a=h(),x.length!==0&&(u=h(s,x),a=h())},g=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let x=0,S=[];for(;x<e;){a=h();let _=a.slice();S.push(_),x+=a.length}return pr(...S)};return(x,S)=>{f(),p(x);let _;for(;!(_=S(g()));)p();return f(),_}}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 Ml(t){if(!Y0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function ht(...t){return ke(ft(...t))}function td(t){Ml(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){Ml(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:sa(t,e)}function ca(t){return Ml(t),Wc.encode(t)}function Jn(t){let e=Wc.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var zv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(zv||(zv={}));l();l();var No=256;function aa(t,e){return Number(t>>BigInt(e)&1n)}var Yv=(()=>{let t=new Array(No+1),e=new Uint8Array(32);for(let r=0;r<=No;r++)e=ht(e,e),t[r]=e;return t})();function Kl(t,e){if(t.length===0)return Yv[e];if(e===0)return t[0].leaf;let r=No-e,n=[],i=[];for(let o of t)(aa(o.index,r)===0?n:i).push(o);return ht(Kl(n,e-1),Kl(i,e-1))}function Jv(t){return Kl(t,No)}function Zv(t,e){let r=0n,n=[];for(let i=1;i<=No;i++){let o=No-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(aa(c.index,u)!==aa(e,u)){a=!1;break}a&&aa(c.index,o)!==aa(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Kl(s,i-1))}return{collapsed:r,hashes:n}}function Xv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<No;c++){let a=No-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Yv[c];else{if(s>=e.length)return!1;u=e[s++]}o=aa(r,a)===1?ht(u,o):ht(o,u)}return s===e.length&&X0(o,i)}l();var d6=new TextEncoder;function $l(t){return td(ht(d6.encode(t)))}function Qv(t,e){return ht(ht(t),ht(e))}function e1(t){return ht(ht(t))}l();function t1(t,e,r){let n={id:ca(t),collapsed:ca(J0(e.collapsed)),hashes:e.hashes.map(i=>ca(i))};return r?.nonce&&(n.nonce=ca(r.nonce)),r?.updateId&&(n.updateId=ca(r.updateId)),n}function f6(t){let e={rootHash:Jn(t.id),collapsed:td(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 r1(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=f6(t);return Xv(i,o,e,r,n)}l();var Hl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=$l(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?Qv(n.nonce,n.signedUpdate):e1(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=Jv(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?ht(n.signedUpdate):void 0;return t1(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var rd=class extends Ci{constructor(e,r){super({...e,type:"SMTBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;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 na("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=$l(o),u=Jn(c.nonce),d=c.updateId?ht(ht(u),Jn(c.updateId)):ht(ht(u));if(!r1(c,a,d))throw new na("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=Z0(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.did,s=new TextEncoder().encode(ir(e)),c=Ir(32),a=new Hl;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 Ms=class{static establish(e,r){switch(e.type){case"SingletonBeacon":return new Yu(e,r);case"CASBeacon":return new zu(e,r);case"SMTBeacon":return new rd(e,r);default:throw new we("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Mi;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Mi||(Mi={}));l();var pt={"@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 p6=Mn(i1(),1);l();l();l();l();var PH=new Uint8Array(0);function o1(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 ua(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 g6(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,x=0,S=0,_=g.length;S!==_&&g[S]===0;)S++,y++;for(var A=(_-S)*d+1>>>0,O=new Uint8Array(A);S!==_;){for(var T=g[S],M=0,q=A-1;(T!==0||M<x)&&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");x=M,S++}for(var j=A-x;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 x=0,S=0;g[y]===a;)x++,y++;for(var _=(g.length-y)*u+1>>>0,A=new Uint8Array(_);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=_-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=_-S;q!==_&&A[q]===0;)q++;for(var j=new Uint8Array(x+(_-q)),$=x;q!==_;)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 m6=g6,w6=m6,s1=w6;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 c1(this,e)}},ig=class{decoders;constructor(e){this.decoders=e}or(e){return c1(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 c1(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 a1({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}=s1(r,t);return a1({prefix:e,name:t,encode:n,decode:o=>ua(i(o))})}function b6(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 x6(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 or({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return a1({prefix:e,name:t,encode(i){return x6(i,n,r)},decode(i){return b6(i,n,r,t)}})}var nd=or({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),WH=or({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),GH=or({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zH=or({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YH=or({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),JH=or({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZH=or({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),XH=or({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cg=or({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var yr=sg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rV=sg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var sV=or({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cV=or({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=or({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aV=or({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function u1(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function d1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function da(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())})},f1=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)}},ql=new TextEncoder,Ks=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(!d1(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 yr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(da(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return u1(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 yr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return yr.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=ql.encode(e);return Zn.baseEncode(r)}case"String":{let e=ql.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 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=f1(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=Ks.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Ks.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 Ks.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Ks.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Ks.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=f1(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+=Ks.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+=Ks.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 yr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=da(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 ql.encode(e)}case"String":return ql.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)}},E6=new ag;typeof window<"u"&&(window.web5logger=E6);l();l();l();l();var Ki={};vu(Ki,{decode:()=>fa,encodeTo:()=>$s,encodingLength:()=>Hs});l();l();var v6=p1,l1=128,S6=127,A6=~S6,T6=Math.pow(2,31);function p1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=T6;)e[r++]=t&255|l1,t/=128;for(;t&A6;)e[r++]=t&255|l1,t>>>=7;return e[r]=t|0,p1.bytes=r-n+1,e}var _6=ug,I6=128,h1=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&h1)<<i:(s&h1)*Math.pow(2,i),i+=7}while(s>=I6);return ug.bytes=o-n,r}var B6=Math.pow(2,7),R6=Math.pow(2,14),U6=Math.pow(2,21),O6=Math.pow(2,28),D6=Math.pow(2,35),k6=Math.pow(2,42),N6=Math.pow(2,49),C6=Math.pow(2,56),L6=Math.pow(2,63),P6=function(t){return t<B6?1:t<R6?2:t<U6?3:t<O6?4:t<D6?5:t<k6?6:t<N6?7:t<C6?8:t<L6?9:10},M6={encode:v6,decode:_6,encodingLength:P6},K6=M6,sd=K6;function fa(t,e=0){return[sd.decode(t,e),sd.decode.bytes]}function $s(t,e,r=0){return sd.encode(t,e,r),e}function Hs(t){return sd.encodingLength(t)}function dg(t,e){let r=e.byteLength,n=Hs(t),i=n+Hs(r),o=new Uint8Array(i+r);return $s(t,o,0),$s(r,o,n),o.set(e,i),new la(t,r,e,o)}function y1(t){let e=ua(t),[r,n]=fa(e),[i,o]=fa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new la(r,i,s,e)}function g1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&o1(t.bytes,r.bytes)}}var la=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function m1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return H6(r,lg(t),e??yr.encoder);default:return V6(r,lg(t),e??nd.encoder)}}var w1=new WeakMap;function lg(t){let e=w1.get(t);if(e==null){let r=new Map;return w1.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!==q6)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&&g1(e.multihash,n.multihash)}toString(e){return m1(this,e)}toJSON(){return{"/":m1(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??b1(n,i,o.bytes))}else if(r[F6]===!0){let{version:n,multihash:i,code:o}=r,s=y1(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=b1(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=ua(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 la(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]=fa(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]=$6(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return lg(o).set(n,e),o}};function $6(t,e){switch(t[0]){case"Q":{let r=e??yr;return[yr.prefix,r.decode(`${yr.prefix}${t}`)]}case yr.prefix:{let r=e??yr;return[yr.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 H6(t,e,r){let{prefix:n}=r;if(n!==yr.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 V6(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,q6=18;function b1(t,e,r){let n=Hs(t),i=n+Hs(e),o=new Uint8Array(i+r.byteLength);return $s(t,o,0),$s(e,o,n),o.set(r,i),o}var F6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Jt=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=Ki.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Ki.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Ki.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]=Ki.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}}};Jt.codeToName=new Map;Jt.nameToCode=new Map;Jt.registerCodec({code:237,name:"ed25519-pub"});Jt.registerCodec({code:4864,name:"ed25519-priv"});Jt.registerCodec({code:236,name:"x25519-pub"});Jt.registerCodec({code:4866,name:"x25519-priv"});Jt.registerCodec({code:231,name:"secp256k1-pub"});Jt.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=Mn(sm(),1),rc=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 mh=class{constructor(){this.store=new Map}clear(){return rc(this,void 0,void 0,function*(){this.store.clear()})}close(){return rc(this,void 0,void 0,function*(){})}delete(e){return rc(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return rc(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return rc(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return rc(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return rc(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var p4=Mn(ww(),1);var y4=Mn(ww(),1);l();l();l();l();l();function g4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function bw(t,...e){if(!g4(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 _T(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 Ma=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Jh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),In=(t,e)=>t<<32-e|t>>>e;var Nj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function m4(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=m4(t)),bw(t),t}var Yh=class{clone(){return this._cloneInto()}},Cj={}.toString;function IT(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(Ma&&typeof Ma.getRandomValues=="function")return Ma.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function w4(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 RT=(t,e,r)=>t&e^~t&r,UT=(t,e,r)=>t&e^t&r^e&r,Zh=class extends Yh{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=Jh(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=Jh(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),_T(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;w4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Jh(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 b4=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Go=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zo=new Uint32Array(64),vw=class extends Zh{constructor(){super(64,32,8,!1),this.A=Go[0]|0,this.B=Go[1]|0,this.C=Go[2]|0,this.D=Go[3]|0,this.E=Go[4]|0,this.F=Go[5]|0,this.G=Go[6]|0,this.H=Go[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)zo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=zo[f-15],p=zo[f-2],g=In(h,7)^In(h,18)^h>>>3,y=In(p,17)^In(p,19)^p>>>10;zo[f]=y+zo[f-7]+g+zo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=In(c,6)^In(c,11)^In(c,25),p=d+h+RT(c,a,u)+b4[f]+zo[f]|0,y=(In(n,2)^In(n,13)^In(n,22))+UT(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){zo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Yo=IT(()=>new vw);var x4=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ka=class{static digest(e){return x4(this,arguments,void 0,function*({data:r}){return Yo(r)})}};l();var ci=class{};var E4=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())})},Xh=class extends ci{digest(e){return E4(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Ka.digest({data:n})}})}};l();l();l();l();l();l();function OT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function v4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Sw(t,...e){if(!v4(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 DT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");OT(t.outputLen),OT(t.blockLen)}function $a(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 kT(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 Qh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function NT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var ep=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,S4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!S4)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)),!NT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function tp(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!NT(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 Ha=class{clone(){return this._cloneInto()}},sW={}.toString;function rp(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(Qh&&typeof Qh.getRandomValues=="function")return Qh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function A4(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 Va=class extends Ha{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=ep(this.buffer)}update(e){$a(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=ep(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){$a(this),kT(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;A4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=ep(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 T4=(t,e,r)=>t&e^~t&r,_4=(t,e,r)=>t&e^t&r^e&r,I4=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]),Zo=new Uint32Array(64),Tw=class extends Va{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)Zo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Zo[f-15],p=Zo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;Zo[f]=y+Zo[f-7]+g+Zo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=Bn(c,6)^Bn(c,11)^Bn(c,25),p=d+h+T4(c,a,u)+I4[f]+Zo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+_4(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Zo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var np=rp(()=>new Tw);l();var op={};vu(op,{bitGet:()=>N4,bitLen:()=>k4,bitMask:()=>Vd,bitSet:()=>C4,bytesToHex:()=>Xi,bytesToNumberBE:()=>Qi,bytesToNumberLE:()=>Un,concatBytes:()=>to,createHmacDrbg:()=>Bw,ensureBytes:()=>Ge,equalBytes:()=>O4,hexToBytes:()=>pc,hexToNumber:()=>Iw,isBytes:()=>Rn,numberToBytesBE:()=>mr,numberToBytesLE:()=>eo,numberToHexUnpadded:()=>MT,numberToVarBytesBE:()=>U4,utf8ToBytes:()=>D4,validateObject:()=>sn});l();var PT=BigInt(0),ip=BigInt(1),B4=BigInt(2);function Rn(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var R4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Xi(t){if(!Rn(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=R4[t[r]];return e}function MT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Iw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Zi={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function CT(t){if(t>=Zi._0&&t<=Zi._9)return t-Zi._0;if(t>=Zi._A&&t<=Zi._F)return t-(Zi._A-10);if(t>=Zi._a&&t<=Zi._f)return t-(Zi._a-10)}function pc(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=CT(t.charCodeAt(o)),c=CT(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 Qi(t){return Iw(Xi(t))}function Un(t){if(!Rn(t))throw new Error("Uint8Array expected");return Iw(Xi(Uint8Array.from(t).reverse()))}function mr(t,e){return pc(t.toString(16).padStart(e*2,"0"))}function eo(t,e){return mr(t,e).reverse()}function U4(t){return pc(MT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=pc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(Rn(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 to(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!Rn(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 O4(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 D4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function k4(t){let e;for(e=0;t>PT;t>>=ip,e+=1);return e}function N4(t,e){return t>>BigInt(e)&ip}var C4=(t,e,r)=>t|(r?ip:PT)<<BigInt(e),Vd=t=>(B4<<BigInt(t-1))-ip,_w=t=>new Uint8Array(t),LT=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=_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(LT([0]),f),n=c(),f.length!==0&&(i=c(LT([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 to(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var L4={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"||Rn(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=L4[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 _t=BigInt(0),et=BigInt(1),yc=BigInt(2),P4=BigInt(3),Rw=BigInt(4),KT=BigInt(5),$T=BigInt(8),M4=BigInt(9),K4=BigInt(16);function Be(t,e){let r=t%e;return r>=_t?r:e+r}function Uw(t,e,r){if(r<=_t||e<_t)throw new Error("Expected power/modulo > 0");if(r===et)return _t;let n=et;for(;e>_t;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >_t;)n*=n,n%=r;return n}function sp(t,e){if(t===_t||e<=_t)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Be(t,e),n=e,i=_t,o=et,s=et,c=_t;for(;r!==_t;){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 $4(t){let e=(t-et)/yc,r,n,i;for(r=t-et,n=0;r%yc===_t;r/=yc,n++);for(i=yc;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)/yc;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 H4(t){if(t%Rw===P4){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%$T===KT){let e=(t-KT)/$T;return function(n,i){let o=n.mul(i,yc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,yc),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%K4,$4(t)}var HT=(t,e)=>(Be(t,e)&et)===et,V4=["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=V4.reduce((n,i)=>(n[i]="function",n),e);return sn(t,r)}function q4(t,e,r){if(r<_t)throw new Error("Expected power > 0");if(r===_t)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>_t;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function F4(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 qa(t,e,r=!1,n={}){if(t<=_t)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=H4(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Vd(i),ZERO:_t,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 _t<=a&&a<t},is0:a=>a===_t,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)=>q4(c,a,u),div:(a,u)=>Be(a*sp(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>sp(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>F4(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?eo(a,o):mr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Un(a):Qi(a)}});return Object.freeze(c)}function VT(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 qT(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=qT(t);return e+Math.ceil(e/2)}function FT(t,e,r=!1){let n=t.length,i=qT(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?Qi(t):Un(t),c=Be(s,e-et)+et;return r?eo(c,i):mr(c,i)}l();l();var W4=BigInt(0),Nw=BigInt(1);function cp(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>W4;)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,x=Number(s&f);s>>=p,x>a&&(x-=h,s+=Nw);let S=y,_=y+Math.abs(x)-1,A=g%2!==0,O=x<0;x===0?d=d.add(r(A,o[S])):u=u.add(r(O,o[_]))}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),sn(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 G4(t){let e=qd(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:z4,hexToBytes:Y4}=op,gc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=gc;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:z4(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=gc,r=typeof t=="string"?Y4(t):t;if(!Rn(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}=gc._parseInt(r.subarray(2)),{d:s,l:c}=gc._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}`}},ro=BigInt(0),cn=BigInt(1),IW=BigInt(2),jT=BigInt(3),BW=BigInt(4);function J4(t){let e=G4(t),{Fp:r}=e,n=e.toBytes||((g,y,x)=>{let S=y.toAffine();return to(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),i=e.fromBytes||(g=>{let y=g.subarray(1),x=r.fromBytes(y.subarray(0,r.BYTES)),S=r.fromBytes(y.subarray(r.BYTES,2*r.BYTES));return{x,y:S}});function o(g){let{a:y,b:x}=e,S=r.sqr(g),_=r.mul(S,g);return r.add(r.add(_,r.mul(g,y)),x)}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"&&ro<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:x,wrapPrivateKey:S,n:_}=e;if(y&&typeof g!="bigint"){if(Rn(g)&&(g=Xi(g)),typeof g!="string"||!y.includes(g.length))throw new Error("Invalid key");g=g.padStart(x*2,"0")}let A;try{A=typeof g=="bigint"?g:Qi(Ge("private key",g,x))}catch{throw new Error(`private key must be ${x} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Be(A,_)),c(A),A}let u=new Map;function d(g){if(!(g instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(y,x,S){if(this.px=y,this.py=x,this.pz=S,y==null||!r.isValid(y))throw new Error("x required");if(x==null||!r.isValid(x))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(y){let{x,y:S}=y||{};if(!y||!r.isValid(x)||!r.isValid(S))throw new Error("invalid affine point");if(y instanceof f)throw new Error("projective point not allowed");let _=A=>r.eql(A,r.ZERO);return _(x)&&_(S)?f.ZERO:new f(x,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let x=r.invertBatch(y.map(S=>S.pz));return y.map((S,_)=>S.toAffine(x[_])).map(f.fromAffine)}static fromHex(y){let x=f.fromAffine(i(Ge("pointHex",y)));return x.assertValidity(),x}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:x}=this.toAffine();if(!r.isValid(y)||!r.isValid(x))throw new Error("bad point: x or y not FE");let S=r.sqr(x),_=o(y);if(!r.eql(S,_))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:x,py:S,pz:_}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(x,T),r.mul(A,_)),q=r.eql(r.mul(S,T),r.mul(O,_));return M&&q}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:y,b:x}=e,S=r.mul(x,jT),{px:_,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(_,_),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(_,A);return Q=r.add(Q,Q),q=r.mul(_,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:x,py:S,pz:_}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,jT),Q=r.mul(x,A),G=r.mul(S,O),I=r.mul(_,T),D=r.add(x,S),E=r.add(A,O);D=r.mul(D,E),E=r.add(Q,G),D=r.sub(D,E),E=r.add(x,_);let U=r.add(A,T);return E=r.mul(E,U),U=r.add(Q,I),E=r.sub(E,U),U=r.add(S,_),M=r.add(O,T),U=r.mul(U,M),M=r.add(G,I),U=r.sub(U,M),j=r.mul($,E),M=r.mul(X,I),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),I=r.mul($,I),E=r.mul(X,E),G=r.add(G,I),I=r.sub(Q,I),I=r.mul($,I),E=r.add(E,I),Q=r.mul(G,E),q=r.add(q,Q),Q=r.mul(U,E),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,x=>{let S=r.invertBatch(x.map(_=>_.pz));return x.map((_,A)=>_.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let x=f.ZERO;if(y===ro)return x;if(c(y),y===cn)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:_,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=x,q=x,j=this;for(;A>ro||T>ro;)A&cn&&(M=M.add(j)),T&cn&&(q=q.add(j)),j=j.double(),A>>=cn,T>>=cn;return _&&(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 x=y,S,_,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(x),{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),_=$.add(Q)}else{let{p:O,f:T}=this.wNAF(x);S=O,_=T}return f.normalizeZ([S,_])[0]}multiplyAndAddUnsafe(y,x,S){let _=f.BASE,A=(T,M)=>M===ro||M===cn||!T.equals(_)?T.multiplyUnsafe(M):T.multiply(M),O=A(this,x).add(A(y,S));return O.is0()?void 0:O}toAffine(y){let{px:x,py:S,pz:_}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(_));let O=r.mul(x,y),T=r.mul(S,y),M=r.mul(_,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:x}=e;if(y===cn)return!0;if(x)return x(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:x}=e;return y===cn?this:x?x(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Xi(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=cp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function Z4(t){let e=qd(t);return sn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function WT(t){let e=Z4(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(E){return ro<E&&E<r.ORDER}function c(E){return Be(E,n)}function a(E){return sp(E,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=J4({...e,toBytes(E,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=to;return L?C(Uint8Array.from([U.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,r.toBytes(N.y))},fromBytes(E){let U=E.length,L=E[0],N=E.subarray(1);if(U===i&&(L===2||L===3)){let R=Qi(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=E=>Xi(mr(E,e.nByteLength));function g(E){let U=n>>cn;return E>U}function y(E){return g(E)?c(-E):E}let x=(E,U,L)=>Qi(E.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(x(U,0,L),x(U,L,2*L))}static fromDER(U){let{r:L,s:N}=gc.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 pc(this.toDERHex())}toDERHex(){return gc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return pc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let _={isValidPrivateKey(E){try{return d(E),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let E=kw(e.n);return FT(e.randomBytes(E),e.n)},precompute(E=8,U=u.BASE){return U._setWindowSize(E),U.multiply(BigInt(3)),U}};function A(E,U=!0){return u.fromPrivateKey(E).toRawBytes(U)}function O(E){let U=Rn(E),L=typeof E=="string",N=(U||L)&&E.length;return U?N===i||N===o:L?N===2*i||N===2*o:E instanceof u}function T(E,U,L=!0){if(O(E))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(E)).toRawBytes(L)}let M=e.bits2int||function(E){let U=Qi(E),L=E.length*8-e.nBitLength;return L>0?U>>BigInt(L):U},q=e.bits2int_modN||function(E){return c(M(E))},j=Vd(e.nBitLength);function $(E){if(typeof E!="bigint")throw new Error("bigint expected");if(!(ro<=E&&E<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return mr(E,e.nByteLength)}function X(E,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),E=Ge("msgHash",E),P&&(E=Ge("prehashed msgHash",N(E)));let J=q(E),z=d(U),W=[$(z),$(J)];if(V!=null){let ee=V===!0?R(r.BYTES):V;W.push(Ge("extraEntropy",ee))}let Y=to(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Ue=a(ce),Ke=u.BASE.multiply(ce).toAffine(),Je=c(Ke.x);if(Je===ro)return;let bt=c(Ue*c(Z+Je*z));if(bt===ro)return;let pi=(Ke.x===Je?0:2)|Number(Ke.y&cn),ho=bt;return C&&g(bt)&&(ho=y(bt),pi^=1),new S(Je,ho,pi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function I(E,U,L=Q){let{seed:N,k2sig:R}=X(E,U,L),C=e;return Bw(C.hash.outputLen,C.nByteLength,C.hmac)(N,R)}u.BASE._setWindowSize(8);function D(E,U,L,N=G){let R=E;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"||Rn(R))try{V=S.fromDER(R)}catch(Ke){if(!(Ke instanceof gc.Err))throw Ke;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Ke,s:Je}=R;V=new S(Ke,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Ke){if(Ke.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:I,verify:D,ProjectivePoint:u,Signature:S,utils:_}}l();l();var ap=class extends Ha{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,DT(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 $a(this),this.iHash.update(e),this}digestInto(e){$a(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 ap(t,e).update(r).digest();Cw.create=(t,e)=>new ap(t,e);function X4(t){return{hash:t,hmac:(e,...r)=>Cw(t,e,tp(...r)),randomBytes:Hd}}function up(t,e){let r=n=>WT({...t,...X4(n)});return Object.freeze({...r(e),create:r})}var YT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),GT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Q4=BigInt(1),Lw=BigInt(2),zT=(t,e)=>(t+e/Lw)/e;function eN(t){let e=YT,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,x=ze(y,c,e)*y%e,S=ze(x,a,e)*x%e,_=ze(S,c,e)*y%e,A=ze(_,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=qa(YT,void 0,void 0,{sqrt:eN}),wr=up({a:BigInt(0),b:BigInt(7),Fp:Pw,n:GT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=GT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Q4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=zT(o*t,e),a=zT(-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}}}},np),qW=BigInt(0);var FW=wr.ProjectivePoint;l();l();function JT(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 tN=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 tN(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=JT(n),o=ne.string(i).toUint8Array(),s=yield Ka.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ai(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function Fa(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 ja(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 $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())})},rN=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},kt=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=wr.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:"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 $t(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 $t(this,arguments,void 0,function*({publicKeyBytes:r}){return wr.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:"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 $t(this,arguments,void 0,function*({derSignature:r}){return wr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return wr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=wr.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==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=rN(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("Secp256k1: 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(!(Fa(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 $t(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 wr.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=Yo(r);return wr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return wr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{wr.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=Yo(i);return wr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=wr.getPublicKey(r));let n=wr.ProjectivePoint.fromHex(r),i=mr(n.x,32),o=mr(n.y,32);return{x:i,y:o}})}};l();l();var XT=qa(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),nN=XT.create(BigInt("-3")),iN=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),oN=up({a:nN,b:iN,Fp:XT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},np),Lr=oN;var Ht=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())})},sN=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},Vt=class t{static adjustSignatureToLowS(e){return Ht(this,arguments,void 0,function*({signature:r}){let n=Lr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ht(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 Ht(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 Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Lr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ht(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 Ht(this,arguments,void 0,function*({derSignature:r}){return Lr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Lr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ht(this,void 0,void 0,function*(){let e=Lr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Ht(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=sN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Ht(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 Ht(this,arguments,void 0,function*({publicKey:r}){if(!(Fa(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 Ht(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 Lr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Ht(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Yo(r);return Lr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){return Lr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){try{Lr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ht(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Yo(i);return Lr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Ht(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Lr.getPublicKey(r));let n=Lr.ProjectivePoint.fromHex(r),i=mr(n.x,32),o=mr(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 ci{computePublicKey(e){return Fd(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 kt.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.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 kt.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Vt.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Fd(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 kt.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.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(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield kt.sign({key:r,data:n});case"P-256":return yield Vt.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(!Fa(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield kt.verify({key:r,signature:n,data:i});case"P-256":return yield Vt.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var dp=BigInt(4294967295),Kw=BigInt(32);function QT(t,e=!1){return e?{h:Number(t&dp),l:Number(t>>Kw&dp)}:{h:Number(t>>Kw&dp)|0,l:Number(t&dp)|0}}function cN(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}=QT(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var aN=(t,e)=>BigInt(t>>>0)<<Kw|BigInt(e>>>0),uN=(t,e,r)=>t>>>r,dN=(t,e,r)=>t<<32-r|e>>>r,fN=(t,e,r)=>t>>>r|e<<32-r,lN=(t,e,r)=>t<<32-r|e>>>r,hN=(t,e,r)=>t<<64-r|e>>>r-32,pN=(t,e,r)=>t>>>r-32|e<<64-r,yN=(t,e)=>e,gN=(t,e)=>t,mN=(t,e,r)=>t<<r|e>>>32-r,wN=(t,e,r)=>e<<r|t>>>32-r,bN=(t,e,r)=>e<<r-32|t>>>64-r,xN=(t,e,r)=>t<<r-32|e>>>64-r;function EN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var vN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),SN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,AN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),TN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,_N=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),IN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var BN={fromBig:QT,split:cN,toBig:aN,shrSH:uN,shrSL:dN,rotrSH:fN,rotrSL:lN,rotrBH:hN,rotrBL:pN,rotr32H:yN,rotr32L:gN,rotlSH:mN,rotlSL:wN,rotlBH:bN,rotlBL:xN,add:EN,add3L:vN,add3H:SN,add4L:AN,add4H:TN,add5H:IN,add5L:_N},le=BN;var[RN,UN]=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))),Xo=new Uint32Array(80),Qo=new Uint32Array(80),$w=class extends Va{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:x}=this;return[e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,x]}set(e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,x){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=x|0}process(e,r){for(let A=0;A<16;A++,r+=4)Xo[A]=e.getUint32(r),Qo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Xo[A-15]|0,T=Qo[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=Xo[A-2]|0,$=Qo[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,Qo[A-7],Qo[A-16]),I=le.add4H(G,M,X,Xo[A-7],Xo[A-16]);Xo[A]=I|0,Qo[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:x,Hh:S,Hl:_}=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&x,j=le.add5L(_,T,q,UN[A],Qo[A]),$=le.add5H(j,S,O,M,RN[A],Xo[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),I=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,_=x|0,y=p|0,x=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 E=le.add3L(X,G,D);n=le.add3H(E,$,Q,I),i=E|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:x}=le.add(this.Gh|0,this.Gl|0,y|0,x|0),{h:S,l:_}=le.add(this.Hh|0,this.Hl|0,S|0,_|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,x,S,_)}roundClean(){Xo.fill(0),Qo.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=rp(()=>new $w);l();var On=BigInt(0),Pr=BigInt(1),fp=BigInt(2),ON=BigInt(8),DN={zip215:!0};function kN(t){let e=qd(t);return sn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function lp(t){let e=kN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=fp<<BigInt(c*8)-Pr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:On}}}),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"&&On<N,y=(N,R)=>g(N)&&g(R)&&N<R,x=N=>N===On||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 _(N){return N===On?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,!x(R))throw new Error("x required");if(!x(C))throw new Error("y required");if(!x(P))throw new Error("z required");if(!x(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(!x(C)||!x(P))throw new Error("invalid affine point");return new T(C,P,Pr,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)),Ue=d(ue+d(C*d(W*Y)));if(ce!==Ue)throw new Error("bad point: equation left != right (1)");let Ke=d(P*V),Je=d(J*z);if(Ke!==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(fp*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Ue=Y-z,Ke=d(ue*ce),Je=d(ee*Ue),bt=d(ue*Ue),pi=d(ce*ee);return new T(Ke,Je,pi,bt)}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 pu=d((J-V)*(Z+Y)),vf=d((J+V)*(Z-Y)),yu=d(vf-pu);if(yu===On)return this.double();let Sf=d(z*fp*ee),Af=d(W*fp*ue),Wr=Af+Sf,yo=vf+pu,gu=Af-Sf,Tf=d(Wr*yu),fs=d(yo*gu),_f=d(Wr*gu),ry=d(yu*yo);return new T(Tf,fs,ry,_f)}let ce=d(V*Y),Ue=d(J*Z),Ke=d(W*P*ee),Je=d(z*ue),bt=d((V+J)*(Y+Z)-ce-Ue),pi=Je-Ke,ho=Je+Ke,hu=d(Ue-C*ce),Ef=d(bt*pi),ty=d(ho*hu),po=d(bt*hu),jr=d(pi*ho);return new T(Ef,ty,jr,po)}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=_(R);return C===On?q:this.equals(q)||C===Pr?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?ON:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:On,y:Pr};if(Y!==Pr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Pr?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=Un(z);Y===On||(C?S(Y,u):S(Y,r.ORDER));let Z=d(Y*Y),ue=d(Z-Pr),ee=d(P*Z-V),{isValid:ce,value:Ue}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Ke=(Ue&Pr)===Pr,Je=(W&128)!==0;if(!C&&Ue===On&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Ke&&(Ue=d(-Ue)),T.fromAffine({x:Ue,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=eo(C,r.BYTES);return P[P.length-1]|=R&Pr?128:0,P}toHex(){return Xi(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Pr,d(e.Gx*e.Gy)),T.ZERO=new T(On,Pr,Pr,On);let{BASE:M,ZERO:q}=T,j=cp(T,c*8);function $(N){return Be(N,n)}function X(N){return $(Un(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 I(N=new Uint8Array,...R){let C=to(...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=I(C.context,P,N),W=M.multiply(z).toRawBytes(),Y=I(C.context,W,J,N),Z=$(z+Y*V);_(Z);let ue=to(W,eo(Z,r.BYTES));return Ge("result",ue,c*2)}let E=DN;function U(N,R,C,P=E){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=Un(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=I(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 NN(t){return sn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function e_(t){let e=NN(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,I;for(let E=BigInt(i-1);E>=Wd;E--){let U=M>>E&Vw;G^=U,I=u(G,j,X),j=I[0],X=I[1],I=u(G,$,Q),$=I[0],Q=I[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)))}I=u(G,j,X),j=I[0],X=I[1],I=u(G,$,Q),$=I[0],Q=I[1];let D=a($);return n(j*D)}function p(A){return eo(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),Un(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 Un(c(O))}function x(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 _(A){return x(A,S)}return{scalarMult:x,scalarMultBase:_,getSharedSecret:(A,O)=>x(A,O),getPublicKey:A=>_(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Gd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),t_=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),WG=BigInt(0),CN=BigInt(1),qw=BigInt(2),LN=BigInt(5),r_=BigInt(10),PN=BigInt(20),MN=BigInt(40),n_=BigInt(80);function i_(t){let e=Gd,n=t*t%e*t%e,i=ze(n,qw,e)*n%e,o=ze(i,CN,e)*t%e,s=ze(o,LN,e)*o%e,c=ze(s,r_,e)*s%e,a=ze(c,PN,e)*c%e,u=ze(a,MN,e)*a%e,d=ze(u,n_,e)*u%e,f=ze(d,n_,e)*u%e,h=ze(f,r_,e)*s%e;return{pow_p_5_8:ze(h,qw,e)*t%e,b2:n}}function o_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function KN(t,e){let r=Gd,n=Be(e*e*e,r),i=Be(n*n*e,r),o=i_(t*i).pow_p_5_8,s=Be(t*n*o,r),c=Be(e*s*s,r),a=s,u=Be(s*t_,r),d=c===t,f=c===Be(-t,r),h=c===Be(-t*t_,r);return d&&(s=a),(f||h)&&(s=u),HT(s,r)&&(s=Be(-s,r)),{isValid:d||f,value:s}}var an=qa(Gd,void 0,!0),zd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:an,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Hw,randomBytes:Hd,adjustScalarBytes:o_,uvRatio:KN},es=lp(zd);function s_(t,e,r){if(e.length>255)throw new Error("Context is too big");return tp(Aw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var GG=lp({...zd,domain:s_}),zG=lp({...zd,domain:s_,prehash:Hw}),mc=e_({P:Gd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Gd,{pow_p_5_8:r,b2:n}=i_(t);return Be(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:o_,randomBytes:Hd});function c_(t){let{y:e}=es.ExtendedPoint.fromHex(t),r=BigInt(1);return an.toBytes(an.create((r+e)*an.inv(r-e)))}function a_(t){let e=zd.hash(t.subarray(0,32));return zd.adjustScalarBytes(e).subarray(0,32)}var $N=(an.ORDER+BigInt(3))/BigInt(8),YG=an.pow(qw,$N),JG=an.sqrt(an.neg(an.ONE)),ZG=(an.ORDER-BigInt(5))/BigInt(8),XG=BigInt(486662);var QG=VT(an,an.neg(BigInt(486664)));var ez=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tz=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),rz=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),nz=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var iz=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())})},HN=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},It=class t{static bytesToPrivateKey(e){return un(this,arguments,void 0,function*({privateKeyBytes:r}){let n=es.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=es.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=a_(n),o=mc.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=c_(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=es.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=HN(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(!ja(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 es.sign(n,i)})}static validatePublicKey(e){return un(this,arguments,void 0,function*({publicKeyBytes:r}){try{es.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 es.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())})},hp=class extends ci{computePublicKey(e){return Yd(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 It.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 It.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Yd(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 It.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(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield It.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(!ja(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield It.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var no=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:hp,names:["Ed25519"]},secp256k1:{implementation:jd,names:["ES256K","secp256k1"]},secp256r1:{implementation:jd,names:["ES256","secp256r1"]},"SHA-256":{implementation:Xh,names:["SHA-256"]}},er=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new mh}digest(e){return no(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return no(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return no(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 no(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Mw}${n}`})}getPublicKey(e){return no(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 no(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 no(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 no(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 no(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 pp=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 Ma.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 ts=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())})},VN=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},Wa=class t{static bytesToPrivateKey(e){return ts(this,arguments,void 0,function*({privateKeyBytes:r}){let n=mc.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 ts(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 ts(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=mc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return ts(this,void 0,void 0,function*(){let e=mc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return ts(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=VN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return ts(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 ts(this,arguments,void 0,function*({publicKey:r}){if(!ja(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 ts(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 mc.getSharedSecret(i,o)})}};l();l();l();function Mr(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(Mi).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 u_({didDocument:t}){let r=Gw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function d_({didDocument:t,methodId:e}){let r=[];return Object.keys(Mi).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Mr(e);i.some(c=>{let a=Mr(c)===o,u=Ww(c)&&Mr(c.id)===o;return a||u})&&r.push(n)}}),r}function f_(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=Jt.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}=Jt.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())})},br=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 Mr(a.id)===((u=Mr(e?.methodId))!==null&&u!==void 0?u:Mr((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:pp.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 er}){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",h_=[],l_=[];for(let t=0;t<256;t++)h_[t]=Jw[t>>4&15]+Jw[t&15],t<16&&(t<10?l_[48+t]=t:l_[87+t]=t);var Zw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=h_[t[n++]];return r};var p_=(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 y_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",FN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Zd=0;Zd<y_.length;Zd++)FN[y_.charCodeAt(Zd)]=Zd;var Zd;var jN=new TextDecoder,Xw=(t,e)=>e?new TextDecoder(e).decode(t):jN.decode(t),WN=new TextEncoder,dn=t=>WN.encode(t);var g_=typeof window<"u"?window:self,m_=g_.crypto||g_.msCrypto||{},iJ=m_.subtle||m_.webkitSubtle;l();function Ga(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function yp(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 Re(t,e,r){let n=[],i=null;return Re._encode(n,t),i=p_(n),Re.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Re.bytes=-1;Re._floatConversionDetected=!1;Re._encode=function(t,e){if(e!=null)switch(yp(e)){case"object":Re.dict(t,e);break;case"map":Re.dictMap(t,e);break;case"array":Re.list(t,e);break;case"set":Re.listSet(t,e);break;case"string":Re.string(t,e);break;case"number":Re.number(t,e);break;case"boolean":Re.number(t,e);break;case"arraybufferview":Re.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Re.buffer(t,new Uint8Array(e));break}};var gp=new Uint8Array([101]),w_=new Uint8Array([100]),b_=new Uint8Array([108]);Re.buffer=function(t,e){t.push(dn(e.length+":"),e)};Re.string=function(t,e){t.push(dn(dn(e).byteLength+":"+e))};Re.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&&!Re._floatConversionDetected&&(Re._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())};Re.dict=function(t,e){t.push(w_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Re.string(t,n),Re._encode(t,e[n]));t.push(gp)};Re.dictMap=function(t,e){t.push(w_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Re._encode(t,n):Re.string(t,String(n)),Re._encode(t,e.get(n)));t.push(gp)};Re.list=function(t,e){let r=0,n=e.length;for(t.push(b_);r<n;r++)e[r]!=null&&Re._encode(t,e[r]);t.push(gp)};Re.listSet=function(t,e){t.push(b_);for(let r of e)r!=null&&Re._encode(t,r);t.push(gp)};var x_=Re;l();var GN=105,zN=58,YN=100,JN=108,Qw=101;function E_(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 YN:return de.dictionary();case JN:return de.list();case GN: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=E_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(zN),e=E_(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 v_=de;l();function ZN(t){let e=2;for(let r of t)e+=mp(r);return e}function XN(t){let e=2;for(let[r,n]of t){let i=dn(r).byteLength;e+=Ga(i)+1+i,e+=mp(n)}return e}function QN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=dn(r[n]).byteLength;e+=Ga(i)+1+i,e+=mp(t[r[n]])}return e}function eC(t){let e=dn(t).byteLength;return Ga(e)+1+e}function tC(t){let e=t.byteLength-t.byteOffset;return Ga(e)+1+e}function mp(t){if(t==null)return 0;let r=yp(t);switch(r){case"arraybufferview":return tC(t);case"string":return eC(t);case"array":case"set":return ZN(t);case"number":return 1+Ga(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return QN(t);case"map":return XN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var eb=mp;var rC=eb,tb={encode:x_,decode:v_,byteLength:eb,encodingLength:rC};l();l();var nC=/^(\d{1,3}\.){3,3}\d{1,3}$/;var iC=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var Dn={name:"v4",size:4,isFormat:t=>nC.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]}`}},io={name:"v6",size:16,isFormat:t=>t.length>0&&iC.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 S_(t){if(Dn.isFormat(t))return Dn.size;if(io.isFormat(t))return io.size;throw Error(`Invalid ip address: ${t}`)}function A_(t){return S_(t)===Dn.size?1:2}function T_(t,e,r){r=~~r;let n=S_(t);return typeof e=="function"&&(e=e(r+n)),n===Dn.size?Dn.encode(t,e,r):io.encode(t,e,r)}function __(t,e,r){if(e=~~e,r=r||t.length-e,r===Dn.size)return Dn.decode(t,e,r);if(r===io.size)return io.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Dn.size} for v4 or ${io.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 za(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 I_(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 R_(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 Ya(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 Ya.bytes=i-r,e}Ya.bytes=0;function Ja(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 Ja.bytes=r-e,n}Ja.bytes=0;var rs=t=>t instanceof Uint8Array;function oo(t){return typeof t=="string"?ob(t):t.byteLength}function wp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Ya(t)}function bp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Ya(e,t,r),Ya.bytes}var Qd={},U_=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}`;U_[s]=c,Qd[c]=s,Qd[`${r}${i}`]=s,Qd[`${e}${o}`]=s,Qd[`${r}${o}`]=s}}function O_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=U_[o]}return n}function sb(t){return t.length>>>1}function D_(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 lC=Math.pow(2,24),hC=Math.pow(2,16),pC=Math.pow(2,8),di=(t,e)=>t[e]*lC+t[e+1]*hC+t[e+2]*pC+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 xr(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:yC(t,e,r,n,i)}function yC(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 mC=0,k_=32768,ab=32768,wC=~ab,C_=32768,bC=~C_;function He({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=He({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=bp(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(Ja(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:oo(t.replace(/^\.|\.$/gm,""))+2}}),Bt=He({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=bp(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=Ja(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return oo(t)+1}}),Za=He({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Za.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?k_:mC;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&k_?"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:I_(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}}),Ep=He({encode(t,e,r){e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),xr(t,e,r+2,0,n),Ep.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 Ep.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),vp=He({encode(t,e,r){return e||(e=new Uint8Array(vp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),vp.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 vp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),Sp=He({encode(t,e,r){e||(e=new Uint8Array(Sp.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),Sp.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,Sp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),Ap=He({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=wp(t[i])),!rs(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(Ap.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,xr(i,e,r,0,i.length),r+=i.length}),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=[];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 Ap.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=oo(r)+1:e+=r.length+1}),e}}),Tp=He({encode(t,e,r){e||(e=new Uint8Array(Tp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=wp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return xr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),Tp.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,Tp.decode.bytes=e-r,i},encodingLength(t){return t?(rs(t)?t.length:oo(t))+2:2}}),_p=He({encode(t,e,r){e||(e=new Uint8Array(_p.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),_p.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,_p.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),eu=He({encode(t,e,r){return e||(e=new Uint8Array(eu.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),eu.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return eu.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),Ip=He({encode(t,e,r){e||(e=new Uint8Array(Ip.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),Ip.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),Ip.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),ns=He({encode(t,e,r){let n=ns.encodingLength(t);return e||(e=new Uint8Array(ns.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=ns.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,bp(e,t.value,r),r+=oo(t.value),ns.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=Ja(t,e,n+r),i.issuerCritical=!!(i.flags&ns.ISSUER_CRITICAL),ns.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});ns.ISSUER_CRITICAL=128;var Bp=He({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)}}),L_=He({encode(t,e,r){return e||(e=new Uint8Array(L_.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,Dn.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Dn.decode(t,e)},bytes:6}),Rp=He({encode(t,e,r){return e||(e=new Uint8Array(Rp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,io.encode(t,e,r),Rp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=io.decode(t,e);return Rp.decode.bytes=18,r},bytes:18}),N_=t=>new Uint8Array(t),so=He({encode(t,e,r){e||(e=new Uint8Array(so.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,xr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||A_(t.ip,N_),c=T_(t.ip,N_),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,xr(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 so.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=R_(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);xr(t,i,0,e,e+n-4),r.ip=__(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 so.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}`)}}),is=He({encode(t,e,r){e||(e=new Uint8Array(is.encodingLength(t))),r||(r=0);let n=r,i=Qa(t,so);return ae(e,i,r),r=sf(t,so,e,r+2),is.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++]=so.decode(t,e),e+=so.decode.bytes,i-=so.decode.bytes;return is.decode.bytes=e-r,n},encodingLength(t){return 2+Qa(t||[],so)}}),li=He({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!rs(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,xr(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+oo(t.key)}});li.PROTOCOL_DNSSEC=3;li.ZONE_KEY=128;li.SECURE_ENTRYPOINT=32768;var ef=He({encode(t,e,r){e||(e=new Uint8Array(ef.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!rs(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,za(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,xr(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=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,ef.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+oo(t.signature)}}),tf=He({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||".")}}),Kr=He({encode(t,e,r){e||(e=new Uint8Array(Kr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=za(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=wp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,xr(s,e,r,0,s.length),r+=s.length}return Kr.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 Kr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=za(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=He({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,Kr.encode(t.rrtypes,e,r),r+=Kr.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=Kr.decode(t,e,i-(e-r)),e+=Kr.decode.bytes,rf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Kr.encodingLength(t.rrtypes)}}),nf=He({encode(t,e,r){e||(e=new Uint8Array(nf.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!rs(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!rs(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,xr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,xr(o,e,r,0,o.length),r+=o.length,Kr.encode(t.rrtypes,e,r),r+=Kr.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=Kr.decode(t,e,i-(e-r)),e+=Kr.decode.bytes,nf.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Kr.encodingLength(t.rrtypes)}}),of=He({encode(t,e,r){e||(e=new Uint8Array(of.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!rs(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,xr(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+oo(t.digest)}}),Xa=He({encode(t,e,r){e||(e=new Uint8Array(Xa.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 D_(e,t.fingerprint,r,r+=i),Xa.encode.bytes=r-n,ae(e,Xa.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=O_(t,e,e+i),e+=i,Xa.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`)}Xa.getFingerprintLengthForHashType=ub;function cb(t){switch(t.toUpperCase()){case"A":return L_;case"PTR":return eu;case"CNAME":return eu;case"DNAME":return eu;case"TXT":return Ap;case"NULL":return Tp;case"AAAA":return Rp;case"SRV":return Ip;case"HINFO":return _p;case"CAA":return ns;case"NS":return vp;case"SOA":return Sp;case"MX":return Bp;case"OPT":return is;case"DNSKEY":return li;case"RRSIG":return ef;case"RP":return tf;case"NSEC":return rf;case"NSEC3":return nf;case"SSHFP":return Xa;case"DS":return of}return Ep}var fn=He({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,za(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,is.encode(t.options||[],e,r),r+=is.encode.bytes}else{let i=nb(t.class===void 0?"IN":t.class);t.flush&&(i|=ab),ae(e,i,r+2),fi(e,t.ttl||0,r+4),r+=8;let o=cb(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=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=is.decode(t,e+8),e+=8+is.decode.bytes;else{let i=he(t,e+2);r.ttl=di(t,e+4),r.class=rb(i&wC),r.flush=!!(i&ab);let o=cb(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+cb(t.type).encodingLength(e)}}),tu=He({encode(t,e,r){e||(e=new Uint8Array(tu.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,za(t.type),r),r+=2,ae(e,nb(t.class===void 0?"IN":t.class),r),r+=2,tu.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&C_)&&(n.class&=bC),tu.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var P_=1024;var qt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(xC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Za.encode(t,e,r),r+=Za.encode.bytes,r=sf(t.questions,tu,e,r),r=sf(t.answers,fn,e,r),r=sf(t.authorities,fn,e,r),r=sf(t.additionals,fn,e,r),qt.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=Za.decode(t,e);return e+=Za.decode.bytes,e=xp(n.questions,tu,t,e),e=xp(n.answers,fn,t,e),e=xp(n.authorities,fn,t,e),e=xp(n.additionals,fn,t,e),qt.decode.bytes=e-r,n},encodingLength:function(t){return Za.encodingLength(t)+Qa(t.questions||[],tu)+Qa(t.answers||[],fn)+Qa(t.authorities||[],fn)+Qa(t.additionals||[],fn)}};qt.encode.bytes=0;qt.decode.bytes=0;function Up(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 Op={encode:function(t,e,r){return e=qt.encode(Up(t,"query"),e,r),Op.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Op.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Up(t,"query"))}};Op.encode.bytes=0;Op.decode.bytes=0;var Dp={encode:function(t,e,r){return e=qt.encode(Up(t,"response"),e,r),Dp.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Dp.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Up(t,"response"))}};Dp.encode.bytes=0;Dp.decode.bytes=0;var cf=qt.encode,kp=qt.decode,xC=qt.encodingLength;function M_(t){let e=cf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),xr(e,r,2,0,e.length),M_.bytes=r.byteLength,r}M_.bytes=0;function K_(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=kp(t.slice(2));return K_.bytes=kp.bytes,r}K_.bytes=0;function Qa(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 xp(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 $_=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 $_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return $_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var Ct=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())})},H_=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},V_="https://diddht.tbddev.org",EC=0,os=7200,Np=";",cr=",",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 ar;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(ar||(ar={}));var fb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(fb||(fb={}));var F_={Ed25519:ar.Ed25519,ES256K:ar.secp256k1,ES256:ar.secp256r1,"P-256":ar.secp256r1,secp256k1:ar.secp256k1,secp256r1:ar.secp256r1,X25519:ar.X25519},q_={[ar.Ed25519]:"EdDSA",[ar.secp256k1]:"ES256K",[ar.secp256r1]:"ES256",[ar.X25519]:"ECDH-ES+A256KW"},af=class t extends ln{static create(){return Ct(this,arguments,void 0,function*({keyManager:e=new er,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 F_)))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"}),x=yield e.getPublicKey({keyUri:y}),S=yield Nt.identityKeyToIdentifier({identityKey:x}),_=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}#${Mr(j)}`,(u=_.verificationMethod)!==null&&u!==void 0||(_.verificationMethod=[]),_.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:[])_[$]||(_[$]=[]),_[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=_.service)!==null&&M!==void 0||(_.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,_.service.push(T)});let O=new br({uri:S,document:_,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 Ct(this,arguments,void 0,function*({portableDid:r,keyManager:n=new er}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield br.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 Ct(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 Mr(c.id)===((a=Mr(n))!==null&&a!==void 0?a:Mr((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 Ct(this,arguments,void 0,function*({did:r,gatewayUri:n=V_}){return yield Cp.put({did:r,gatewayUri:n})})}static resolve(e){return Ct(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:V_;try{yield Nt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Cp.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},pt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},pt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};af.methodName="dht";var Cp=class t{static get(e){return Ct(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=Nt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield Nt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return Ct(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield Nt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Nt.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 Ct(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 Ct(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 Ct(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=Nt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(cr);break}case f.startsWith("cnt"):{let h=Nt.parseTxtDataToString(d.data);c.controller=h.includes(cr)?h.split(cr):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:x}=Nt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),_=ar[Number(p)],A=yield Nt.keyConverter(_).bytesToPublicKey({publicKeyBytes:S});A.alg=x||q_[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=Nt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,x=H_(h,["id","t","se"]),S=y.includes(cr)?y.split(cr):[y],_=Object.fromEntries(Object.entries(x).map(([A,O])=>[A,O.includes(cr)?O.split(cr):O]));(s=c.service)!==null&&s!==void 0||(c.service=[]),c.service.push(Object.assign(Object.assign({},_),{id:`${r}#${p}`,type:g,serviceEndpoint:S}));break}case f.startsWith("typ"):{let{id:h}=Nt.parseTxtDataToObject(d.data);a.types=h.split(cr).map(p=>Number(p));break}case f.startsWith("did"):{let h=_=>_.split(cr).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:x,agm:S}=Nt.parseTxtDataToObject(d.data);p&&(c.authentication=h(p)),g&&(c.assertionMethod=h(g)),y&&(c.capabilityDelegation=h(y)),x&&(c.capabilityInvocation=h(x)),S&&(c.keyAgreement=h(S));break}}}return{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{}}})}static toDnsPacket(e){return Ct(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:_,previousDid:A}=o;yield Nt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:os,data:`id=${A};s=${_}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:os,data:r.alsoKnownAs.join(cr)}),r.controller){let _=Array.isArray(r.controller)?r.controller.join(cr):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:os,data:_})}for(let[_,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${_}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in F_))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=ar[M.crv],j=yield Nt.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_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:os,data:X.join(Np)})}(u=r.service)===null||u===void 0||u.forEach((_,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=_,j=H_(_,["id","type","serviceEndpoint"]);T=Mr(T),q=Array.isArray(q)?q.join(","):q;let X=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,I])=>`${G}=${I}`).join(Np),Q=Nt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:os,data:Q})});let x=[`v=${EC}`];if(y.length&&x.push(`vm=${y.join(cr)}`),Object.keys(Mi).forEach(_=>{var A;let O=(A=r[_])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=fb[_];x.push(`${T}=${O.join(cr)}`)}}),g.length&&x.push(`svc=${g.join(cr)}`),!((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:os,data:`id=${A.join(cr)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:os,data:x.join(Np)});for(let _ of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:os,data:_+"."});return{id:0,type:"response",flags:P_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},Nt=class t{static createBep44PutMessage(e){return Ct(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 Ct(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield It.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 Ct(this,arguments,void 0,function*({identityKey:r}){let n=yield It.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${af.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:It,"P-256":{publicKeyToBytes:i=>Ct(this,[i],void 0,function*({publicKey:o}){let s=yield Vt.publicKeyToBytes({publicKey:o});return yield Vt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Vt.bytesToPublicKey,privateKeyToBytes:Vt.privateKeyToBytes,bytesToPrivateKey:Vt.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>Ct(this,[i],void 0,function*({publicKey:o}){let s=yield kt.publicKeyToBytes({publicKey:o});return yield kt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:kt.bytesToPublicKey,privateKeyToBytes:kt.privateKeyToBytes,bytesToPrivateKey:kt.bytesToPrivateKey},X25519:Wa}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return Ct(this,arguments,void 0,function*({bep44Message:r}){let n=yield It.bytesToPublicKey({publicKeyBytes:r.k}),i=tb.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield It.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return kp(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Np).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 Ct(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 It.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 Me=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var iZ=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 j_(this,e)}},yb=class{constructor(e){this.decoders=e}or(e){return j_(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`)}},j_=(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)}},vC=({name:t,prefix:e,encode:r,decode:n})=>new gb(t,e,r,n);var SC=(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},AC=(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})=>vC({prefix:e,name:t,encode(i){return AC(i,n,r)},decode(i){return SC(i,n,r,t)}});var yZ=uf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gZ=uf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),df=uf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),mZ=uf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Er=class t{static encode(e){return df.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Me(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 rI=Mn(G_(),1);l();l();var mb;(function(t){t.Public="public",t.Private="private"})(mb||(mb={}));var $r=mb;var Rt=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===$r.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Me(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Me(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Me(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===$r.Private&&(e.d===void 0||e.d.length!==43))throw new Me(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Me(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!Er.isBase64UrlString(e))throw new Me(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 Me(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var ff=class{};ff.hashAlgorithmInMultihashCode=18;ff.maxCanonicalizedDeltaSizeInBytes=1e3;var ur=ff;l();var J_=Mn(Y_(),1);var kn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=J_.default(r);return Er.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 TC=Q_,Z_=128,_C=127,IC=~_C,BC=Math.pow(2,31);function Q_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=BC;)e[r++]=t&255|Z_,t/=128;for(;t&IC;)e[r++]=t&255|Z_,t>>>=7;return e[r]=t|0,Q_.bytes=r-n+1,e}var RC=wb,UC=128,X_=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&X_)<<i:(s&X_)*Math.pow(2,i),i+=7}while(s>=UC);return wb.bytes=o-n,r}var OC=Math.pow(2,7),DC=Math.pow(2,14),kC=Math.pow(2,21),NC=Math.pow(2,28),CC=Math.pow(2,35),LC=Math.pow(2,42),PC=Math.pow(2,49),MC=Math.pow(2,56),KC=Math.pow(2,63),$C=function(t){return t<OC?1:t<DC?2:t<kC?3:t<NC?4:t<CC?5:t<LC?6:t<PC?7:t<MC?8:t<KC?9:10},HC={encode:TC,decode:RC,encodingLength:$C},VC=HC,lf=VC;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 Pp(t,r,e,o)},eI=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 Pp(r,i,s,e)};var Pp=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 tI=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Mp=Ab({name:"sha2-256",code:18,encode:tI("SHA-256")}),ZZ=Ab({name:"sha2-512",code:19,encode:tI("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())})},Lt=class t{static hash(e,r){return hf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Mp.digest(e)).bytes;break;default:throw new Me(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 Mp.encode(e);break;default:throw new Me(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=kn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return hf(this,void 0,void 0,function*(){let n=kn.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 Er.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=Er.decodeAsBytes(e,r);try{n=eI(i)}catch{throw new Me(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=ur.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Me(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 wc=_b;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())})},ss=class t{static createCreateRequest(e){return Kp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;Rt.validateEs256kOperationKey(r,$r.Public),Rt.validateEs256kOperationKey(n,$r.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=ur.hashAlgorithmInMultihashCode,c=[{action:wc.Replace,document:e.document}],a={updateCommitment:yield Lt.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Lt.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Lt.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:pf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Kp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,$r.Public);let r=ur.hashAlgorithmInMultihashCode,n=yield Lt.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 Kp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextRecoveryPublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,$r.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=ur.hashAlgorithmInMultihashCode,n=yield Lt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:wc.Replace,document:e.document}],o=yield Lt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Lt.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Lt.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 Kp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.updatePublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,$r.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)Rt.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)Rt.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:wc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:wc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:wc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:wc.RemovePublicKeys,ids:s};r.push(g)}let c=ur.hashAlgorithmInMultihashCode,a=yield Lt.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Lt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Lt.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){Lt.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 Me(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Rt.validateId(n.id),r.has(n.id))throw new Me(Ye.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),Rt.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 Me(Ye.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){Rt.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 Me(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Me(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&rI.parse(e.serviceEndpoint).error!==void 0)throw new Me(Ye.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=kn.canonicalizeAsBytes(e);if(r.length>ur.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${ur.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Me(Ye.DeltaExceedsMaximumSize,n)}}};var nI=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())})},ru=class t{static createLongFormDid(e){return nI(this,void 0,void 0,function*(){let r=yield ss.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;ur.network===void 0||ur.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${ur.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=kn.canonicalizeAsBytes(o),c=Er.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return nI(this,void 0,void 0,function*(){let r=kn.canonicalizeAsBytes(e),n=yield Lt.hash(r,ur.hashAlgorithmInMultihashCode);return Er.encode(n)})}};l();l();var iI;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(iI||(iI={}));l();var oI;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(oI||(oI={}));l();var cs=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 jC={Ed25519:hi.Ed25519,ES256K:hi.secp256k1,ES256:hi.secp256r1,"P-256":hi.secp256r1,secp256k1:hi.secp256k1,secp256r1:hi.secp256r1},sI="https://ion.tbd.engineering",Ib=class t extends ln{static create(){return cs(this,arguments,void 0,function*({keyManager:e=new er,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in jC)))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}),x=yield e.getPublicKey({keyUri:y}),S=yield bc.computeLongFormDidUri({recoveryKey:g,updateKey:x,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:_,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(_===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new br({uri:S,document:_,metadata:{published:!1,canonicalId:S.split(":",3).join(":"),recoveryKey:g,updateKey:x},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 cs(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 cs(this,arguments,void 0,function*({portableDid:r,keyManager:n=new er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield br.import({portableDid:r,keyManager:n})})}static publish(e){return cs(this,arguments,void 0,function*({did:r,gatewayUri:n=sI}){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:d_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield bc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield bc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=bc.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 cs(this,arguments,void 0,function*(r,n={}){var i,o;let s=me.parse(r);if(!s)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:sI;try{let a=bc.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({},pt),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({},pt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};Ib.methodName="ion";var bc=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 cs(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 ru.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return cs(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield ss.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return cs(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 $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())})},Bb=class t extends ln{static create(){return $p(this,arguments,void 0,function*({keyManager:e=new er,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 br({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return $p(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 $p(this,arguments,void 0,function*({portableDid:r,keyManager:n=new er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield br.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 $p(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({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},pt),{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({},pt),{didDocument:o})})}};Bb.methodName="jwk";l();var Nn=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())})},co;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(co||(co={}));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"},WC={Ed25519:co.Ed25519,ES256K:co.secp256k1,ES256:co.secp256r1,"P-256":co.secp256r1,secp256k1:co.secp256k1,secp256r1:co.secp256r1,X25519:co.X25519},Ub=class t extends ln{static create(){return Nn(this,arguments,void 0,function*({keyManager:e=new er,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 vr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new br({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Nn(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 Nn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new er}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield br.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 Nn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},pt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},pt),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return Nn(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 u_({didDocument:a}).forEach(g=>{let y=Rb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return Nn(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=vr.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 vr.multicodecToJwk({code:u});c.publicKeyJwk=yield vr.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return Nn(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=vr.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 kt.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield It.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 vr.multicodecToJwk({code:u});c.publicKeyJwk=yield vr.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return Nn(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 vr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield It.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield vr.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&&da(n)==="String"&&n.startsWith("z")}};Ub.methodName="key";var vr=class t{static jwkToMulticodec(e){return Nn(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:Jt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Vt.compressPublicKey,secp256k1:kt.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:It,"P-256":Vt,secp256k1:kt,X25519:Wa}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return Nn(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?Jt.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 Nn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in WC))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})})}};vr.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"};vr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};vr.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 GC=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 ln{static resolve(e,r){return GC(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},pt),{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({},pt),{didDocument:c})}catch{return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"notFound"}})}})}};Ob.methodName="web";l();var QC=Mn(aI(),1),eL=Mn(sm(),1);l();l();var ot=class t{static absoluteDidUrl(e,r){if(typeof e=="string"&&e.length!==0)return e.startsWith("#")?`${r}${e}`:e}static relationshipMethodId(e,r){let n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.id:e;return t.absoluteDidUrl(n,r)}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(Mi).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 uI(t,e,r){return t&e^~t&r}function dI(t,e,r){return t&e^t&r^e&r}var Vp=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=Cl(this.buffer)}update(e){oa(this),Ae(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=Cl(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){oa(this),Kv(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Ns(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=Cl(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()}},ao=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tL=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]),as=new Uint32Array(64),Db=class extends Vp{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)as[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=as[f-15],p=as[f-2],g=En(h,7)^En(h,18)^h>>>3,y=En(p,17)^En(p,19)^p>>>10;as[f]=y+as[f-7]+g+as[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=En(c,6)^En(c,11)^En(c,25),p=d+h+uI(c,a,u)+tL[f]+as[f]|0,y=(En(n,2)^En(n,13)^En(n,22))+dI(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(){Ns(as)}destroy(){this.set(0,0,0,0,0,0,0,0),Ns(this.buffer)}},kb=class extends Db{A=ao[0]|0;B=ao[1]|0;C=ao[2]|0;D=ao[3]|0;E=ao[4]|0;F=ao[5]|0;G=ao[6]|0;H=ao[7]|0;constructor(){super(32)}};var qp=Hv(()=>new kb,Vv(1));l();l();var dr=BigInt(0),tr=BigInt(1),Ec=BigInt(2),hI=BigInt(3),pI=BigInt(4),yI=BigInt(5),rL=BigInt(7),gI=BigInt(8),nL=BigInt(9),mI=BigInt(16);function Cn(t,e){let r=t%e;return r>=dr?r:e+r}function Hr(t,e,r){let n=t;for(;e-- >dr;)n*=n,n%=r;return n}function fI(t,e){if(t===dr)throw new Error("invert: expected non-zero number");if(e<=dr)throw new Error("invert: expected positive modulus, got "+e);let r=Cn(t,e),n=e,i=dr,o=tr,s=tr,c=dr;for(;r!==dr;){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!==tr)throw new Error("invert: does not exist");return Cn(i,e)}function Cb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function wI(t,e){let r=(t.ORDER+tr)/pI,n=t.pow(e,r);return Cb(t,n,e),n}function iL(t,e){let r=(t.ORDER-yI)/gI,n=t.mul(e,Ec),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,Ec),i),c=t.mul(o,t.sub(s,t.ONE));return Cb(t,c,e),c}function oL(t){let e=su(t),r=bI(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+rL)/mI;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),x=c.cmov(u,d,y);return Cb(c,x,a),x}}function bI(t){if(t<hI)throw new Error("sqrt is not defined for small field");let e=t-tr,r=0;for(;e%Ec===dr;)e/=Ec,r++;let n=Ec,i=su(t);for(;lI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return wI;let o=i.pow(n,e),s=(e+tr)/Ec;return function(a,u){if(a.is0(u))return u;if(lI(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 x=tr<<BigInt(d-g-1),S=a.pow(f,x);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function sL(t){return t%pI===hI?wI:t%gI===yI?iL:t%mI===nL?oL(t):bI(t)}var cL=["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=cL.reduce((n,i)=>(n[i]="function",n),e);return ed(t,r),t}function aL(t,e,r){if(r<dr)throw new Error("invalid exponent, negatives unsupported");if(r===dr)return t.ONE;if(r===tr)return e;let n=t.ONE,i=e;for(;r>dr;)r&tr&&(n=t.mul(n,i)),i=t.sqr(i),r>>=tr;return n}function Fp(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 lI(t,e){let r=(t.ORDER-tr)/Ec,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 uL(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 Nb=class{ORDER;BITS;BYTES;isLE;ZERO=dr;ONE=tr;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=dr)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}=uL(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 Cn(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return dr<=e&&e<this.ORDER}is0(e){return e===dr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&tr)===tr}neg(e){return Cn(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Cn(e*e,this.ORDER)}add(e,r){return Cn(e+r,this.ORDER)}sub(e,r){return Cn(e-r,this.ORDER)}mul(e,r){return Cn(e*r,this.ORDER)}pow(e,r){return aL(this,e,r)}div(e,r){return Cn(e*fI(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 fI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=sL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?W0(e,this.BYTES):Pl(e,this.BYTES)}fromBytes(e,r=!1){Ae(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):ko(e);if(c&&(a=Cn(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Fp(this,e)}cmov(e,r,n){return n?r:e}};function su(t,e={}){return new Nb(t,e)}function xI(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=xI(t);return e+Math.ceil(e/2)}function jp(t,e,r=!1){Ae(t);let n=t.length,i=xI(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):ko(t),c=Cn(s,e-tr)+tr;return r?W0(c,i):Pl(c,i)}var cu=BigInt(0),vc=BigInt(1);function yf(t,e){let r=e.negate();return t?r:e}function Hb(t,e){let r=Fp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function AI(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){AI(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 EI(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+=vc);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,TI=new WeakMap;function $b(t){return TI.get(t)||1}function vI(t){if(t!==cu)throw new Error("invalid wNAF")}var Wp=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>cu;)r&vc&&(n=n.add(i)),i=i.double(),r>>=vc;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}=EI(n,c,s);n=a,d?o=o.add(yf(h,r[p])):i=i.add(yf(f,r[u]))}return vI(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!==cu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=EI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return vI(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){AI(r,this.bits),TI.set(e,r),Kb.delete(e)}hasCache(e){return $b(e)!==1}};function _I(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>cu||n>cu;)r&vc&&(o=o.add(i)),n&vc&&(s=s.add(i)),i=i.double(),r>>=vc,n>>=vc;return{p1:o,p2:s}}function SI(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 su(t,{isLE:r})}function II(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>cu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=SI(e.p,r.Fp,n),o=SI(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 Gp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var zp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Nl(e),Ae(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),Ns(i)}update(e){return oa(this),this.iHash.update(e),this}digestInto(e){oa(this),Ae(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 zp(t,e).update(r).digest();Vb.create=(t,e)=>new zp(t,e);var BI=(t,e)=>(t+(t>=0?e:-e)/RI)/e;function dL(t,e,r){let[[n,i],[o,s]]=e,c=BI(s*t,r),a=BI(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<uo,h=d<uo;f&&(u=-u),h&&(d=-d);let p=Qu(Math.ceil(G0(r)/2))+au;if(u<uo||u>=p||d<uo||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)}},us={Err:jb,_tlv:{encode:(t,e)=>{let{Err:r}=us;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}=us,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}=us;if(t<uo)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}=us;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 ko(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=us,i=Ae(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}=us,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},uo=BigInt(0),au=BigInt(1),RI=BigInt(2),Yp=BigInt(3),fL=BigInt(4);function UI(t,e={}){let r=II("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=DI(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,I,D){let{x:E,y:U}=I.toAffine(),L=n.toBytes(E);if(Zu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return pr(OI(N),L)}else return pr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){Ae(G,void 0,"Point");let{publicKey:I,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===I&&(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(E===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!x(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${E}, expected compressed=${I} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let I=n.sqr(G),D=n.mul(I,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function x(G,I){let D=n.sqr(I),E=y(G);return n.eql(D,E)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Yp),fL),_=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function A(G,I,D=!1){if(!n.isValid(I)||D&&n.is0(I))throw new Error(`bad point coordinate ${G}`);return I}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 dL(G,a.basises,i.ORDER)}let M=z0((G,I)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();I==null&&(I=L?n.ONE:n.inv(U));let N=n.mul(D,I),R=n.mul(E,I),C=n.mul(U,I);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:I,y:D}=G.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!x(I,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,I,D,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),I=yf(E,I),D=yf(U,D),I.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(I,D,E){this.X=A("x",I),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:D,y:E}=I||{};if(!I||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(I instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(I){let D=$.fromAffine(g(Ae(I,void 0,"point")));return D.assertValidity(),D}static fromHex(I){return $.fromBytes(Ls(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,D=!0){return Q.createCache(this,I),D||this.multiply(Yp),this}assertValidity(){q(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(E,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:D}=o,E=n.mul(D,Yp),{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(I,P),C=n.mul(E,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(E,P),z=n.mul(I,z),W=n.sub(V,z),W=n.mul(I,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(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Yp),W=n.mul(D,L),Y=n.mul(E,N),Z=n.mul(U,R),ue=n.add(D,E),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(E,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(I){return this.add(I.negate())}is0(){return this.equals($.ZERO)}multiply(I){let{endo:D}=e;if(!i.isValidNot0(I))throw new Error("invalid scalar: out of range");let E,U,L=N=>Q.cached(this,N,R=>Hb($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(I),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(I);E=N,U=R}return Hb($,[E,U])[0]}multiplyUnsafe(I){let{endo:D}=e,E=this;if(!i.isValid(I))throw new Error("invalid scalar: out of range");if(I===uo||E.is0())return $.ZERO;if(I===au)return E;if(Q.hasCache(this))return this.multiply(I);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(I),{p1:C,p2:P}=_I($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,I)}toAffine(I){return M(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===au?!0:I?I($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===au?this:I?I($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return Zu(I,"isCompressed"),this.assertValidity(),p($,this,I)}toHex(I=!0){return Cs(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=i.BITS,Q=new Wp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function OI(t){return Uint8Array.of(t?2:3)}function DI(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function lL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ps,i=Object.assign(DI(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:x}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==x?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return jp(Ae(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:x}=i;if(!Ju(p)||"_lengths"in r&&r._lengths||g===y)return;let S=Ae(p,void 0,"key").length;return S===y||S===x}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 x=r.fromBytes(p);return t.fromBytes(g).multiply(x).toBytes(y)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c},h=Gp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function kI(t,e,r={}){Nl(e),ed(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ps,i=r.hmac||((D,E)=>Vb(e,D,E)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=lL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*RI<o.ORDER;function x(D){let E=c>>au;return D>E}function S(D,E){if(!s.isValidNot0(E))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return E}function _(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,E){Fb(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return Ae(D,L)}class O{r;s;recovery;constructor(E,U,L){if(this.r=S("r",E),this.s=S("s",U),L!=null){if(_(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(E,U=g.format){A(E,U);let L;if(U==="der"){let{r:P,s:V}=us.toSig(Ae(E));return new O(P,V)}U==="recovered"&&(L=E[0],U="compact",E=E.subarray(1));let N=p.signature/2,R=E.subarray(0,N),C=E.subarray(N,N*2);return new O(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(E,U){return this.fromBytes(Ls(E),U)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new O(this.r,this.s,E)}recoverPublicKey(E){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(pr(OI((N&1)===0),C)),V=s.inv(R),J=M(Ae(E,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 x(this.s)}toBytes(E=g.format){if(Fb(E),E==="der")return Ls(us.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return E==="recovered"?(_(),pr(Uint8Array.of(this.assertRecovery()),N,R)):pr(N,R)}toHex(E){return Cs(this.toBytes(E))}}let T=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=ko(E),L=E.length*8-a;return L>0?U>>BigInt(L):U},M=r.bits2int_modN||function(E){return s.create(T(E))},q=Qu(a);function j(D){return Wv("num < 2^"+a,D,uo,q),s.toBytes(D)}function $(D,E){return Ae(D,void 0,"message"),E?Ae(e(D),void 0,"prehashed message"):D}function X(D,E,U){let{lowS:L,prehash:N,extraEntropy:R}=qb(U,g);D=$(D,N);let C=M(D),P=s.fromBytes(E);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(Ae(Y,void 0,"extraEntropy"))}let J=pr(...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===uo)return;let Ue=s.create(ue*s.create(z+ce*P));if(Ue===uo)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&au),Je=Ue;return L&&x(Ue)&&(Je=s.neg(Ue),Ke^=1),new O(ce,Je,y?void 0:Ke)}return{seed:J,k2sig:W}}function Q(D,E,U={}){let{seed:L,k2sig:N}=X(D,E,U);return Gv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=qb(L,g);if(U=Ae(U,void 0,"publicKey"),E=$(E,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(E),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 I(D,E,U={}){let{prehash:L}=qb(U,g);return E=$(E,L),O.fromBytes(D,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:Q,verify:G,recoverPublicKey:I,Signature:O,hash:e})}var Xp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},hL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},pL=BigInt(0),Wb=BigInt(2);function yL(t){let e=Xp.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=Hr(d,r,e)*d%e,h=Hr(f,r,e)*d%e,p=Hr(h,Wb,e)*u%e,g=Hr(p,i,e)*p%e,y=Hr(g,o,e)*g%e,x=Hr(y,c,e)*y%e,S=Hr(x,a,e)*x%e,_=Hr(S,c,e)*y%e,A=Hr(_,r,e)*d%e,O=Hr(A,s,e)*g%e,T=Hr(O,n,e)*u%e,M=Hr(T,Wb,e);if(!Jp.eql(Jp.sqr(M),t))throw new Error("Cannot find square root");return M}var Jp=su(Xp.p,{sqrt:yL}),Sc=UI(Xp,{Fp:Jp,endo:hL}),hn=kI(Sc,qp),NI={};function Zp(t,...e){let r=NI[t];if(r===void 0){let n=qp(jv(t));r=pr(n,n),NI[t]=r}return qp(pr(r,...e))}var zb=t=>t.toBytes(!0).slice(1),Yb=t=>t%Wb===pL;function Gb(t){let{Fn:e,BASE:r}=Sc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Yb(i.y)?n:e.neg(n),bytes:zb(i)}}function LI(t){let e=Jp;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=Sc.fromAffine({x:t,y:i});return o.assertValidity(),o}var gf=ko;function PI(...t){return Sc.Fn.create(gf(Zp("BIP0340/challenge",...t)))}function CI(t){return Gb(t).bytes}function gL(t,e,r=Ps(32)){let{Fn:n}=Sc,i=Ae(t,void 0,"message"),{bytes:o,scalar:s}=Gb(e),c=Ae(r,32,"auxRand"),a=n.toBytes(s^gf(Zp("BIP0340/aux",c))),u=Zp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Gb(u),h=PI(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!MI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function MI(t,e,r){let{Fp:n,Fn:i,BASE:o}=Sc,s=Ae(t,64,"signature"),c=Ae(e,void 0,"message"),a=Ae(r,32,"publicKey");try{let u=LI(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=PI(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 Qp=(()=>{let r=(n=Ps(48))=>jp(n,Xp.n);return{keygen:Gp(r,CI),getPublicKey:CI,sign:gL,verify:MI,Point:Sc,utils:{randomSecretKey:r,taggedHash:Zp,lift_x:LI,pointToBytes:zb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function mL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function $I(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 HI(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Zb(t){if(!Array.isArray(t))throw new Error("array expected")}function VI(t,e){if(!$I(!0,e))throw new Error(`${t}: array of strings expected`)}function wL(t,e){if(!$I(!1,e))throw new Error(`${t}: array of numbers expected`)}function bL(...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 xL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;VI("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 EL(t=""){return Jb("join",t),{encode:e=>(VI("join.decode",e),e.join(t)),decode:e=>(Jb("join.decode",e),e.split(t))}}function KI(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(HI(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 vL(t){HI(t);let e=2**8;return{encode:r=>{if(!mL(r))throw new Error("radix.encode input should be Uint8Array");return KI(Array.from(r),e,t)},decode:r=>(wL("radix.decode",r),Uint8Array.from(KI(r,t,e)))}}var SL=t=>bL(vL(58),xL(t),EL("")),uu=SL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var qI=new Uint8Array([231,1]),ut=class t{#e;#t={prefix:qI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:_r(e);if(!r||r.length!==33)throw new Us("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!hn.utils.isValidPublicKey(r))throw new Us("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 Us("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 Pt(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return uu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(qI);return r.push(...e),"z"+uu.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 Qp.verify(e,r,this.x);throw new Us(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return sa(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 FI=new Uint8Array([129,38]),AL=Pt(ke(FI)),Vr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new Wn("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 Wn("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 Wn("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 Pt(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(FI);return r.push(...e),"z"+uu.encode(Uint8Array.from(r))}equals(e){return sa(this.bytes,e.bytes)}computePublicKey(){return new ut(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 Qp.sign(e,this.bytes);throw new Wn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=uu.decode(e.slice(1));if(r.length!==34)throw new Wn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Pt(ke(n))!==AL)throw new Wn(`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 Wn("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=Ir(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 fo=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new bn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Vr(e.secretKey):e.secretKey instanceof Vr&&(this.#e=e.secretKey),e.publicKey instanceof ut?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ut(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new bn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new bn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new bn("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 bn("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 bn("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:Vr.fromJSON(e.secretKey),publicKey:ut.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?_r(e):e;if(r.length!==32)throw new bn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Vr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Vr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Pt(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Vr.random(),r=new Vr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();l();var jI=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Ac="Multikey",Tc="zQ3s",rr="did:btcr2:_",TL="",WI=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function GI(t){if(!ot.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===Ac&&typeof r=="string"&&r.startsWith(Tc)}var ey=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==Ac)throw new qe(`Invalid verification method: type must be "${Ac}"`,De,{id:e,type:r});if(typeof i!="string"||!i.startsWith(Tc))throw new qe(`Invalid verification method: publicKeyMultibase must start with "${Tc}"`,De,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},qr=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",De,e);let r=e.id.includes("k1")?en.KEY:en.EXTERNAL,n=e.id===rr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new qe(`Invalid id: ${i}`,De,e);if(!t.isValidVerificationMethods(o))throw new qe("Invalid verificationMethod: "+o,De,e);if(!t.isValidServices(s))throw new qe("Invalid service: "+s,De,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===en.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 ey({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"',De,e);if(!this.isValidId(e?.id))throw new qe('Invalid "id"',De,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new qe('Invalid "verificationMethod"',De,e);if(!this.isValidServices(e?.service))throw new qe('Invalid "service"',De,e);if(!this.isValidVerificationRelationships(e))throw new qe("Invalid verification relationships",De,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:jI.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return fr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(GI)}static isValidServices(e){return Array.isArray(e)&&e.every(f_)}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"||ot.isDidVerificationMethod(c))})}static validate(e){return e.id===rr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==rr)throw new qe("Invalid GenesisDocument ID",De,this);if(!this.verificationMethod.every(e=>e.id.includes(rr)&&e.controller===rr))throw new qe("Invalid GenesisDocument verificationMethod",De,this);if(!this.service.every(e=>e.id.includes(rr)))throw new qe("Invalid GenesisDocument service",De,this);if(!t.isValidVerificationRelationships(this))throw new qe("Invalid GenesisDocument assertionMethod",De,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new qe("Cannot convert a key identifier to an intermediate document",De,this);return new du(this)}},du=class t extends qr{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(rr,e),n=JSON.parse(r);return new qr(n)}static fromDidDocument(e){let r=ks.cloneReplace(e,WI,rr);return new t(r)}static create(e,r,n){return new t({id:rr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ut(e),i=rr,o=ki(n.compressed,Do(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 Ro(ir(e))}};var zI="did:btcr2:",fr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in en))throw new lt('Expected "idType" to be "KEY" or "EXTERNAL"',Dt,{idType:n});if(i!==1)throw new lt('Expected "version" to be 1',Dt,{version:i});if(typeof o!="string")throw new lt('Expected "network" to be a known network name',Dt,{network:o});let s=ra[o];if(s===void 0)throw new lt('Invalid "network" name',Dt,{network:o});if(n==="KEY")try{new ut(e)}catch{throw new lt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Dt,{genesisBytes:e})}else if(e.length!==32)throw new lt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Dt,{genesisBytes:e});let c=n==="KEY"?"k":"x",a=i-1<<4|s,u=new Uint8Array([a,...e]);return`${zI}${Ss.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new lt(`Invalid did: ${e}`,Dt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new lt(`Invalid did: ${e}`,Dt,{identifier:e});if(i!=="btcr2")throw new lt(`Invalid did method: ${i}`,El,{identifier:e});if(!o)throw new lt(`Invalid method-specific id: ${e}`,Dt,{identifier:e});if(o!==o.toLowerCase())throw new lt(`Invalid method-specific id (must be lowercase): ${e}`,Dt,{identifier:e});let{prefix:s,bytes:c}=Ss.decodeToBytes(o);if(!["x","k"].includes(s))throw new lt(`Invalid hrp: ${s}`,Dt,{identifier:e});if(!c||c.length<1)throw new lt(`Failed to decode id: ${o}`,Dt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new lt(`Invalid btcr2_version (expected 0): ${u}`,Dt,{identifier:e});let d=1,f=c[0]&15,h=ra[f];if(typeof h!="string"){let g=f>=12?"custom network not supported":"reserved";throw new lt(`Invalid network (${g}): ${f}`,Dt,{identifier:e})}let p=c.slice(1);if(a==="KEY")try{new ut(p)}catch{throw new lt(`Invalid genesisBytes: ${p}`,Dt,{identifier:e})}else if(p.length!==32)throw new lt(`Invalid genesisBytes: ${p}`,Dt,{identifier:e});return{idType:a,hrp:s,version:d,network:h,genesisBytes:p}}static validate(e,r={}){let n=[],i=(x,S)=>{n.push(S===void 0?{name:x,ok:!0}:{name:x,ok:!0,detail:S})},o=(x,S,_={})=>(n.push({name:x,ok:!1,detail:S}),{did:e,valid:!1,..._,checks:n});if(typeof e!="string")return o("prefix","The identifier is not a string.");let s=e.split(":");if(s.length!==3||s[0]!=="did"||s[1]!=="btcr2")return o("prefix",`The identifier must be "${zI}" followed by the method-specific id.`);let c=s[2];if(c.length===0)return o("prefix","The method-specific id is empty.");if(i("prefix"),c!==c.toLowerCase())return o("lowercase","The method-specific id must be lowercase.");i("lowercase");let a,u;try{({prefix:a,bytes:u}=Ss.decodeToBytes(c))}catch(x){return o("bech32m",`Bech32m decoding failed: ${x instanceof Error?x.message:String(x)}`)}if(a!=="k"&&a!=="x")return o("bech32m",`The hrp must be "k" or "x", got "${a}".`);let d=a==="k"?en.KEY:en.EXTERNAL;if(u.length<1)return o("bech32m","The data bytes are empty.",{idType:d});i("bech32m",`hrp "${a}", ${u.length} data bytes`);let f=u[0]>>>4;if(f!==0)return o("version",`btcr2_version must be 0, got ${f}.`,{idType:d});i("version","btcr2_version 0 (version_number 1)");let h=u[0]&15,p=ra[h];if(typeof p!="string"){let x=h>=12?`network_value ${h} is a custom network, not supported by this implementation.`:`network_value ${h} is reserved.`;return o("network",x,{idType:d})}i("network",`network_value ${h} (${p})`);let g=u.slice(1);if(d===en.KEY){try{new ut(g)}catch{return o("genesisBytes",`Expected a 33-byte SEC compressed secp256k1 public key, got ${g.length} bytes that are not a valid key.`,{idType:d,network:p})}i("genesisBytes","33-byte SEC compressed secp256k1 public key")}else{if(g.length!==32)return o("genesisBytes",`Expected a 32-byte SHA-256 hash, got ${g.length} bytes.`,{idType:d,network:p});i("genesisBytes","32-byte SHA-256 hash")}let y;try{y=t.encode(g,{idType:d,version:1,network:p})}catch(x){return o("roundTrip",`Re-encoding failed: ${x instanceof Error?x.message:String(x)}`,{idType:d,network:p})}if(y!==e)return o("roundTrip",`Re-encoding produced "${y}".`,{idType:d,network:p});if(i("roundTrip"),r.genesisBytes!==void 0){let x=r.genesisBytes;if(!(x instanceof Uint8Array))return o("genesisBytesMatch","The supplied genesis bytes are not a Uint8Array.",{idType:d,network:p});if(x.length!==g.length)return o("genesisBytesMatch",`Expected ${g.length} genesis bytes for a ${d} identifier, got ${x.length}.`,{idType:d,network:p});if(!wo(x,g))return o("genesisBytesMatch",`The supplied genesis bytes ${xe.encode(x)} do not equal the genesis bytes of the identifier ${xe.encode(g)}.`,{idType:d,network:p});i("genesisBytesMatch","The supplied genesis bytes equal the genesis bytes of the identifier.")}if(r.genesisDocument!==void 0){let x=r.genesisDocument;if(d===en.KEY)return o("genesisDocument","A KEY identifier has no genesis document.",{idType:d,network:p});let S=x.id;if(S!==rr)return o("genesisDocument",`The genesis document id must be "${rr}", got ${JSON.stringify(S)}.`,{idType:d,network:p});try{du.fromJSON(x)}catch(A){return o("genesisDocument",`Invalid genesis document: ${A instanceof Error?A.message:String(A)}`,{idType:d,network:p})}let _=Uo(x);if(!wo(_,g))return o("genesisDocument",`The genesis document hash ${xe.encode(_)} does not equal the genesis bytes ${xe.encode(g)}.`,{idType:d,network:p});i("genesisDocument","The genesis document hashes to the genesis bytes.")}return{did:e,valid:!0,idType:d,network:p,checks:n}}static generate(){let e=fo.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 lt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Dt,{did:e,idType:r});return new ut(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var Fr=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!(!ot.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 Yt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=fr.decode(e),o=Do(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?_s(s.slice(1,33),void 0,o).address:r==="p2wpkh"?Ts(s,o).address:ki(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new Yt("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=Ts(r,n).address,c=_s(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new zt("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 Yt("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 _L=/^6a20([0-9a-f]{64})$/i;function Xb(t){if(!t)return null;let e=_L.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=Fr.parseBitcoinAddress(o.serviceEndpoint),c=await r.rest.address.getTxs(s);if(!(!c||!c.length))for(let a of c){let u=a.status;if(u.confirmed!==!0)continue;let d=a.vout.slice(-1)[0];if(!d)continue;let f=Xb(d.scriptpubkey);if(!f||!await t.spendsFromAddress(a,s,r))continue;let h=i-u.block_height+1;n.get(o)?.push({tx:a,signalBytes:f,blockMetadata:{confirmations:h,height:u.block_height,time:u.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 Le("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=new Map(e.map(u=>[Fr.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 x=s.get(y.address);!x||h.has(x)||(h.add(x),console.info(`Tx ${u.txid} contains beacon address ${y.address}`),n.get(x)?.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 gre=new Uint8Array(0);function YI(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 IL(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,x=0,S=0,_=g.length;S!==_&&g[S]===0;)S++,y++;for(var A=(_-S)*d+1>>>0,O=new Uint8Array(A);S!==_;){for(var T=g[S],M=0,q=A-1;(T!==0||M<x)&&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");x=M,S++}for(var j=A-x;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 x=0,S=0;g[y]===a;)x++,y++;for(var _=(g.length-y)*u+1>>>0,A=new Uint8Array(_);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=_-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=_-S;q!==_&&A[q]===0;)q++;for(var j=new Uint8Array(x+(_-q)),$=x;q!==_;)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 BL=IL,RL=BL,JI=RL;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 ZI(this,e)}},rx=class{decoders;constructor(e){this.decoders=e}or(e){return ZI(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 ZI(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 UL({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}=JI(r,t);return UL({prefix:e,name:t,encode:n,decode:o=>YI(i(o))})}var mf=ix({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_re=ix({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function XI(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var fu=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 wn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Bo,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new wn("Domain mismatch: proof.domain !== config.domain",Bo,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new wn("Challenge mismatch options and challenge passed",Bo,{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 wn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ni,s);if(r&&r!==c.proofPurpose)throw new wn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Ni,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new wn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=XI(i),d=XI(c.domain);if(u.length!==d.length)throw new wn("Domain mismatch: expectedDomain length does not match proof.domain length",Ni,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new wn("Domain mismatch: expectedDomain and proof.domain do not match",Ni,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var lu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new fu(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",Ni,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new we("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ni,{config:r,suite:this.#e()});return ir(e)}generateHash(e,r){let n=ke(xs(e)),i=ke(xs(r)),o=ft(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new Io("Type mismatch: config.type !== this.type",Bo,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new Io("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Bo,{config:e,suite:this.#e()});if(e.created&&!Oo.isValidXsdDateTime(e.created))throw new Io('Invalid config: "created" must be a valid XMLSchema DateTime string',Bo,e);return ir(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new Io("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 Io("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Ni,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var ds=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new xn('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new xn('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 xn("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 xn("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new lu(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new xn("Cannot sign: no secretKey","SIGN_ERROR");return Ur.sign(e,this.secretKey.bytes,Ir(32))}verify(e,r){return Ur.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 Vr(n),o=i.computePublicKey(),s=new fo({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ut(n.publicKey),o=new fo({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ut(n),o=new fo({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new xn("Invalid publicKeyMultibase: cannot be undefined",vl,{publicKeyMultibase:n});let i=mf.decode(n);if(i.length!==35)throw new xn(`Invalid publicKeyMultibase length: ${i.length}`,vl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new xn(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,vl,{publicKeyMultibase:n});let o=i.slice(2),s=new fo({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();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:Gn(e)},o=ta.apply(e,r);if(o.id!==e.id)throw new St(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,Ie,{sourceId:e.id,targetId:o.id});try{qr.isValid(o)}catch(s){throw new St("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),Ie,o)}return i.targetHash=Gn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new St(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,Ie,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new St(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,Ie,{verificationMethodId:n.id});let c=n.id.slice(s),a=ds.fromSigner(c,o,i),u=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new St(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,Ie,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:d});let f={"@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:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,f)}static async announce(e,r,n,i,o,s){return Ms.establish(e,r).broadcastSignal(n,i,o,s)}#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,did:this.#t.id}]};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 St(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,Ie,{phase:this.#e.phase});if(!r)throw new St("NeedSigningKey requires a Signer.",Ie);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 St(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,Ie,{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 St(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,Ie,{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 St(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,Ie,{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",De,r);return fr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=fr.decode(e),i=lo.sidecarData(r.sidecar),o=n.hrp===Ol.k?lo.deterministic(n):null;return new lo(n,i,o,{versionId:r.versionId,versionTime:r.versionTime,genesisDocument:r.sidecar?.genesisDocument,maxDiscoveryRounds:r.maxDiscoveryRounds,minConf:r.minConf})}static update({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethodId:i,beaconId:o}){let s=ot.relationshipMethodId(i,e.id);if(!(s!==void 0&&e.capabilityInvocation?.some(f=>ot.relationshipMethodId(f,e.id)===s)))throw new St("Invalid verificationMethodId: not authorized for capabilityInvocation",De,e);let a=this.getSigningMethod(e,i);if(!a)throw new St("Invalid verificationMethod: not found in source document",De,{sourceDocument:e,verificationMethodId:i});if(a.type!==Ac)throw new St(`Invalid verificationMethod: verificationMethod.type must be "${Ac}"`,De,a);if(!a.publicKeyMultibase?.startsWith(Tc))throw new St(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${Tc}"`,De,a);let u=ot.absoluteDidUrl(o,e.id),d=e.service.filter(f=>u!==void 0&&ot.absoluteDidUrl(f.id,e.id)===u).filter(f=>!!f).shift();if(!d)throw new St("No beacon service found for provided beaconId",Ie,{sourceDocument:e,beaconId:o});return new wf({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:a,beaconService:d})}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}`,El,{identifier:e.id});let i=ot.absoluteDidUrl(r,e.id)??ot.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:e.verificationMethod?.find(s=>ot.absoluteDidUrl(s.id,e.id)===i);if(!(o&&o.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o}};var QI=6;function xf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function OL(t){return xf(t)&&Object.values(t).every(e=>typeof e=="string")}function DL(t){return xf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&xf(t.proof):!1}function kL(t){return xf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}function NL(t){if(t===void 0)return QI;if(typeof t=="number"&&Number.isInteger(t)&&t>=1)return t;let e=typeof t=="string"?JSON.stringify(t):String(t);throw new Le(`Invalid resolution option minConf: expected a positive integer (minimum 1), got ${e}.`,Sv,{minConf:t})}var lo=class t{#e;#t;#n;#r;#o;#i;#s=null;#f=new Map;#l=new Set;#d=new Set;#c=[];#a=null;#h=1;#g=[];#u;#p=0;#y;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,this.#y=NL(i?.minConf),i?.genesisDocument&&(this.#s=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=fr.encode(r,e),{multibase:i}=new ut(r),o=Fr.generateBeaconServices({id:n,publicKey:r,network:Do(e.network),beaconType:"SingletonBeacon"});return new qr({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Uo(r);if(!wo(e.genesisBytes,n))throw new Le("Initial document mismatch: genesisBytes !== genesisDocumentHash",De,{genesisBytes:Qr(e.genesisBytes,"hex"),genesisDocumentHash:Qr(n,"hex")});let i=fr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(rr,i));return new qr(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(Qr(Os(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=Uo(u.didDocument),p=Oo.blocktimeToTimestamp(f.time);if(u.metadata.updated=Oo.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(n&&p>Oo.dateStringToTimestamp(n))return u;if(d.targetVersionId===s+1){let y=Os(d.sourceHash,"base64urlnopad");if(!wo(y,h))throw new Le("Hash mismatch: update.sourceHash !== currentDocumentHash",Ie,{sourceHash:d.sourceHash,currentDocumentHash:Qr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let x=ks.deleteKeys(d,["proof"]);c.push(Uo(x))}else throw new Le("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",Sl,{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 Le("Invalid duplicate: targetVersionId must be an integer >= 2",Ie,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=Uo(i),s=r[e.targetVersionId-2];if(s===void 0)throw new Le("Invalid duplicate: no applied update in history for targetVersionId",Sl,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!wo(s,o))throw new Le("Invalid duplicate: unsigned update hash does not match historical hash",Sl,{unsignedUpdateHash:Qr(o,"hex"),historicalHash:Qr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new Le("No root capability found in update",Ie,r);let i=ot.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(A=>A===e.id))throw new Le("Invalid root capability",Ie,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new Le("No verificationMethod found in update",Ie,r);let a=ot.relationshipMethodId(c,e.id);if(!(a!==void 0&&e.capabilityInvocation?.some(A=>ot.relationshipMethodId(A,e.id)===a)))throw new Le("Invalid update: verificationMethod is not authorized for capabilityInvocation",Ie,{verificationMethodId:c,capabilityInvocation:e.capabilityInvocation});let d=bf.getSigningMethod(e,c),f=ds.fromVerificationMethod(d),h=new lu(f),p=ir(r),y=new fu(h).verifyProof(p,"capabilityInvocation");if(!y.verified)throw new Le("Invalid update: proof not verified",Ie,y);let x=ta.apply(e,r.patch);qr.validate(x);let S=Uo(x),_=Os(r.targetHash);if(!wo(_,S))throw new Le("Invalid update: update.targetHash !== currentDocumentHash",Ie,{updateTargetHash:_,currentDocumentHash:S});return x}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=Fr.getBeaconServices(this.#i).filter(n=>{let i=Fr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=Fr.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 i=this.#m(n);if(!i.length)continue;let s=Ms.establish(r,this.#i.id).processSignals(i,this.#o);s.needs.length>0?e.push(...s.needs):(this.#c.push(...s.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.#g}),this.#h=Number(this.#a.metadata.versionId),this.#i=this.#a.didDocument,this.#c=[],Fr.getBeaconServices(this.#i).some(n=>{let i=Fr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new Le(`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}}}}}#m(e){let r=[];for(let n of e){let i=n.blockMetadata,o=i?.confirmations;if(!(!Number.isInteger(o)||o<this.#y)){if(!Number.isFinite(i?.height)||!Number.isFinite(i?.time))throw new Le(`Beacon signal ${n.signalBytes} has ${o} confirmations but no valid block height or block time.`,Ie,{signalBytes:n.signalBytes,confirmations:o,height:i?.height,time:i?.time});r.push(n)}}return r}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!xf(r))throw new Le("Provided data for NeedGenesisDocument must be a document object.",Ie,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new Le("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",Ie,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!OL(r))throw new Le("Provided data for NeedCASAnnouncement is not a CAS announcement.",Ie,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new Le(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,Ie,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!DL(r))throw new Le("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",Ie,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.updateHash)throw new Le(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ie,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!kL(r))throw new Le("Provided data for NeedSMTProof is not an SMT proof.",Ie,{kind:e.kind});let n=Qr(Os(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new Le(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,Ie,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function eB(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new qe("Cannot derive aggregation communication key: capabilityInvocation is absent",De,{id:t.id});let r=ot.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>ot.absoluteDidUrl(i.id,t.id)===r):e;if(!n)throw new qe(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,De,{id:t.id,invocation:e});return ds.fromVerificationMethod(n).publicKey}function CL(t,e){try{let r=fr.decode(t);if(r.idType==="KEY")return new ut(r.genesisBytes);if(e?.genesisDocument){let n=lo.external(r,e.genesisDocument);return eB(n)}}catch{}}l();l();l();var ox=class{document={};constructor(e){if(!e.id)throw new qe('Missing required "id" property',De,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 qr(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};return TB(LL);})();
|
|
4
4
|
/*! Bundled license information:
|
|
5
5
|
|
|
6
6
|
ieee754/index.js:
|