@libp2p/webrtc 5.2.9-0b9090aea → 5.2.9-4f37aff53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,45 +1,114 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PWebrtc=(()=>{var zo=Object.defineProperty;var uf=Object.getOwnPropertyDescriptor;var ff=Object.getOwnPropertyNames;var hf=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)zo(r,e,{get:t[e],enumerable:!0})},df=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ff(t))!hf.call(r,o)&&o!==e&&zo(r,o,{get:()=>t[o],enumerable:!(n=uf(t,o))||n.enumerable});return r};var pf=r=>df(zo({},"__esModule",{value:!0}),r);var Vm={};It(Vm,{webRTC:()=>qm,webRTCDirect:()=>Hm});var $o=Symbol.for("@libp2p/peer-id");var mn=Symbol.for("@libp2p/transport");var Ka;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ka||(Ka={}));var gn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},yn=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Q=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Je=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var xn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ne=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var bn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},En=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Sn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var An=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var ke=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Qe=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var tr=Symbol.for("@libp2p/service-capabilities"),Ma=Symbol.for("@libp2p/service-dependencies");var Jo={};It(Jo,{base58btc:()=>et,base58flickr:()=>bf});var y0=new Uint8Array(0);function Fa(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function oe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ha(r){return new TextEncoder().encode(r)}function qa(r){return new TextDecoder().decode(r)}function mf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var m=0,h=0,w=0,b=x.length;w!==b&&x[w]===0;)w++,m++;for(var p=(b-w)*u+1>>>0,I=new Uint8Array(p);w!==b;){for(var P=x[w],B=0,v=p-1;(P!==0||B<h)&&v!==-1;v--,B++)P+=256*I[v]>>>0,I[v]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");h=B,w++}for(var L=p-h;L!==p&&I[L]===0;)L++;for(var T=c.repeat(m);L<p;++L)T+=r.charAt(I[L]);return T}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var m=0;if(x[m]!==" "){for(var h=0,w=0;x[m]===c;)h++,m++;for(var b=(x.length-m)*l+1>>>0,p=new Uint8Array(b);x[m];){var I=e[x.charCodeAt(m)];if(I===255)return;for(var P=0,B=b-1;(I!==0||P<w)&&B!==-1;B--,P++)I+=a*p[B]>>>0,p[B]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=P,m++}if(x[m]!==" "){for(var v=b-w;v!==b&&p[v]===0;)v++;for(var L=new Uint8Array(h+(b-v)),T=h;v!==b;)L[T++]=p[v++];return L}}}function g(x){var m=d(x);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var gf=mf,yf=gf,Wa=yf;var jo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Xo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ga(this,t)}},Zo=class{decoders;constructor(t){this.decoders=t}or(t){return Ga(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ga(r,t){return new Zo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Yo=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new jo(t,e,n),this.decoder=new Xo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function er({name:r,prefix:t,encode:e,decode:n}){return new Yo(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Wa(e,r);return er({prefix:t,name:r,encode:n,decode:s=>oe(o(s))})}function wf(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function xf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ht({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return er({prefix:t,name:r,encode(o){return xf(o,n,e)},decode(o){return wf(o,n,e,r)}})}var et=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bf=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qo={};It(Qo,{base32:()=>se,base32hex:()=>vf,base32hexpad:()=>Cf,base32hexpadupper:()=>Tf,base32hexupper:()=>If,base32pad:()=>Sf,base32padupper:()=>Af,base32upper:()=>Ef,base32z:()=>_f});var se=ht({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ef=ht({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sf=ht({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Af=ht({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vf=ht({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),If=ht({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cf=ht({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tf=ht({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_f=ht({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ts={};It(ts,{base36:()=>Lr,base36upper:()=>Lf});var Lr=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lf=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ft={};It(Ft,{Digest:()=>Ue,create:()=>Ct,decode:()=>xe,equals:()=>rs,hasCode:()=>jf});var Bf=ja,za=128,Pf=127,Rf=~Pf,Df=Math.pow(2,31);function ja(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Df;)t[e++]=r&255|za,r/=128;for(;r&Rf;)t[e++]=r&255|za,r>>>=7;return t[e]=r|0,ja.bytes=e-n+1,t}var Nf=es,kf=128,$a=127;function es(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw es.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&$a)<<o:(i&$a)*Math.pow(2,o),o+=7}while(i>=kf);return es.bytes=s-n,e}var Uf=Math.pow(2,7),Of=Math.pow(2,14),Kf=Math.pow(2,21),Mf=Math.pow(2,28),Ff=Math.pow(2,35),Hf=Math.pow(2,42),qf=Math.pow(2,49),Vf=Math.pow(2,56),Wf=Math.pow(2,63),Gf=function(r){return r<Uf?1:r<Of?2:r<Kf?3:r<Mf?4:r<Ff?5:r<Hf?6:r<qf?7:r<Vf?8:r<Wf?9:10},zf={encode:Bf,decode:Nf,encodingLength:Gf},$f=zf,Br=$f;function Pr(r,t=0){return[Br.decode(r,t),Br.decode.bytes]}function rr(r,t,e=0){return Br.encode(r,t,e),t}function nr(r){return Br.encodingLength(r)}function Ct(r,t){let e=t.byteLength,n=nr(r),o=n+nr(e),s=new Uint8Array(o+e);return rr(r,s,0),rr(e,s,n),s.set(t,o),new Ue(r,e,t,s)}function xe(r){let t=oe(r),[e,n]=Pr(t),[o,s]=Pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ue(e,o,i,t)}function rs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Fa(r.bytes,e.bytes)}}var Ue=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function jf(r,t){return r.code===t}function Xa(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Zf(e,ns(r),t??et.encoder);default:return Yf(e,ns(r),t??se.encoder)}}var Za=new WeakMap;function ns(r){let t=Za.get(r);if(t==null){let e=new Map;return Za.set(r,e),e}return t}var dt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:t,multihash:e}=this;if(t!==Rr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Jf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Ct(t,e);return r.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(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&rs(t.multihash,n.multihash)}toString(t){return Xa(this,t)}toJSON(){return{"/":Xa(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Ya(n,o,s.bytes))}else if(e[Qf]===!0){let{version:n,multihash:o,code:s}=e,i=xe(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Rr)throw new Error(`Version 0 CID must use dag-pb (code: ${Rr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Ya(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Rr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=oe(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Ue(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=Pr(t.subarray(e));return e+=d,f},o=n(),s=Rr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Xf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ns(s).set(n,t),s}};function Xf(r,t){switch(r[0]){case"Q":{let e=t??et;return[et.prefix,e.decode(`${et.prefix}${r}`)]}case et.prefix:{let e=t??et;return[et.prefix,e.decode(r)]}case se.prefix:{let e=t??se;return[se.prefix,e.decode(r)]}case Lr.prefix:{let e=t??Lr;return[Lr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Zf(r,t,e){let{prefix:n}=e;if(n!==et.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Yf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Rr=112,Jf=18;function Ya(r,t,e){let n=nr(r),o=n+nr(t),s=new Uint8Array(o+e.byteLength);return rr(r,s,0),rr(t,s,n),s.set(e,o),s}var Qf=Symbol.for("@ipld/js-cid/CID");var os={};It(os,{identity:()=>Wt});var Ja=0,th="identity",Qa=oe;function eh(r){return Ct(Ja,Qa(r))}var Wt={code:Ja,name:th,encode:Qa,digest:eh};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function mt(r=0){return new Uint8Array(r)}function gt(r=0){return new Uint8Array(r)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=gt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var ec=Symbol.for("@achingbrain/uint8arraylist");function tc(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function In(r){return!!r?.[ec]}var V=class r{bufs;length;[ec]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(In(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(In(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=tc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=tc(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(In(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return yt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:yt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!In(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=mt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=mt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=mt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=gt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=mt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=mt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=mt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=mt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=mt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var ss={};It(ss,{base10:()=>nh});var nh=we({prefix:"9",name:"base10",alphabet:"0123456789"});var is={};It(is,{base16:()=>oh,base16upper:()=>sh});var oh=ht({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sh=ht({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var as={};It(as,{base2:()=>ih});var ih=ht({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cs={};It(cs,{base256emoji:()=>fh});var rc=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),ah=rc.reduce((r,t,e)=>(r[e]=t,r),[]),ch=rc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function lh(r){return r.reduce((t,e)=>(t+=ah[e],t),"")}function uh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=ch[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var fh=er({prefix:"\u{1F680}",name:"base256emoji",encode:lh,decode:uh});var ls={};It(ls,{base64:()=>hh,base64pad:()=>dh,base64url:()=>Dr,base64urlpad:()=>ph});var hh=ht({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dh=ht({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dr=ht({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ph=ht({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var us={};It(us,{base8:()=>mh});var mh=ht({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fs={};It(fs,{identity:()=>gh});var gh=er({prefix:"\0",name:"identity",encode:r=>qa(r),decode:r=>Ha(r)});var Q0=new TextEncoder,tg=new TextDecoder;var ps={};It(ps,{sha256:()=>ie,sha512:()=>xh});function ds({name:r,code:t,encode:e}){return new hs(r,t,e)}var hs=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Ct(this.code,e):e.then(n=>Ct(this.code,n))}else throw Error("Unknown type, must be binary type")}};function oc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ie=ds({name:"sha2-256",code:18,encode:oc("SHA-256")}),xh=ds({name:"sha2-512",code:19,encode:oc("SHA-512")});var Oe={...fs,...as,...us,...ss,...is,...Qo,...ts,...Jo,...ls,...cs},hg={...ps,...os};function ic(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var sc=ic("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ms=ic("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=gt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bh={utf8:sc,"utf-8":sc,hex:Oe.base16,latin1:ms,ascii:ms,binary:ms,...Oe},Cn=bh;function X(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function H(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Eh=parseInt("11111",2),gs=parseInt("10000000",2),Sh=parseInt("01111111",2),ac={0:Nr,1:Nr,2:Ah,3:Ch,4:Th,5:Ih,6:vh,16:Nr,22:Nr,48:Nr};function ae(r,t={offset:0}){let e=r[t.offset]&Eh;if(t.offset++,ac[e]!=null)return ac[e](r,t);throw new Error("No decoder for tag "+e)}function kr(r,t){let e=0;if((r[t.offset]&gs)===gs){let n=r[t.offset]&Sh,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Nr(r,t){kr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ae(r,t);if(n===null)break;e.push(n)}return e}function Ah(r,t){let e=kr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function vh(r,t){let e=kr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ih(r,t){return t.offset++,null}function Ch(r,t){let e=kr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Th(r,t){let e=kr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function _h(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new V;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ys(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=_h(r.byteLength);return new V(Uint8Array.from([t.byteLength|gs]),t)}function Nt(r){let t=new V,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new V(Uint8Array.from([2]),ys(t),t)}function Tn(r){let t=Uint8Array.from([0]),e=new V(t,r);return new V(Uint8Array.from([3]),ys(e),e)}function be(r,t=48){let e=new V;for(let n of r)e.append(n);return new V(Uint8Array.from([t]),ys(e),e)}async function cc(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Lh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Bh=Uint8Array.from([6,5,43,129,4,0,34]),Ph=Uint8Array.from([6,5,43,129,4,0,35]),Rh={ext:!0,kty:"EC",crv:"P-256"},Dh={ext:!0,kty:"EC",crv:"P-384"},Nh={ext:!0,kty:"EC",crv:"P-521"},ws=32,xs=48,bs=66;function Es(r){let t=ae(r);return lc(t)}function lc(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===ws*2+1)return n=H(t.subarray(e,e+ws),"base64url"),o=H(t.subarray(e+ws),"base64url"),new or({...Rh,key_ops:["verify"],x:n,y:o});if(t.byteLength===xs*2+1)return n=H(t.subarray(e,e+xs),"base64url"),o=H(t.subarray(e+xs),"base64url"),new or({...Dh,key_ops:["verify"],x:n,y:o});if(t.byteLength===bs*2+1)return n=H(t.subarray(e,e+bs),"base64url"),o=H(t.subarray(e+bs),"base64url"),new or({...Nh,key_ops:["verify"],x:n,y:o});throw new Q(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function uc(r){return be([Nt(Uint8Array.from([1])),be([kh(r.crv)],160),be([Tn(new V(Uint8Array.from([4]),X(r.x??"","base64url"),X(r.y??"","base64url")))],161)]).subarray()}function kh(r){if(r==="P-256")return Lh;if(r==="P-384")return Bh;if(r==="P-521")return Ph;throw new Q(`Invalid curve ${r}`)}var or=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=uc(this.jwk)),this._raw}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e){return cc(this.jwk,e,t)}};function _n(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Uh(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function sr(r,...t){if(!Uh(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Ur(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_n(r.outputLen),_n(r.blockLen)}function ir(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function fc(r,t){sr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ke=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ln(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Gt(r,t){return r<<32-t|r>>>t}function hc(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Se(r){return typeof r=="string"&&(r=hc(r)),sr(r),r}function Ss(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];sr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var ar=class{clone(){return this._cloneInto()}};function Bn(r){let t=n=>r().update(Se(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Or(r=32){if(Ke&&typeof Ke.getRandomValues=="function")return Ke.getRandomValues(new Uint8Array(r));if(Ke&&typeof Ke.randomBytes=="function")return Ke.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Oh(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function dc(r,t,e){return r&t^~r&e}function pc(r,t,e){return r&t^r&e^t&e}var cr=class extends ar{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Ln(this.buffer)}update(t){ir(this);let{view:e,buffer:n,blockLen:o}=this;t=Se(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ln(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ir(this),fc(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Oh(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ln(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Pn=BigInt(4294967295),As=BigInt(32);function mc(r,t=!1){return t?{h:Number(r&Pn),l:Number(r>>As&Pn)}:{h:Number(r>>As&Pn)|0,l:Number(r&Pn)|0}}function Kh(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=mc(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Mh=(r,t)=>BigInt(r>>>0)<<As|BigInt(t>>>0),Fh=(r,t,e)=>r>>>e,Hh=(r,t,e)=>r<<32-e|t>>>e,qh=(r,t,e)=>r>>>e|t<<32-e,Vh=(r,t,e)=>r<<32-e|t>>>e,Wh=(r,t,e)=>r<<64-e|t>>>e-32,Gh=(r,t,e)=>r>>>e-32|t<<64-e,zh=(r,t)=>t,$h=(r,t)=>r,jh=(r,t,e)=>r<<e|t>>>32-e,Xh=(r,t,e)=>t<<e|r>>>32-e,Zh=(r,t,e)=>t<<e-32|r>>>64-e,Yh=(r,t,e)=>r<<e-32|t>>>64-e;function Jh(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Qh=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),td=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ed=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),rd=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,nd=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),od=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var sd={fromBig:mc,split:Kh,toBig:Mh,shrSH:Fh,shrSL:Hh,rotrSH:qh,rotrSL:Vh,rotrBH:Wh,rotrBL:Gh,rotr32H:zh,rotr32L:$h,rotlSH:jh,rotlSL:Xh,rotlBH:Zh,rotlBL:Yh,add:Jh,add3L:Qh,add3H:td,add4L:ed,add4H:rd,add5H:od,add5L:nd},W=sd;var[id,ad]=W.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(r=>BigInt(r))),Ae=new Uint32Array(80),ve=new Uint32Array(80),vs=class extends cr{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:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:g,Gl:x,Hh:m,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=g|0,this.Gl=x|0,this.Hh=m|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Ae[p]=t.getUint32(e),ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let I=Ae[p-15]|0,P=ve[p-15]|0,B=W.rotrSH(I,P,1)^W.rotrSH(I,P,8)^W.shrSH(I,P,7),v=W.rotrSL(I,P,1)^W.rotrSL(I,P,8)^W.shrSL(I,P,7),L=Ae[p-2]|0,T=ve[p-2]|0,K=W.rotrSH(L,T,19)^W.rotrBH(L,T,61)^W.shrSH(L,T,6),N=W.rotrSL(L,T,19)^W.rotrBL(L,T,61)^W.shrSL(L,T,6),O=W.add4L(v,N,ve[p-7],ve[p-16]),F=W.add4H(O,B,K,Ae[p-7],Ae[p-16]);Ae[p]=F|0,ve[p]=O|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:x,Gh:m,Gl:h,Hh:w,Hl:b}=this;for(let p=0;p<80;p++){let I=W.rotrSH(f,d,14)^W.rotrSH(f,d,18)^W.rotrBH(f,d,41),P=W.rotrSL(f,d,14)^W.rotrSL(f,d,18)^W.rotrBL(f,d,41),B=f&g^~f&m,v=d&x^~d&h,L=W.add5L(b,P,v,ad[p],ve[p]),T=W.add5H(L,w,I,B,id[p],Ae[p]),K=L|0,N=W.rotrSH(n,o,28)^W.rotrBH(n,o,34)^W.rotrBH(n,o,39),O=W.rotrSL(n,o,28)^W.rotrBL(n,o,34)^W.rotrBL(n,o,39),F=n&s^n&a^s&a,C=o&i^o&c^i&c;w=m|0,b=h|0,m=g|0,h=x|0,g=f|0,x=d|0,{h:f,l:d}=W.add(l|0,u|0,T|0,K|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=W.add3L(K,O,C);n=W.add3H(_,T,N,F),o=_|0}({h:n,l:o}=W.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=W.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=W.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=W.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=W.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:x}=W.add(this.Fh|0,this.Fl|0,g|0,x|0),{h:m,l:h}=W.add(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:b}=W.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,g,x,m,h,w,b)}roundClean(){Ae.fill(0),ve.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 gc=Bn(()=>new vs);var Nn={};It(Nn,{aInRange:()=>St,abool:()=>zt,abytes:()=>lr,bitGet:()=>dd,bitLen:()=>_s,bitMask:()=>Mr,bitSet:()=>pd,bytesToHex:()=>le,bytesToNumberBE:()=>ue,bytesToNumberLE:()=>$t,concatBytes:()=>he,createHmacDrbg:()=>Ls,ensureBytes:()=>st,equalBytes:()=>fd,hexToBytes:()=>Fe,hexToNumber:()=>Ts,inRange:()=>Kr,isBytes:()=>Ie,memoized:()=>He,notImplemented:()=>gd,numberToBytesBE:()=>Ce,numberToBytesLE:()=>fe,numberToHexUnpadded:()=>Me,numberToVarBytesBE:()=>ud,utf8ToBytes:()=>hd,validateObject:()=>Ht});var Rn=BigInt(0),Dn=BigInt(1),cd=BigInt(2);function Ie(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function lr(r){if(!Ie(r))throw new Error("Uint8Array expected")}function zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var ld=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function le(r){lr(r);let t="";for(let e=0;e<r.length;e++)t+=ld[r[e]];return t}function Me(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ts(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Rn:BigInt("0x"+r)}var ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function yc(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function Fe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=yc(r.charCodeAt(s)),a=yc(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ue(r){return Ts(le(r))}function $t(r){return lr(r),Ts(le(Uint8Array.from(r).reverse()))}function Ce(r,t){return Fe(r.toString(16).padStart(t*2,"0"))}function fe(r,t){return Ce(r,t).reverse()}function ud(r){return Fe(Me(r))}function st(r,t,e){let n;if(typeof t=="string")try{n=Fe(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Ie(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function he(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];lr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function fd(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function hd(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Is=r=>typeof r=="bigint"&&Rn<=r;function Kr(r,t,e){return Is(r)&&Is(t)&&Is(e)&&t<=r&&r<e}function St(r,t,e,n){if(!Kr(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function _s(r){let t;for(t=0;r>Rn;r>>=Dn,t+=1);return t}function dd(r,t){return r>>BigInt(t)&Dn}function pd(r,t,e){return r|(e?Dn:Rn)<<BigInt(t)}var Mr=r=>(cd<<BigInt(r-1))-Dn,Cs=r=>new Uint8Array(r),wc=r=>Uint8Array.from(r);function Ls(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Cs(r),o=Cs(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Cs())=>{o=a(wc([0]),f),n=a(),f.length!==0&&(o=a(wc([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let g=n.slice();d.push(g),f+=n.length}return he(...d)};return(f,d)=>{i(),c(f);let g;for(;!(g=d(l()));)c();return i(),g}}var md={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Ie(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Ht(r,t,e={}){let n=(o,s,i)=>{let a=md[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var gd=()=>{throw new Error("not implemented")};function He(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var wt=BigInt(0),ft=BigInt(1),qe=BigInt(2),yd=BigInt(3),Bs=BigInt(4),xc=BigInt(5),bc=BigInt(8),wd=BigInt(9),xd=BigInt(16);function Y(r,t){let e=r%t;return e>=wt?e:t+e}function Ps(r,t,e){if(t<wt)throw new Error("invalid exponent, negatives unsupported");if(e<=wt)throw new Error("invalid modulus");if(e===ft)return wt;let n=ft;for(;t>wt;)t&ft&&(n=n*r%e),r=r*r%e,t>>=ft;return n}function ct(r,t,e){let n=r;for(;t-- >wt;)n*=n,n%=e;return n}function kn(r,t){if(r===wt)throw new Error("invert: expected non-zero number");if(t<=wt)throw new Error("invert: expected positive modulus, got "+t);let e=Y(r,t),n=t,o=wt,s=ft,i=ft,a=wt;for(;e!==wt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ft)throw new Error("invert: does not exist");return Y(o,t)}function bd(r){let t=(r-ft)/qe,e,n,o;for(e=r-ft,n=0;e%qe===wt;e/=qe,n++);for(o=qe;o<r&&Ps(o,t,r)!==r-ft;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ft)/Bs;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ft)/qe;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let m=a.sqr(d);g<l&&!a.eql(m,a.ONE);g++)m=a.sqr(m);let x=a.pow(u,ft<<BigInt(l-g-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=g}return f}}function Ed(r){if(r%Bs===yd){let t=(r+ft)/Bs;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%bc===xc){let t=(r-xc)/bc;return function(n,o){let s=n.mul(o,qe),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,qe),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%xd,bd(r)}var Ec=(r,t)=>(Y(r,t)&ft)===ft,Sd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rs(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Sd.reduce((n,o)=>(n[o]="function",n),t);return Ht(r,e)}function Ad(r,t,e){if(e<wt)throw new Error("invalid exponent, negatives unsupported");if(e===wt)return r.ONE;if(e===ft)return t;let n=r.ONE,o=t;for(;e>wt;)e&ft&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ft;return n}function vd(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Ds(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Te(r,t,e=!1,n={}){if(r<=wt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ds(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:Mr(o),ZERO:wt,ONE:ft,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return wt<=c&&c<r},is0:c=>c===wt,isOdd:c=>(c&ft)===ft,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>Ad(a,c,l),div:(c,l)=>Y(c*kn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>kn(c,r),sqrt:n.sqrt||(c=>(i||(i=Ed(r)),i(a,c))),invertBatch:c=>vd(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?fe(c,s):Ce(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?$t(c):ue(c)}});return Object.freeze(a)}function Sc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ns(r){let t=Sc(r);return t+Math.ceil(t/2)}function Ac(r,t,e=!1){let n=r.length,o=Sc(t),s=Ns(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?$t(r):ue(r),a=Y(i,t-ft)+ft;return e?fe(a,o):Ce(a,o)}var vc=BigInt(0),Un=BigInt(1);function ks(r,t){let e=t.negate();return r?e:t}function Ic(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Us(r,t){Ic(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Id(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Cd(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Os=new WeakMap,Cc=new WeakMap;function Ks(r){return Cc.get(r)||1}function On(r,t){return{constTimeNegate:ks,hasPrecomputes(e){return Ks(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>vc;)n&Un&&(o=o.add(s)),s=s.double(),n>>=Un;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Us(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=Us(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let g=d*i,x=Number(o&l);o>>=f,x>i&&(x-=u,o+=Un);let m=g,h=g+Math.abs(x)-1,w=d%2!==0,b=x<0;x===0?c=c.add(ks(w,n[m])):a=a.add(ks(b,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Us(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===vc)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=Un),g===0)continue;let x=n[d+Math.abs(g)-1];g<0&&(x=x.negate()),s=s.add(x)}return s},getPrecomputes(e,n,o){let s=Os.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Os.set(n,o(s))),s},wNAFCached(e,n,o){let s=Ks(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Ks(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Ic(n,t),Cc.set(e,n),Os.delete(e)}}}function Kn(r,t,e,n){if(Id(e,r),Cd(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=_s(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let g=0;g<n.length;g++){let x=n[g],m=Number(x>>BigInt(f)&BigInt(a));c[m]=c[m].add(e[g])}let d=o;for(let g=c.length-1,x=o;g>0;g--)x=x.add(c[g]),d=d.add(x);if(u=u.add(d),f!==0)for(let g=0;g<i;g++)u=u.double()}return u}function Fr(r){return Rs(r.Fp),Ht(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ds(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var jt=BigInt(0),kt=BigInt(1),Mn=BigInt(2),Td=BigInt(8),_d={zip215:!0};function Ld(r){let t=Fr(r);return Ht(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Tc(r){let t=Ld(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Mn<<BigInt(a*8)-kt,u=e.create,f=Te(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:jt}}}),g=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,A)=>{if(zt("phflag",A),y.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){St("coordinate "+E,y,jt,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let w=He((E,y)=>{let{ex:A,ey:S,ez:R}=E,D=E.is0();y==null&&(y=D?Td:e.inv(R));let U=u(A*y),q=u(S*y),M=u(R*y);if(D)return{x:jt,y:kt};if(M!==kt)throw new Error("invZ was invalid");return{x:U,y:q}}),b=He(E=>{let{a:y,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:S,ey:R,ez:D,et:U}=E,q=u(S*S),M=u(R*R),G=u(D*D),j=u(G*G),it=u(q*y),at=u(G*u(it+M)),ut=u(j+u(A*u(q*M)));if(at!==ut)throw new Error("bad point: equation left != right (1)");let vt=u(S*R),Dt=u(D*U);if(vt!==Dt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,A,S,R){this.ex=y,this.ey=A,this.ez=S,this.et=R,m("x",y),m("y",A),m("z",S),m("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:A,y:S}=y||{};return m("x",A),m("y",S),new p(A,S,kt,u(A*S))}static normalizeZ(y){let A=e.invertBatch(y.map(S=>S.ez));return y.map((S,R)=>S.toAffine(A[R])).map(p.fromAffine)}static msm(y,A){return Kn(p,f,y,A)}_setWindowSize(y){B.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:A,ey:S,ez:R}=this,{ex:D,ey:U,ez:q}=y,M=u(A*q),G=u(D*R),j=u(S*q),it=u(U*R);return M===G&&j===it}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:A,ey:S,ez:R}=this,D=u(A*A),U=u(S*S),q=u(Mn*u(R*R)),M=u(y*D),G=A+S,j=u(u(G*G)-D-U),it=M+U,at=it-q,ut=M-U,vt=u(j*at),Dt=u(it*ut),Rt=u(j*ut),Qt=u(at*it);return new p(vt,Dt,Qt,Rt)}add(y){h(y);let{a:A,d:S}=t,{ex:R,ey:D,ez:U,et:q}=this,{ex:M,ey:G,ez:j,et:it}=y;if(A===BigInt(-1)){let Pa=u((D-R)*(G+M)),Ra=u((D+R)*(G-M)),Go=u(Ra-Pa);if(Go===jt)return this.double();let Da=u(U*Mn*it),Na=u(q*Mn*j),ka=Na+Da,Ua=Ra+Pa,Oa=Na-Da,sf=u(ka*Go),af=u(Ua*Oa),cf=u(ka*Oa),lf=u(Go*Ua);return new p(sf,af,lf,cf)}let at=u(R*M),ut=u(D*G),vt=u(q*S*it),Dt=u(U*j),Rt=u((R+D)*(M+G)-at-ut),Qt=Dt-vt,ne=Dt+vt,_r=u(ut-A*at),ef=u(Rt*Qt),rf=u(ne*_r),nf=u(Rt*_r),of=u(Qt*ne);return new p(ef,rf,of,nf)}subtract(y){return this.add(y.negate())}wNAF(y){return B.wNAFCached(this,y,p.normalizeZ)}multiply(y){let A=y;St("scalar",A,kt,n);let{p:S,f:R}=this.wNAF(A);return p.normalizeZ([S,R])[0]}multiplyUnsafe(y,A=p.ZERO){let S=y;return St("scalar",S,jt,n),S===jt?P:this.is0()||S===kt?this:B.wNAFCachedUnsafe(this,S,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(y){return w(this,y)}clearCofactor(){let{h:y}=t;return y===kt?this:this.multiplyUnsafe(y)}static fromHex(y,A=!1){let{d:S,a:R}=t,D=e.BYTES;y=st("pointHex",y,D),zt("zip215",A);let U=y.slice(),q=y[D-1];U[D-1]=q&-129;let M=$t(U),G=A?l:e.ORDER;St("pointHex.y",M,jt,G);let j=u(M*M),it=u(j-kt),at=u(S*j-R),{isValid:ut,value:vt}=d(it,at);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Dt=(vt&kt)===kt,Rt=(q&128)!==0;if(!A&&vt===jt&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Dt&&(vt=u(-vt)),p.fromAffine({x:vt,y:M})}static fromPrivateKey(y){return T(y).point}toRawBytes(){let{x:y,y:A}=this.toAffine(),S=fe(A,e.BYTES);return S[S.length-1]|=y&kt?128:0,S}toHex(){return le(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,kt,u(t.Gx*t.Gy)),p.ZERO=new p(jt,kt,kt,jt);let{BASE:I,ZERO:P}=p,B=On(p,a*8);function v(E){return Y(E,n)}function L(E){return v($t(E))}function T(E){let y=e.BYTES;E=st("private key",E,y);let A=st("hashed private key",s(E),2*y),S=g(A.slice(0,y)),R=A.slice(y,2*y),D=L(S),U=I.multiply(D),q=U.toRawBytes();return{head:S,prefix:R,scalar:D,point:U,pointBytes:q}}function K(E){return T(E).pointBytes}function N(E=new Uint8Array,...y){let A=he(...y);return L(s(x(A,st("context",E),!!o)))}function O(E,y,A={}){E=st("message",E),o&&(E=o(E));let{prefix:S,scalar:R,pointBytes:D}=T(y),U=N(A.context,S,E),q=I.multiply(U).toRawBytes(),M=N(A.context,q,D,E),G=v(U+M*R);St("signature.s",G,jt,n);let j=he(q,fe(G,e.BYTES));return st("result",j,e.BYTES*2)}let F=_d;function C(E,y,A,S=F){let{context:R,zip215:D}=S,U=e.BYTES;E=st("signature",E,2*U),y=st("message",y),A=st("publicKey",A,U),D!==void 0&&zt("zip215",D),o&&(y=o(y));let q=$t(E.slice(U,2*U)),M,G,j;try{M=p.fromHex(A,D),G=p.fromHex(E.slice(0,U),D),j=I.multiplyUnsafe(q)}catch{return!1}if(!D&&M.isSmallOrder())return!1;let it=N(R,G.toRawBytes(),M.toRawBytes(),y);return G.add(M.multiplyUnsafe(it)).subtract(j).clearCofactor().equals(p.ZERO)}return I._setWindowSize(8),{CURVE:t,getPublicKey:K,sign:O,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var ur=BigInt(0),Ms=BigInt(1);function Bd(r){return Ht(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function _c(r){let t=Bd(r),{P:e}=t,n=b=>Y(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>Ps(b,e-BigInt(2),e));function l(b,p,I){let P=n(b*(p-I));return p=n(p-P),I=n(I+P),[p,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){St("u",b,ur,e),St("scalar",p,ur,e);let I=p,P=b,B=Ms,v=ur,L=b,T=Ms,K=ur,N;for(let F=BigInt(o-1);F>=ur;F--){let C=I>>F&Ms;K^=C,N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1],K=C;let _=B+v,E=n(_*_),y=B-v,A=n(y*y),S=E-A,R=L+T,D=L-T,U=n(D*_),q=n(R*y),M=U+q,G=U-q;L=n(M*M),T=n(P*n(G*G)),B=n(E*A),v=n(S*(E+n(u*S)))}N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1];let O=c(v);return n(B*O)}function d(b){return fe(n(b),s)}function g(b){let p=st("u coordinate",b,s);return i===32&&(p[31]&=127),$t(p)}function x(b){let p=st("scalar",b),I=p.length;if(I!==s&&I!==i){let P=""+s+" or "+i;throw new Error("invalid scalar, expected "+P+" bytes, got "+I)}return $t(a(p))}function m(b,p){let I=g(p),P=x(b),B=f(I,P);if(B===ur)throw new Error("invalid private or public key received");return d(B)}let h=d(t.Gu);function w(b){return m(b,h)}return{scalarMult:m,scalarMultBase:w,getSharedSecret:(b,p)=>m(b,p),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var Hr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Lc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),by=BigInt(0),Pd=BigInt(1),Bc=BigInt(2),Rd=BigInt(3),Dd=BigInt(5),Nd=BigInt(8);function Pc(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Hr,a=r*r%s*r%s,c=ct(a,Bc,s)*a%s,l=ct(c,Pd,s)*r%s,u=ct(l,Dd,s)*l%s,f=ct(u,t,s)*u%s,d=ct(f,e,s)*f%s,g=ct(d,n,s)*d%s,x=ct(g,o,s)*g%s,m=ct(x,o,s)*g%s,h=ct(m,t,s)*u%s;return{pow_p_5_8:ct(h,Bc,s)*r%s,b2:a}}function Rc(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function kd(r,t){let e=Hr,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Pc(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,l=Y(i*Lc,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*Lc,e);return u&&(i=c),(f||d)&&(i=l),Ec(i,e)&&(i=Y(-i,e)),{isValid:u||f,value:i}}var Ud=Te(Hr,void 0,!0),Od={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ud,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Nd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gc,randomBytes:Or,adjustScalarBytes:Rc,uvRatio:kd},Dc=Tc(Od);var qr=_c({P:Hr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Hr,{pow_p_5_8:e,b2:n}=Pc(r);return Y(ct(e,Rd,t)*n,t)},adjustScalarBytes:Rc,randomBytes:Or});var Fn=32;function Nc(r,t,e){return Dc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Hn=class{type="Ed25519";raw;constructor(t){this.raw=Fs(t,Fn)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return Nc(this.raw,e,t)}};function Hs(r){return r=Fs(r,Fn),new Hn(r)}function Fs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Q(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Md=Math.pow(2,7),Fd=Math.pow(2,14),Hd=Math.pow(2,21),qs=Math.pow(2,28),Vs=Math.pow(2,35),Ws=Math.pow(2,42),Gs=Math.pow(2,49),tt=128,Tt=127;function nt(r){if(r<Md)return 1;if(r<Fd)return 2;if(r<Hd)return 3;if(r<qs)return 4;if(r<Vs)return 5;if(r<Ws)return 6;if(r<Gs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function zs(r,t,e=0){switch(nt(r)){case 8:t[e++]=r&255|tt,r/=128;case 7:t[e++]=r&255|tt,r/=128;case 6:t[e++]=r&255|tt,r/=128;case 5:t[e++]=r&255|tt,r/=128;case 4:t[e++]=r&255|tt,r>>>=7;case 3:t[e++]=r&255|tt,r>>>=7;case 2:t[e++]=r&255|tt,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function qd(r,t,e=0){switch(nt(r)){case 8:t.set(e++,r&255|tt),r/=128;case 7:t.set(e++,r&255|tt),r/=128;case 6:t.set(e++,r&255|tt),r/=128;case 5:t.set(e++,r&255|tt),r/=128;case 4:t.set(e++,r&255|tt),r>>>=7;case 3:t.set(e++,r&255|tt),r>>>=7;case 2:t.set(e++,r&255|tt),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function $s(r,t){let e=r[t],n=0;if(n+=e&Tt,e<tt||(e=r[t+1],n+=(e&Tt)<<7,e<tt)||(e=r[t+2],n+=(e&Tt)<<14,e<tt)||(e=r[t+3],n+=(e&Tt)<<21,e<tt)||(e=r[t+4],n+=(e&Tt)*qs,e<tt)||(e=r[t+5],n+=(e&Tt)*Vs,e<tt)||(e=r[t+6],n+=(e&Tt)*Ws,e<tt)||(e=r[t+7],n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function Vd(r,t){let e=r.get(t),n=0;if(n+=e&Tt,e<tt||(e=r.get(t+1),n+=(e&Tt)<<7,e<tt)||(e=r.get(t+2),n+=(e&Tt)<<14,e<tt)||(e=r.get(t+3),n+=(e&Tt)<<21,e<tt)||(e=r.get(t+4),n+=(e&Tt)*qs,e<tt)||(e=r.get(t+5),n+=(e&Tt)*Vs,e<tt)||(e=r.get(t+6),n+=(e&Tt)*Ws,e<tt)||(e=r.get(t+7),n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=gt(nt(r))),t instanceof Uint8Array?zs(r,t,e):qd(r,t,e)}function Ot(r,t=0){return r instanceof Uint8Array?$s(r,t):Vd(r,t)}var js=new Float32Array([-0]),_e=new Uint8Array(js.buffer);function Uc(r,t,e){js[0]=r,t[e]=_e[0],t[e+1]=_e[1],t[e+2]=_e[2],t[e+3]=_e[3]}function Oc(r,t){return _e[0]=r[t],_e[1]=r[t+1],_e[2]=r[t+2],_e[3]=r[t+3],js[0]}var Xs=new Float64Array([-0]),_t=new Uint8Array(Xs.buffer);function Kc(r,t,e){Xs[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function Mc(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],Xs[0]}var Wd=BigInt(Number.MAX_SAFE_INTEGER),Gd=BigInt(Number.MIN_SAFE_INTEGER),Kt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Ve;if(t<Wd&&t>Gd)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Fc&&(o=0n,++n>Fc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ve;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):Ve}},Ve=new Kt(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var Fc=4294967296n;function Hc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function qc(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Zs(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Xt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function qn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ys=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Xt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Xt(this,4);return qn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xt(this,4);return qn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xt(this,4);let t=Oc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Xt(this,4);let t=Mc(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Xt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return qc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Xt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Xt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Kt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Xt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Xt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Xt(this,8);let t=qn(this.buf,this.pos+=4),e=qn(this.buf,this.pos+=4);return new Kt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=$s(this.buf,this.pos);return this.pos+=nt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Js(r){return new Ys(r instanceof Uint8Array?r:r.subarray())}function Zt(r,t,e){let n=Js(r);return t.decode(n,void 0,e)}function Qs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return gt(i);o+i>t&&(n=gt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var We=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ti(){}var ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},zd=Qs();function $d(r){return globalThis.Buffer!=null?gt(r):zd(r)}var Wr=class{len;head;tail;states;constructor(){this.len=0,this.head=new We(ti,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new We(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ni((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Vn,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Kt.fromBigInt(t);return this._push(Vn,e.length(),e)}uint64Number(t){return this._push(zs,nt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Kt.fromBigInt(t).zzEncode();return this._push(Vn,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(Vn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ei,1,t?1:0)}fixed32(t){return this._push(Vr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(Vr,4,e.lo)._push(Vr,4,e.hi)}fixed64Number(t){let e=Kt.fromNumber(t);return this._push(Vr,4,e.lo)._push(Vr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Uc,4,t)}double(t){return this._push(Kc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ei,1,0):this.uint32(e)._push(Xd,e,t)}string(t){let e=Hc(t);return e!==0?this.uint32(e)._push(Zs,e,t):this._push(ei,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new We(ti,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new We(ti,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=$d(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ei(r,t,e){t[e]=r&255}function jd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ni=class extends We{next;constructor(t,e){super(jd,t,e),this.next=void 0}};function Vn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Vr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Xd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Wr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Zd,t,r),this},Wr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Yd,t,r),this});function Zd(r,t,e){t.set(r,e)}function Yd(r,t,e){r.length<40?Zs(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(X(r),e)}function oi(){return new Wr}function Yt(r,t){let e=oi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var hr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(hr||(hr={}));function Wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ge(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Wn("enum",hr.VARINT,e,n)}function Jt(r,t){return Wn("message",hr.LENGTH_DELIMITED,r,t)}var Gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(pt||(pt={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>Ge(si)})(pt||(pt={}));var te;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(te||(te={}));var ii;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(ii||(ii={}));var zr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Gn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Gc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Gn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Le=Gc;var jr={};It(jr,{MAX_RSA_KEY_SIZE:()=>ci,generateRSAKeyPair:()=>Xc,jwkToJWKKeyPair:()=>Zc,jwkToPkcs1:()=>rp,jwkToPkix:()=>hi,jwkToRSAPrivateKey:()=>gi,pkcs1MessageToJwk:()=>ui,pkcs1MessageToRSAPrivateKey:()=>di,pkcs1ToJwk:()=>ep,pkcs1ToRSAPrivateKey:()=>jc,pkixMessageToJwk:()=>fi,pkixMessageToRSAPublicKey:()=>mi,pkixToJwk:()=>np,pkixToRSAPublicKey:()=>pi});var Jd=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]),Be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=new Uint32Array(64),ai=class extends cr{constructor(){super(64,32,8,!1),this.A=Be[0]|0,this.B=Be[1]|0,this.C=Be[2]|0,this.D=Be[3]|0,this.E=Be[4]|0,this.F=Be[5]|0,this.G=Be[6]|0,this.H=Be[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)Pe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Pe[f-15],g=Pe[f-2],x=Gt(d,7)^Gt(d,18)^d>>>3,m=Gt(g,17)^Gt(g,19)^g>>>10;Pe[f]=m+Pe[f-7]+x+Pe[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Gt(a,6)^Gt(a,11)^Gt(a,25),g=u+d+dc(a,c,l)+Jd[f]+Pe[f]|0,m=(Gt(n,2)^Gt(n,13)^Gt(n,22))+pc(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ee=Bn(()=>new ai);var dr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return $c(this.jwk,e,t)}},$r=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t){return zc(this.jwk,t)}};var ci=8192,li=18,Qd=1062,tp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ep(r){let t=ae(r);return ui(t)}function ui(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function rp(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new Q("JWK was missing components");return be([Nt(Uint8Array.from([0])),Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url")),Nt(X(r.d,"base64url")),Nt(X(r.p,"base64url")),Nt(X(r.q,"base64url")),Nt(X(r.dp,"base64url")),Nt(X(r.dq,"base64url")),Nt(X(r.qi,"base64url"))]).subarray()}function np(r){let t=ae(r,{offset:0});return fi(t)}function fi(r){let t=ae(r[1],{offset:0});return{kty:"RSA",n:H(t[0],"base64url"),e:H(t[1],"base64url")}}function hi(r){if(r.n==null||r.e==null)throw new Q("JWK was missing components");return be([tp,Tn(be([Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url"))]))]).subarray()}function jc(r){let t=ae(r);return di(t)}function di(r){let t=ui(r);return gi(t)}function pi(r,t){if(r.byteLength>=Qd)throw new Je("Key size is too large");let e=ae(r,{offset:0});return mi(e,r,t)}function mi(r,t,e){let n=fi(r);if(e==null){let o=ee(te.encode({Type:pt.RSA,Data:t}));e=Ct(li,o)}return new dr(n,e)}function gi(r){if(Jc(r)>ci)throw new Q("Key size is too large");let t=Zc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}async function Xc(r){if(r>ci)throw new Q("Key size is too large");let t=await Yc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}function Zc(r){if(r==null)throw new Q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Yc(r){let t=await Le.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await op(t);return{privateKey:e[0],publicKey:e[1]}}async function zc(r,t){let e=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Le.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function $c(r,t,e){let n=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Le.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function op(r){if(r.privateKey==null||r.publicKey==null)throw new Q("Private and public key are required");return Promise.all([Le.get().subtle.exportKey("jwk",r.privateKey),Le.get().subtle.exportKey("jwk",r.publicKey)])}function Jc(r){if(r.kty!=="RSA")throw new Q("invalid key type");if(r.n==null)throw new Q("invalid key modulus");return X(r.n,"base64url").length*8}var zn=class extends ar{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ur(t);let n=Se(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return ir(this),this.iHash.update(t),this}digestInto(t){ir(this),sr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},pr=(r,t,e)=>new zn(r,t).update(e).digest();pr.create=(r,t)=>new zn(r,t);function Qc(r){r.lowS!==void 0&&zt("lowS",r.lowS),r.prehash!==void 0&&zt("prehash",r.prehash)}function sp(r){let t=Fr(r);Ht(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:ip,hexToBytes:ap}=Nn,yi=class extends Error{constructor(t=""){super(t)}},de={Err:yi,_tlv:{encode:(r,t)=>{let{Err:e}=de;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Me(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Me(o.length/2|128):"";return Me(r)+s+o+t},decode(r,t){let{Err:e}=de,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=de;if(r<pe)throw new t("integer: negative integers are not allowed");let e=Me(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=de;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ip(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=de,o=typeof r=="string"?ap(r):r;lr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=de,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},pe=BigInt(0),xt=BigInt(1),Xw=BigInt(2),tl=BigInt(3),Zw=BigInt(4);function cp(r){let t=sp(r),{Fp:e}=t,n=Te(t.n,t.nBitLength),o=t.toBytes||((m,h,w)=>{let b=h.toAffine();return he(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let h=m.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(m){let{a:h,b:w}=t,b=e.sqr(m),p=e.mul(b,m);return e.add(e.add(p,e.mul(m,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Kr(m,xt,t.n)}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:b,n:p}=t;if(h&&typeof m!="bigint"){if(Ie(m)&&(m=le(m)),typeof m!="string"||!h.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let I;try{I=typeof m=="bigint"?m:ue(st("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return b&&(I=Y(I,p)),St("private key",I,xt,p),I}function l(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let u=He((m,h)=>{let{px:w,py:b,pz:p}=m;if(e.eql(p,e.ONE))return{x:w,y:b};let I=m.is0();h==null&&(h=I?e.ONE:e.inv(p));let P=e.mul(w,h),B=e.mul(b,h),v=e.mul(p,h);if(I)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:P,y:B}}),f=He(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=m.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,b){if(this.px=h,this.py=w,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:b}=h||{};if(!h||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=I=>e.eql(I,e.ZERO);return p(w)&&p(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(w[p])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(st("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Kn(d,n,h,w)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.eql(e.mul(w,B),e.mul(I,p)),L=e.eql(e.mul(b,B),e.mul(P,p));return v&&L}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,b=e.mul(w,tl),{px:p,py:I,pz:P}=this,B=e.ZERO,v=e.ZERO,L=e.ZERO,T=e.mul(p,p),K=e.mul(I,I),N=e.mul(P,P),O=e.mul(p,I);return O=e.add(O,O),L=e.mul(p,P),L=e.add(L,L),B=e.mul(h,L),v=e.mul(b,N),v=e.add(B,v),B=e.sub(K,v),v=e.add(K,v),v=e.mul(B,v),B=e.mul(O,B),L=e.mul(b,L),N=e.mul(h,N),O=e.sub(T,N),O=e.mul(h,O),O=e.add(O,L),L=e.add(T,T),T=e.add(L,T),T=e.add(T,N),T=e.mul(T,O),v=e.add(v,T),N=e.mul(I,P),N=e.add(N,N),T=e.mul(N,O),B=e.sub(B,T),L=e.mul(N,K),L=e.add(L,L),L=e.add(L,L),new d(B,v,L)}add(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.ZERO,L=e.ZERO,T=e.ZERO,K=t.a,N=e.mul(t.b,tl),O=e.mul(w,I),F=e.mul(b,P),C=e.mul(p,B),_=e.add(w,b),E=e.add(I,P);_=e.mul(_,E),E=e.add(O,F),_=e.sub(_,E),E=e.add(w,p);let y=e.add(I,B);return E=e.mul(E,y),y=e.add(O,C),E=e.sub(E,y),y=e.add(b,p),v=e.add(P,B),y=e.mul(y,v),v=e.add(F,C),y=e.sub(y,v),T=e.mul(K,E),v=e.mul(N,C),T=e.add(v,T),v=e.sub(F,T),T=e.add(F,T),L=e.mul(v,T),F=e.add(O,O),F=e.add(F,O),C=e.mul(K,C),E=e.mul(N,E),F=e.add(F,C),C=e.sub(O,C),C=e.mul(K,C),E=e.add(E,C),O=e.mul(F,E),L=e.add(L,O),O=e.mul(y,E),v=e.mul(_,v),v=e.sub(v,O),O=e.mul(_,F),T=e.mul(y,T),T=e.add(T,O),new d(v,L,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:b}=t;St("scalar",h,pe,b);let p=d.ZERO;if(h===pe)return p;if(this.is0()||h===xt)return this;if(!w||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:I,k1:P,k2neg:B,k2:v}=w.splitScalar(h),L=p,T=p,K=this;for(;P>pe||v>pe;)P&xt&&(L=L.add(K)),v&xt&&(T=T.add(K)),K=K.double(),P>>=xt,v>>=xt;return I&&(L=L.negate()),B&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),L.add(T)}multiply(h){let{endo:w,n:b}=t;St("scalar",h,xt,b);let p,I;if(w){let{k1neg:P,k1:B,k2neg:v,k2:L}=w.splitScalar(h),{p:T,f:K}=this.wNAF(B),{p:N,f:O}=this.wNAF(L);T=x.constTimeNegate(P,T),N=x.constTimeNegate(v,N),N=new d(e.mul(N.px,w.beta),N.py,N.pz),p=T.add(N),I=K.add(O)}else{let{p:P,f:B}=this.wNAF(h);p=P,I=B}return d.normalizeZ([p,I])[0]}multiplyAndAddUnsafe(h,w,b){let p=d.BASE,I=(B,v)=>v===pe||v===xt||!B.equals(p)?B.multiplyUnsafe(v):B.multiply(v),P=I(this,w).add(I(h,b));return P.is0()?void 0:P}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===xt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===xt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return zt("isCompressed",h),le(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,x=On(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function lp(r){let t=Fr(r);return Ht(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function el(r){let t=lp(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Y(C,n)}function a(C){return kn(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=cp({...t,toBytes(C,_,E){let y=_.toAffine(),A=e.toBytes(y.x),S=he;return zt("isCompressed",E),E?S(Uint8Array.from([_.hasEvenY()?2:3]),A):S(Uint8Array.from([4]),A,e.toBytes(y.y))},fromBytes(C){let _=C.length,E=C[0],y=C.subarray(1);if(_===o&&(E===2||E===3)){let A=ue(y);if(!Kr(A,xt,e.ORDER))throw new Error("Point is not on curve");let S=u(A),R;try{R=e.sqrt(S)}catch(q){let M=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+M)}let D=(R&xt)===xt;return(E&1)===1!==D&&(R=e.neg(R)),{x:A,y:R}}else if(_===s&&E===4){let A=e.fromBytes(y.subarray(0,e.BYTES)),S=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:A,y:S}}else{let A=o,S=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+S+", got "+_)}}}),d=C=>le(Ce(C,t.nByteLength));function g(C){let _=n>>xt;return C>_}function x(C){return g(C)?i(-C):C}let m=(C,_,E)=>ue(C.slice(_,E));class h{constructor(_,E,y){this.r=_,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(_){let E=t.nByteLength;return _=st("compactSignature",_,E*2),new h(m(_,0,E),m(_,E,2*E))}static fromDER(_){let{r:E,s:y}=de.toSig(st("DER",_));return new h(E,y)}assertValidity(){St("r",this.r,xt,n),St("s",this.s,xt,n)}addRecoveryBit(_){return new h(this.r,this.s,_)}recoverPublicKey(_){let{r:E,s:y,recovery:A}=this,S=B(st("msgHash",_));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=(A&1)===0?"02":"03",U=c.fromHex(D+d(R)),q=a(R),M=i(-S*q),G=i(y*q),j=c.BASE.multiplyAndAddUnsafe(U,M,G);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Fe(this.toDERHex())}toDERHex(){return de.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Fe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ns(t.n);return Ac(t.randomBytes(C),t.n)},precompute(C=8,_=c.BASE){return _._setWindowSize(C),_.multiply(BigInt(3)),_}};function b(C,_=!0){return c.fromPrivateKey(C).toRawBytes(_)}function p(C){let _=Ie(C),E=typeof C=="string",y=(_||E)&&C.length;return _?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function I(C,_,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(l(C)).toRawBytes(E)}let P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let _=ue(C),E=C.length*8-t.nBitLength;return E>0?_>>BigInt(E):_},B=t.bits2int_modN||function(C){return i(P(C))},v=Mr(t.nBitLength);function L(C){return St("num < 2^"+t.nBitLength,C,pe,v),Ce(C,t.nByteLength)}function T(C,_,E=K){if(["recovered","canonical"].some(at=>at in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:A}=t,{lowS:S,prehash:R,extraEntropy:D}=E;S==null&&(S=!0),C=st("msgHash",C),Qc(E),R&&(C=st("prehashed msgHash",y(C)));let U=B(C),q=l(_),M=[L(q),L(U)];if(D!=null&&D!==!1){let at=D===!0?A(e.BYTES):D;M.push(st("extraEntropy",at))}let G=he(...M),j=U;function it(at){let ut=P(at);if(!f(ut))return;let vt=a(ut),Dt=c.BASE.multiply(ut).toAffine(),Rt=i(Dt.x);if(Rt===pe)return;let Qt=i(vt*i(j+Rt*q));if(Qt===pe)return;let ne=(Dt.x===Rt?0:2)|Number(Dt.y&xt),_r=Qt;return S&&g(Qt)&&(_r=x(Qt),ne^=1),new h(Rt,_r,ne)}return{seed:G,k2sig:it}}let K={lowS:t.lowS,prehash:!1},N={lowS:t.lowS,prehash:!1};function O(C,_,E=K){let{seed:y,k2sig:A}=T(C,_,E),S=t;return Ls(S.hash.outputLen,S.nByteLength,S.hmac)(y,A)}c.BASE._setWindowSize(8);function F(C,_,E,y=N){let A=C;_=st("msgHash",_),E=st("publicKey",E);let{lowS:S,prehash:R,format:D}=y;if(Qc(y),"strict"in y)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");let U=typeof A=="string"||Ie(A),q=!U&&!D&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,G;try{if(q&&(M=new h(A.r,A.s)),U){try{D!=="compact"&&(M=h.fromDER(A))}catch(ne){if(!(ne instanceof de.Err))throw ne}!M&&D!=="der"&&(M=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!M||S&&M.hasHighS())return!1;R&&(_=t.hash(_));let{r:j,s:it}=M,at=B(_),ut=a(it),vt=i(at*ut),Dt=i(j*ut),Rt=c.BASE.multiplyAndAddUnsafe(G,vt,Dt)?.toAffine();return Rt?i(Rt.x)===j:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:I,sign:O,verify:F,ProjectivePoint:c,Signature:h,utils:w}}function up(r){return{hash:r,hmac:(t,...e)=>pr(r,t,Ss(...e)),randomBytes:Or}}function rl(r,t){let e=n=>el({...r,...up(n)});return{...e(t),create:e}}var sl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),fp=BigInt(1),wi=BigInt(2),ol=(r,t)=>(r+t/wi)/t;function hp(r){let t=sl,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=ct(u,e,t)*u%t,d=ct(f,e,t)*u%t,g=ct(d,wi,t)*l%t,x=ct(g,o,t)*g%t,m=ct(x,s,t)*x%t,h=ct(m,a,t)*m%t,w=ct(h,c,t)*h%t,b=ct(w,a,t)*m%t,p=ct(b,e,t)*u%t,I=ct(p,i,t)*x%t,P=ct(I,n,t)*l%t,B=ct(P,wi,t);if(!xi.eql(xi.sqr(B),r))throw new Error("Cannot find square root");return B}var xi=Te(sl,void 0,void 0,{sqrt:hp}),ze=rl({a:BigInt(0),b:BigInt(7),Fp:xi,n:nl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=nl,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-fp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=ol(s*r,t),c=ol(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ee),sx=BigInt(0);var ix=ze.ProjectivePoint;function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function al(r,t,e){let n=ie.digest(e instanceof Uint8Array?e:e.subarray());if(il(n))return n.then(({digest:o})=>ze.verify(t,o,r)).catch(o=>{throw new zr(String(o))});try{return ze.verify(t,n.digest,r)}catch(o){throw new zr(String(o))}}var $n=class{type="secp256k1";raw;_key;constructor(t){this._key=ll(t),this.raw=cl(this._key)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return al(this._key,e,t)}};function bi(r){return new $n(r)}function cl(r){return ze.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ll(r){try{return ze.ProjectivePoint.fromHex(r),r}catch(t){throw new Je(String(t))}}function Xr(r,t){let{Type:e,Data:n}=te.decode(r),o=n??new Uint8Array;switch(e){case pt.RSA:return pi(o,t);case pt.Ed25519:return Hs(o);case pt.secp256k1:return bi(o);case pt.ECDSA:return Es(o);default:throw new ke}}function ul(r){let{Type:t,Data:e}=te.decode(r.digest),n=e??new Uint8Array;switch(t){case pt.Ed25519:return Hs(n);case pt.secp256k1:return bi(n);case pt.ECDSA:return Es(n);default:throw new ke}}function Ee(r){return te.encode({Type:pt[r.type],Data:r.raw})}var fl=Symbol.for("nodejs.util.inspect.custom"),dp=114,Zr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$o]=!0;toString(){return this.string==null&&(this.string=et.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(dp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[fl](){return`PeerId(${this.toString()})`}},Yr=class extends Zr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Jr=class extends Zr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Qr=class extends Zr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},pp=2336,tn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Wt.digest(X(this.url))}[fl](){return`PeerId(${this.url})`}[$o]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(pp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};var mp=114,hl=2336;function mr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=xe(et.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return gp(dt.parse(r));if(t==null)throw new Q('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=xe(t.decode(r))}return dl(e)}function Ei(r){if(r.type==="Ed25519")return new Jr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Qr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yr({multihash:r.toCID().multihash,publicKey:r});throw new ke}function dl(r){if(wp(r))return new Yr({multihash:r});if(yp(r))try{let t=ul(r);if(t.type==="Ed25519")return new Jr({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Qr({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new tn(new URL(e))}throw new En("Supplied PeerID Multihash is invalid")}function gp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mp&&r.code!==hl)throw new bn("Supplied PeerID CID is invalid");if(r.code===hl){let t=H(r.multihash.digest);return new tn(new URL(t))}return dl(r.multihash)}function yp(r){return r.code===Wt.code}function wp(r){return r.code===ie.code}var jn=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var pl=45,xp=15,gr=new jn;function Si(r){if(!(r.length>xp))return gr.new(r).parseWith(()=>gr.readIPv4Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return gr.new(r).parseWith(()=>gr.readIPv6Addr())}function Xn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>pl)return;let e=gr.new(r).parseWith(()=>gr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var bb=parseInt("0xFFFF",16),Eb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Zn(r){return!!Si(r)}function Yn(r){return!!Ai(r)}function Jn(r){return!!Xn(r)}var yl=Zn,vp=Yn,vi=function(r){let t=0;if(r=r.toString().trim(),yl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(vp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=yl(e[n]),i;s&&(i=vi(e[n]),e[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},wl=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var yr={},Ii={},Cp=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Cp.forEach(r=>{let t=Tp(...r);Ii[t.code]=t,yr[t.name]=t});function Tp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function ot(r){if(typeof r=="number"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yr[r]!=null)return yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var o1=ot("ip4"),s1=ot("ip6"),i1=ot("ipcidr");function Li(r,t){switch(ot(r).code){case 4:case 41:return Lp(t);case 42:return _i(t);case 43:return H(t,"base10");case 6:case 273:case 33:case 132:return El(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return _i(t);case 421:return Dp(t);case 444:return bl(t);case 445:return bl(t);case 466:return Rp(t);case 481:return globalThis.encodeURIComponent(_i(t));default:return H(t,"base16")}}function Bi(r,t){switch(ot(r).code){case 4:return xl(t);case 41:return xl(t);case 42:return Ti(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return Pi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ti(t);case 421:return Bp(t);case 444:return Np(t);case 445:return kp(t);case 466:return Pp(t);case 481:return Ti(globalThis.decodeURIComponent(t));default:return X(t,"base16")}}var Ci=Object.values(Oe).map(r=>r.decoder),_p=function(){let r=Ci[0].or(Ci[1]);return Ci.slice(2).forEach(t=>r=r.or(t)),r}();function xl(r){if(!Jn(r))throw new Error("invalid ip address");return vi(r)}function Lp(r){let t=wl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Jn(t))throw new Error("invalid ip address");return t}function Pi(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function El(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ti(r){let t=X(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function _i(r){let t=Ot(r);if(r=r.slice(nt(t)),r.length!==t)throw new Error("inconsistent lengths");return H(r)}function Bp(r){let t;r[0]==="Q"||r[0]==="1"?t=xe(et.decode(`z${r}`)).bytes:t=dt.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Pp(r){let t=_p.decode(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Rp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+H(e,"base64url")}function Dp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return H(e,"base58btc")}function Np(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=se.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Pi(n);return yt([e,o],e.length+o.length)}function kp(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=se.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Pi(n);return yt([e,o],e.length+o.length)}function bl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=H(t,"base32"),o=El(e);return`${n}:${o}`}function Sl(r){r=Ri(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ot(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new Qn("invalid address: "+r);if(a.path===!0){n=Ri(o.slice(s).join("/")),t.push([a.code,Bi(a.code,n)]),e.push([a.code,n]);break}let c=Bi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Li(a.code,c)])}return{string:Al(e),bytes:to(t),tuples:t,stringTuples:e,path:n}}function Di(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Ot(r,o),i=nt(s),a=ot(s),c=Up(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new Qn("Invalid address Uint8Array: "+H(r,"base16"));t.push([s,l]);let u=Li(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Al(e),tuples:t,stringTuples:e,path:n}}function Al(r){let t=[];return r.map(e=>{let n=ot(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ri(t.join("/"))}function to(r){return yt(r.map(t=>{let e=ot(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Up(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Ot(t instanceof Uint8Array?t:Uint8Array.from(t));return e+nt(e)}}function Ri(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Qn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Op=Symbol.for("nodejs.util.inspect.custom"),ki=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Kp=[ot("dns").code,ot("dns4").code,ot("dns6").code,ot("dnsaddr").code],Ni=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},eo=class r{bytes;#t;#e;#r;#n;[ki]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Di(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Sl(t)}else if(Il(t))e=Di(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=ot("tcp"),a=ot("udp"),c=ot("ip4"),l=ot("ip6"),u=ot("dns6"),f=ot("ip6zone");for(let[g,x]of this.stringTuples())g===f.code&&(s=`%${x??""}`),Kp.includes(g)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${x??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",o=parseInt(x??"")),(g===c.code||g===l.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",n=`${x??""}${s}`,t=g===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},ot(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>ot(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(to(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===yr.p2p.code&&t.push([n,o]),n===yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(et.decode(`z${n}`),"base58btc"):H(dt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=vl.get(e.name);if(n==null)throw new Ni(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>re(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Op](){return`Multiaddr(${this.#t})`}};var vl=new Map;function Il(r){return!!r?.[ki]}function re(r){return new eo(r)}var Mp=r=>r.toString().split("/").slice(1),wr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>wr(e=>e===r).match(t),pattern:r}),$e=()=>({match:r=>wr(t=>typeof t=="string").match(r),pattern:"{string}"}),en=()=>({match:r=>wr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{et.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),rn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Dr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),J=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Lt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),$=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function lt(...r){function t(o){let s=Mp(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var no=$(z("dns4"),$e()),oo=$(z("dns6"),$e()),so=$(z("dnsaddr"),$e()),Oi=$(z("dns"),$e()),O1=lt(no,J(rt())),K1=lt(oo,J(rt())),M1=lt(so,J(rt())),F1=lt(Lt(Oi,so,no,oo),J(rt())),Cl=$(z("ip4"),wr(Zn)),Tl=$(z("ip6"),wr(Yn)),Ki=Lt(Cl,Tl),me=Lt(Ki,Oi,no,oo,so),H1=lt(Lt(Ki,$(Lt(Oi,so,no,oo),J(rt())))),q1=lt(Cl),V1=lt(Tl),W1=lt(Ki),Mi=$(me,z("tcp"),en()),nn=$(me,z("udp"),en()),G1=lt($(Mi,J(rt()))),z1=lt(nn),Fi=$(nn,z("quic"),J(rt())),io=$(nn,z("quic-v1"),J(rt())),Fp=Lt(Fi,io),$1=lt(Fi),j1=lt(io),Ui=Lt(me,Mi,nn,Fi,io),_l=Lt($(Ui,z("ws"),J(rt()))),X1=lt(_l),Ll=Lt($(Ui,z("wss"),J(rt())),$(Ui,z("tls"),J($(z("sni"),$e())),z("ws"),J(rt()))),Z1=lt(Ll),Bl=$(nn,z("webrtc-direct"),J(rn()),J(rn()),J(rt())),Pl=lt(Bl),Rl=$(io,z("webtransport"),J(rn()),J(rn()),J(rt())),Y1=lt(Rl),ro=Lt(_l,Ll,$(Mi,J(rt())),$(Fp,J(rt())),$(me,J(rt())),Bl,Rl,rt()),Dl=lt(ro),Hp=$(ro,z("p2p-circuit"),rt()),J1=lt(Hp),qp=Lt($(ro,z("p2p-circuit"),z("webrtc"),J(rt())),$(ro,z("webrtc"),J(rt())),$(z("webrtc"),J(rt()))),Nl=lt(qp),Vp=Lt($(me,z("tcp"),en(),z("http"),J(rt())),$(me,z("http"),J(rt()))),Q1=lt(Vp),Wp=Lt($(me,z("tcp"),Lt($(z("443"),z("http")),$(en(),z("https"))),J(rt())),$(me,z("tls"),z("http"),J(rt())),$(me,z("https"),J(rt()))),t2=lt(Wp),Gp=Lt($(z("memory"),$e(),J(rt()))),e2=lt(Gp);var Bt;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>Ge(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Bt||(Bt={}));var kl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Hi=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Ul="libp2p+webrtc+v1/";var Ol=466,Kl=2*1024*1024,Ml=30*1e3,xr=16*1024;function zp(r=xr){let t=nt(r-nt(r)),e=1+nt(Object.keys(Bt.Flag).length-1),n=1,o=r-t-e-n,s=nt(o);return t+e+n+s}var Fl=zp(),Hl=5e3,ql=5e3,Vl=3e4,qi="/webrtc",on="/webrtc-signaling/0.0.1";var Wl=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},$p=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var jp=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Xp=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var Zp=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Yp=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Jp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Qp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Gl=3,tm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Jp]],zl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function jl(r){return r?$l(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Yp:typeof navigator<"u"?$l(navigator.userAgent):nm()}function em(r){return r!==""&&tm.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function $l(r){var t=em(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Zp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Gl&&(o=Wl(Wl([],o,!0),om(Gl-o.length),!0)):o=[];var s=o.join("."),i=rm(r),a=Qp.exec(r);return a&&a[1]?new Xp(e,s,i,a[1]):new $p(e,s,i)}function rm(r){for(var t=0,e=zl.length;t<e;t++){var n=zl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function nm(){var r=typeof process<"u"&&process.version;return r?new jp(process.version.slice(1)):null}function om(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function Z(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Vi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Wi=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Xl=r=>globalThis.DOMException===void 0?new Wi(r):new DOMException(r),Zl=r=>{let t=r.reason===void 0?Xl("This operation was aborted."):r.reason;return t instanceof Error?t:Xl(t)};function sn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:g}=t;g.aborted&&f(Zl(g)),a=()=>{f(Zl(g))},g.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Vi;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(g){f(g)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Yl=jl(),an=Yl!=null&&Yl.name==="firefox",ao=async function*(){},co=async r=>{};function Jl(r,t,e=Vl,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=Z(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await sn(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Gi(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??kl.map(t=>({urls:[t]})),r}var Ql=(r=32)=>Ul+[...Array(r)].map(()=>Hi.at(Math.floor(Math.random()*Hi.length))).join("");var je=class{log;peerConnection;remoteAddr;timeline;metrics;source=ao();sink=co;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var lo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},br=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new lo(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new lo(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var zi=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Er(r={}){return sm(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function sm(r,t){t=t??{};let e=t.onEnd,n=new br,o,s,i,a=Z(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){w(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Z()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new br,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new br,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,p;w!=null&&(b=new Promise((I,P)=>{p=()=>{P(new zi)},w.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&w!=null&&w?.removeEventListener("abort",p)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(h){return m.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return m.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:h=>m.onEmpty(h)},o}var uo=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new uo(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new uo(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function tu(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function eu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ru(r,t){let e=tu(r).return?.();eu(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var im=5e3;function $i(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var fo=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=Z(),this.closed=Z(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??im,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Er({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new Ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);$i(o)&&await o}let n=()=>{ru(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new V(o):o;let s=this.sendData(o,e);$i(s)&&(this.sendingData=Z(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await bt(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await bt(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await bt(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await bt(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();$i(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new xn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function ji(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var ho=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},cn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mo(r){return r[Symbol.asyncIterator]!=null}function nu(r,t){if(r.byteLength>t)throw new Sr("Message length too long")}var yo=r=>{let t=nt(r),e=gt(t);return qt(r,e),yo.bytes=t,e};yo.bytes=0;function ln(r,t){t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;function*o(s){nu(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mo(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ln.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;return nu(r,n),new V(e(r.byteLength),r)};var Xe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xe||(Xe={}));var Xi=r=>{let t=Ot(r);return Xi.bytes=nt(t),t};Xi.bytes=0;function Ze(r,t){let e=new V,n=Xe.LENGTH,o=-1,s=t?.lengthDecoder??Xi,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Xe.LENGTH)try{if(o=s(e),o<0)throw new ho("Invalid message length");if(o>a)throw new Sr("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=Xe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new po("Message length length too long");break}throw l}if(n===Xe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=Xe.LENGTH}}}return mo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}()}Ze.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Ze(n,{...t??{},onLength:s=>{e=s}})};var Zi=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function un(r,t,e,n){let o=new Zi(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Yi=class extends fo{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await sn(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Er(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Ml,this.maxBufferedAmount=t.maxBufferedAmount??Kl,this.maxMessageSize=(t.maxMessageSize??xr)-Fl,this.receiveFinAck=Z(),this.finAckTimeout=t.closeTimeout??Hl,this.openTimeout=t.openTimeout??ql,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Ne("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Ze(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new V(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ne(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=ji([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await un(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(e&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=ji([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await un(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new An(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(t.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(t){for(this.log.trace("-> will send %d bytes",t.byteLength),t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Bt.encode({message:n}),s=ln.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),t.consume(e)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Bt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Bt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await bt(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(Bt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Bt.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Bt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Bt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Bt.Flag.RESET&&this.reset(),e.flag===Bt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Bt.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Bt.encode({flag:t}),n=ln.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Ar(r){let{channel:t,direction:e}=r;return new Yi({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Re=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??qi,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Ar({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new Ji(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Ji=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??qi,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,s=Ar({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Jl(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=ao();sink=co;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Ar({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var wo=globalThis.RTCPeerConnection,xo=globalThis.RTCSessionDescription,ou=globalThis.RTCIceCandidate;var Qi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Z(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Z(),await bt(this.readNext.promise,e?.signal,e)}};function su(){return new Qi}var bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function iu(r,t){let e=su();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new V;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new bo("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Eo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},So=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ao=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function au(r,t={}){let e=iu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Eo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ao("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new So("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function vo(r,t){let e=au(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Mt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var De=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Vt=class extends De{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Io=class extends De{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Co=class extends De{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},To=class extends De{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Ut;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>Ge(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Ut||(Ut={}));var _o=async(r,t,e)=>{try{let n=Z();for(lm(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Ut.Type.ICE_CANDIDATE)throw new Sn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new Mt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new ou(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new Mt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&Lo(r)!=="connected")throw n}};function Lo(r){return an?r.iceConnectionState:r.connectionState}function lm(r,t){r[an?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Lo(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new wn("RTCPeerConnection was closed"));break;default:break}}}async function cu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=lu(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new Q("Relay peer was missing");let d=s.getConnections(mr(f)),g,x=!1;d.length===0?(l?.(new Mt("webrtc:dial-relay")),g=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new Mt("webrtc:reuse-relay-connection")),g=d[0]);try{l?.(new Mt("webrtc:open-signaling-stream"));let m=await g.newStream(on,{signal:e,runOnLimitedConnection:!0}),h=vo(m).pb(Ut),w=new wo(r),b=new Re({logger:c},{peerConnection:w,dataChannelOptions:t});try{let p=w.createDataChannel("init");w.onicecandidate=({candidate:v})=>{let L=JSON.stringify(v?.toJSON()??null);a.trace("initiator sending ICE candidate %o",v),h.write({type:Ut.Type.ICE_CANDIDATE,data:L},{signal:e}).catch(T=>{a.error("error sending ICE candidate",T)})},w.onicecandidateerror=v=>{a.error("initiator ICE candidate error",v)};let I=await w.createOffer().catch(v=>{throw a.error("could not execute createOffer",v),new Vt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",I.sdp),l?.(new Mt("webrtc:send-sdp-offer")),await h.write({type:Ut.Type.SDP_OFFER,data:I.sdp},{signal:e}),await w.setLocalDescription(I).catch(v=>{throw a.error("could not execute setLocalDescription",v),new Vt("Failed to set localDescription")}),l?.(new Mt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let P=await h.read({signal:e});if(P.type!==Ut.Type.SDP_ANSWER)throw new Vt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",P.data);let B=new xo({type:"answer",sdp:P.data});return await w.setRemoteDescription(B).catch(v=>{throw a.error("could not execute setRemoteDescription",v),new Vt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Mt("webrtc:read-ice-candidates")),await _o(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Mt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await m.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:w,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),w.close(),m.abort(p),p}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(x)try{await g.close({signal:e})}catch(m){g.abort(m)}}}var uu=lt(Dl.matchers[0],z("p2p-circuit")),Bo=class r extends Qe{transportManager;shutdownController;events;constructor(t,e){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=e.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>uu.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof r)).map(t=>t.getAddrs().filter(e=>uu.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function fu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=vo(t).pb(Ut);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ut.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Ut.Type.SDP_OFFER)throw new Vt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new xo({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Vt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Vt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ut.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Vt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await _o(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Lo(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Po=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[tr]=["@libp2p/transport"];[Ma]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(on,t=>{let e=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,e).catch(n=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,n)}).finally(()=>{e.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(on),this._started=!1}createListener(t){return new Bo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Nl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await cu({rtcConfiguration:await Gi(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new je(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress,signal:e.signal});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e},n){let o=new wo(await Gi(this.init.rtcConfiguration)),s=new Re(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await fu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new je(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s,signal:n}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function lu(r){let t=r.toString().split("/webrtc/");if(t.length!==2)throw new Q("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new Q("p2p-circuit protocol was not present in multiaddr");let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new Q("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new Q("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:mr(o)}}var Ro=class extends Qe{async listen(){throw new Co("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};var ta=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Z(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Z(),await bt(this.readNext.promise,e?.signal,e)}};function hu(){return new ta}var Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ea=class extends Error{code;constructor(t,e){super(t),this.code=e}},ra=class extends ea{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function du(r,t){let e=hu();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new V;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ra("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new V:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Do("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var No=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ko=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Uo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function na(r,t={}){let e=du(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new No("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Uo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ko("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function oa(){let r=Z(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function pu(){let r=oa(),t=oa();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}var sa=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Z(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Z(),await bt(this.readNext.promise,e?.signal,e)}};function mu(){return new sa}function um(r){return r[Symbol.asyncIterator]!=null}async function fm(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*hm(r){let t=mu();fm(r,t).catch(()=>{}),yield*t}function*dm(r){for(let t of r)yield*t}function pm(...r){let t=[];for(let e of r)um(e)||t.push(e);return t.length===r.length?dm(t):hm(r)}var gu=pm;function yu(r,...t){if(r==null)throw new Error("Empty pipeline");if(ia(r)){let n=r;r=()=>n.source}else if(xu(r)||wu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ia(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)ia(e[n])&&(e[n]=gm(e[n]));return mm(...e)}var mm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},wu=r=>r?.[Symbol.asyncIterator]!=null,xu=r=>r?.[Symbol.iterator]!=null,ia=r=>r==null?!1:r.sink!=null&&r.source!=null,gm=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Er({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(wu(s))o=async function*(){yield*s,n.end()};else if(xu(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return gu(n,o())}return r.source};var vr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Oo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function aa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Pt(r,...t){if(!aa(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function ca(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function bu(r,t){Pt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function la(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var ge=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Eu=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ym=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ym)throw new Error("Non little-endian hardware is not supported");function wm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ko(r){if(typeof r=="string")r=wm(r);else if(aa(r))r=Mo(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Su(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Au(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var ua=(r,t)=>{function e(n,...o){if(Pt(n),r.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Pt(u):Pt(u,r.nonceLength)}let s=r.tagLength;s&&o[1]!==void 0&&Pt(o[1]);let i=t(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Pt(f)}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Pt(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Pt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(e,r),e};function fa(r,t,e=!0){if(t===void 0)return new Uint8Array(r);if(t.length!==r)throw new Error("invalid output length, expected "+r+", got: "+t.length);if(e&&!xm(t))throw new Error("invalid output, must be aligned");return t}function ha(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function xm(r){return r.byteOffset%4===0}function Mo(r){return Uint8Array.from(r)}function ye(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Iu=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),bm=Iu("expand 16-byte k"),Em=Iu("expand 32-byte k"),Sm=ge(bm),Am=ge(Em);function k(r,t){return r<<t|r>>>32-t}function da(r){return r.byteOffset%4===0}var Fo=64,vm=16,Cu=2**32-1,vu=new Uint32Array;function Im(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Fo),u=ge(l),f=da(o)&&da(s),d=f?ge(o):vu,g=f?ge(s):vu;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=Cu)throw new Error("arx: counter overflow");let m=Math.min(Fo,c-x);if(f&&m===Fo){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<vm;w++)b=h+w,g[b]=d[b]^u[w];x+=Fo;continue}for(let h=0,w;h<m;h++)w=x+h,s[w]=o[w]^l[h];x+=m}}function pa(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Su({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Oo(o),Oo(i),la(s),la(e),(a,c,l,u,f=0)=>{Pt(a),Pt(c),Pt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Pt(u),Oo(f),f<0||f>=Cu)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let g=[],x=a.length,m,h;if(x===32)g.push(m=Mo(a)),h=Am;else if(x===16&&e)m=new Uint8Array(32),m.set(a),m.set(a,16),h=Sm,g.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);da(c)||g.push(c=Mo(c));let w=ge(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,ge(c.subarray(0,16)),w),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,g.push(c)}let p=ge(c);return Im(r,h,w,p,l,u,f,i),ye(...g),u}}var At=(r,t)=>r[t++]&255|(r[t++]&255)<<8,ma=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=Ko(t),Pt(t,32);let e=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),l=At(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=At(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],g=i[6],x=i[7],m=i[8],h=i[9],w=At(t,e+0),b=At(t,e+2),p=At(t,e+4),I=At(t,e+6),P=At(t,e+8),B=At(t,e+10),v=At(t,e+12),L=At(t,e+14),T=s[0]+(w&8191),K=s[1]+((w>>>13|b<<3)&8191),N=s[2]+((b>>>10|p<<6)&8191),O=s[3]+((p>>>7|I<<9)&8191),F=s[4]+((I>>>4|P<<12)&8191),C=s[5]+(P>>>1&8191),_=s[6]+((P>>>14|B<<2)&8191),E=s[7]+((B>>>11|v<<5)&8191),y=s[8]+((v>>>8|L<<8)&8191),A=s[9]+(L>>>5|o),S=0,R=S+T*a+K*(5*h)+N*(5*m)+O*(5*x)+F*(5*g);S=R>>>13,R&=8191,R+=C*(5*d)+_*(5*f)+E*(5*u)+y*(5*l)+A*(5*c),S+=R>>>13,R&=8191;let D=S+T*c+K*a+N*(5*h)+O*(5*m)+F*(5*x);S=D>>>13,D&=8191,D+=C*(5*g)+_*(5*d)+E*(5*f)+y*(5*u)+A*(5*l),S+=D>>>13,D&=8191;let U=S+T*l+K*c+N*a+O*(5*h)+F*(5*m);S=U>>>13,U&=8191,U+=C*(5*x)+_*(5*g)+E*(5*d)+y*(5*f)+A*(5*u),S+=U>>>13,U&=8191;let q=S+T*u+K*l+N*c+O*a+F*(5*h);S=q>>>13,q&=8191,q+=C*(5*m)+_*(5*x)+E*(5*g)+y*(5*d)+A*(5*f),S+=q>>>13,q&=8191;let M=S+T*f+K*u+N*l+O*c+F*a;S=M>>>13,M&=8191,M+=C*(5*h)+_*(5*m)+E*(5*x)+y*(5*g)+A*(5*d),S+=M>>>13,M&=8191;let G=S+T*d+K*f+N*u+O*l+F*c;S=G>>>13,G&=8191,G+=C*a+_*(5*h)+E*(5*m)+y*(5*x)+A*(5*g),S+=G>>>13,G&=8191;let j=S+T*g+K*d+N*f+O*u+F*l;S=j>>>13,j&=8191,j+=C*c+_*a+E*(5*h)+y*(5*m)+A*(5*x),S+=j>>>13,j&=8191;let it=S+T*x+K*g+N*d+O*f+F*u;S=it>>>13,it&=8191,it+=C*l+_*c+E*a+y*(5*h)+A*(5*m),S+=it>>>13,it&=8191;let at=S+T*m+K*x+N*g+O*d+F*f;S=at>>>13,at&=8191,at+=C*u+_*l+E*c+y*a+A*(5*h),S+=at>>>13,at&=8191;let ut=S+T*h+K*m+N*x+O*g+F*d;S=ut>>>13,ut&=8191,ut+=C*f+_*u+E*l+y*c+A*a,S+=ut>>>13,ut&=8191,S=(S<<2)+S|0,S=S+R|0,R=S&8191,S=S>>>13,D+=S,s[0]=R,s[1]=D,s[2]=U,s[3]=q,s[4]=M,s[5]=G,s[6]=j,s[7]=it,s[8]=at,s[9]=ut}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;ye(n)}update(t){ca(this);let{buffer:e,blockLen:n}=this;t=Ko(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){ye(this.h,this.r,this.buffer,this.pad)}digestInto(t){ca(this),bu(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function Cm(r){let t=(n,o)=>r(o).update(Ko(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Tu=Cm(r=>new ma(r));function Bu(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],g=t[3],x=t[4],m=t[5],h=t[6],w=t[7],b=o,p=e[0],I=e[1],P=e[2],B=i,v=a,L=c,T=l,K=u,N=f,O=d,F=g,C=x,_=m,E=h,y=w,A=b,S=p,R=I,D=P;for(let q=0;q<s;q+=2)B=B+K|0,A=k(A^B,16),C=C+A|0,K=k(K^C,12),B=B+K|0,A=k(A^B,8),C=C+A|0,K=k(K^C,7),v=v+N|0,S=k(S^v,16),_=_+S|0,N=k(N^_,12),v=v+N|0,S=k(S^v,8),_=_+S|0,N=k(N^_,7),L=L+O|0,R=k(R^L,16),E=E+R|0,O=k(O^E,12),L=L+O|0,R=k(R^L,8),E=E+R|0,O=k(O^E,7),T=T+F|0,D=k(D^T,16),y=y+D|0,F=k(F^y,12),T=T+F|0,D=k(D^T,8),y=y+D|0,F=k(F^y,7),B=B+N|0,D=k(D^B,16),E=E+D|0,N=k(N^E,12),B=B+N|0,D=k(D^B,8),E=E+D|0,N=k(N^E,7),v=v+O|0,A=k(A^v,16),y=y+A|0,O=k(O^y,12),v=v+O|0,A=k(A^v,8),y=y+A|0,O=k(O^y,7),L=L+F|0,S=k(S^L,16),C=C+S|0,F=k(F^C,12),L=L+F|0,S=k(S^L,8),C=C+S|0,F=k(F^C,7),T=T+K|0,R=k(R^T,16),_=_+R|0,K=k(K^_,12),T=T+K|0,R=k(R^T,8),_=_+R|0,K=k(K^_,7);let U=0;n[U++]=i+B|0,n[U++]=a+v|0,n[U++]=c+L|0,n[U++]=l+T|0,n[U++]=u+K|0,n[U++]=f+N|0,n[U++]=d+O|0,n[U++]=g+F|0,n[U++]=x+C|0,n[U++]=m+_|0,n[U++]=h+E|0,n[U++]=w+y|0,n[U++]=b+A|0,n[U++]=p+S|0,n[U++]=I+R|0,n[U++]=P+D|0}function Tm(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],g=t[5],x=t[6],m=t[7],h=e[0],w=e[1],b=e[2],p=e[3];for(let P=0;P<20;P+=2)o=o+c|0,h=k(h^o,16),d=d+h|0,c=k(c^d,12),o=o+c|0,h=k(h^o,8),d=d+h|0,c=k(c^d,7),s=s+l|0,w=k(w^s,16),g=g+w|0,l=k(l^g,12),s=s+l|0,w=k(w^s,8),g=g+w|0,l=k(l^g,7),i=i+u|0,b=k(b^i,16),x=x+b|0,u=k(u^x,12),i=i+u|0,b=k(b^i,8),x=x+b|0,u=k(u^x,7),a=a+f|0,p=k(p^a,16),m=m+p|0,f=k(f^m,12),a=a+f|0,p=k(p^a,8),m=m+p|0,f=k(f^m,7),o=o+l|0,p=k(p^o,16),x=x+p|0,l=k(l^x,12),o=o+l|0,p=k(p^o,8),x=x+p|0,l=k(l^x,7),s=s+u|0,h=k(h^s,16),m=m+h|0,u=k(u^m,12),s=s+u|0,h=k(h^s,8),m=m+h|0,u=k(u^m,7),i=i+f|0,w=k(w^i,16),d=d+w|0,f=k(f^d,12),i=i+f|0,w=k(w^i,8),d=d+w|0,f=k(f^d,7),a=a+c|0,b=k(b^a,16),g=g+b|0,c=k(c^g,12),a=a+c|0,b=k(b^a,8),g=g+b|0,c=k(c^g,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=h,n[I++]=w,n[I++]=b,n[I++]=p}var _m=pa(Bu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Lm=pa(Bu,{counterRight:!1,counterLength:8,extendNonceFn:Tm,allowShortKeys:!1});var Bm=new Uint8Array(16),_u=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Bm.subarray(e))},Pm=new Uint8Array(32);function Lu(r,t,e,n,o){let s=r(t,e,Pm),i=Tu.create(s);o&&_u(i,o),_u(i,n);let a=new Uint8Array(16),c=Eu(a);ha(c,0,BigInt(o?o.length:0),!0),ha(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return ye(s,a),l}var Pu=r=>(t,e,n)=>({encrypt(s,i){let a=s.length;i=fa(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(t,e,c,c,1);let l=Lu(r,t,e,c,n);return i.set(l,a),ye(l),i},decrypt(s,i){i=fa(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Lu(r,t,e,a,n);if(!Au(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(t,e,i,i,1),ye(l),i}}),ga=ua({blockSize:64,nonceLength:12,tagLength:16},Pu(_m)),mA=ua({blockSize:64,nonceLength:24,tagLength:16},Pu(Lm));function Du(r,t,e){return Ur(r),e===void 0&&(e=new Uint8Array(r.outputLen)),pr(r,Se(e),Se(t))}var ya=new Uint8Array([0]),Ru=new Uint8Array;function Nu(r,t,e,n=32){if(Ur(r),_n(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Ru);let s=new Uint8Array(o*r.outputLen),i=pr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)ya[0]=l+1,a.update(l===0?Ru:c).update(e).update(ya).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),ya.fill(0),s.slice(0,n)}var wa={hashSHA256(r){return ee(r.subarray())},getHKDF(r,t){let e=Du(ee,t,r),o=Nu(ee,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=qr.utils.randomPrivateKey();return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return qr.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return ga(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return ga(n,t,e).decrypt(r.subarray(),o)}};var ku=wa;function Uu(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Ir=r=>{let t=gt(2);return t[0]=r>>8,t[1]=r,t};Ir.bytes=2;var fn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};fn.bytes=2;function Ou(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function xa(r,t){!t.enabled||!vr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${H(r.privateKey,"hex")}`)):t("Missing local static keys."))}function ba(r,t){!t.enabled||!vr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${H(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ku(r,t){!t.enabled||!vr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote static public key.")}function Ea(r,t){!t.enabled||!vr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Sa(r,t,e){!e.enabled||!vr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&H(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&H(t.k,"hex")}`))}var Cr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Rm=0,Dm=4294967295,Nm="Cipherstate has reached maximum n, a new handshake must be performed",Ho=class{n;bytes;view;constructor(t=Rm){this.n=t,this.bytes=mt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Dm)throw new Error(Nm)}};var Ye=mt(0),Tr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ho(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Aa=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=X(e,"utf-8");this.h=km(t,n),this.ck=this.h,this.cs=new Tr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Tr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new V(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Ye);return[new Tr(this.crypto,t),new Tr(this.crypto,e)]}},va=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Aa(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},hn=class extends va{writeMessageA(t){return new V(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new V(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new V(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Cr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Cr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Cr(`handshake stage 2 validation fail: ${e.message}`)}}};function km(r,t){if(t.length<=32){let e=mt(32);return e.set(t),e}else return r.hash(t)}var qo;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);if(e.streamMuxers!=null)for(let s of e.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Gr('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(e.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Gr('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(e.string());break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(qo||(qo={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),qo.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={identityKey:mt(0),identitySig:mt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.identityKey=e.bytes();break}case 2:{s.identitySig=e.bytes();break}case 4:{s.extensions=qo.codec().decode(e,e.uint32(),{limits:o.limits?.extensions});break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(dn||(dn={}));async function Ia(r,t,e){let n=await r.sign(Mu(t));return dn.encode({identityKey:Ee(r.publicKey),identitySig:n,extensions:e})}async function Ca(r,t,e){try{let n=dn.decode(r),o=Xr(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Mu(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new gn(n.message)}}function Mu(r){let t=X("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Fu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ia(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});xa(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Ye),t),e.trace("Stage 0 - Initiator finished sending first message."),ba(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),Ea(f.re,e),Ku(f.rs,e),e.trace("Initiator going to check remote's signature...");let g=await Ca(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,m]=f.ss.split();return Sa(x,m,e),{payload:g,encrypt:h=>x.encryptWithAd(Ye,h),decrypt:(h,w)=>m.decryptWithAd(Ye,h,w)}}async function Hu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ia(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});xa(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),Ea(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),ba(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let g=await Ca(d,f.rs,c),[x,m]=f.ss.split();return Sa(x,m,e),{payload:g,encrypt:h=>m.encryptWithAd(Ye,h),decrypt:(h,w)=>x.decryptWithAd(Ye,h,w)}}var Vu=16;function Wu(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new V(Ir(i.byteLength),i)}}}function Gu(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Vu<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Vu);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Vo=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??ku;this.crypto=Uu(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ou(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??mt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[tr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=na(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ei(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null)return;let e=this.components.upgrader.getStreamMuxers();if(e!=null)for(let n of t){let o=e.get(n);if(o!=null)return o}if(t.length)throw new yn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,e){let n=na(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ei(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await Fu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await Hu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=pu(),s=t.unwrap();return await yu(n,Wu(e,this.metrics),s,i=>Ze(i,{lengthDecoder:fn}),Gu(e,this.metrics),n),o}};function zu(r={}){return t=>new Vo(t,r)}var Ta=Object.values(Oe).map(r=>r.decoder).reduce((r,t)=>r.or(t)),Um=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function $u(r){return r?.match(Um)?.groups?.fingerprint}function _a(r){let e=r.stringTuples().filter(n=>n[0]===Ol).map(n=>n[1])[0];if(e===void 0||e==="")throw new Q(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Om(r){return Ft.decode(Ta.decode(r))}function Km(r){let t=Om(_a(r)),e=Mm(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Io(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function ju(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=Ct(ie.code,e);return re(`/certhash/${Dr.encode(n.bytes)}`)}function Mm(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new To(r)}}function Xu(r,t){let{host:e,port:n,family:o}=r.toOptions(),s=Km(r);return{type:"answer",sdp:`v=0
3
- o=- 0 0 IN IP${o} ${e}
2
+ "use strict";var Libp2PWebrtc=(()=>{var iA=Object.create;var bu=Object.defineProperty;var sA=Object.getOwnPropertyDescriptor;var aA=Object.getOwnPropertyNames;var cA=Object.getPrototypeOf,uA=Object.prototype.hasOwnProperty;var Ip=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pt=(r,e)=>{for(var t in e)bu(r,t,{get:e[t],enumerable:!0})},cg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aA(e))!uA.call(r,o)&&o!==t&&bu(r,o,{get:()=>e[o],enumerable:!(n=sA(e,o))||n.enumerable});return r};var jr=(r,e,t)=>(t=r!=null?iA(cA(r)):{},cg(e||!r||!r.__esModule?bu(t,"default",{value:r,enumerable:!0}):t,r)),lA=r=>cg(bu({},"__esModule",{value:!0}),r);var Jw=Ip(()=>{var Zw;(function(r){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:a(),n=o(r);typeof t.Reflect<"u"&&(n=o(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=r);function o(c,l){return function(p,h){Object.defineProperty(c,p,{configurable:!0,writable:!0,value:h}),l&&l(p,h)}}function i(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return i()||s()}})(function(e,t){var n=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,l=!a&&!c,p={create:a?function(){return ia(Object.create(null))}:c?function(){return ia({__proto__:null})}:function(){return ia({})},has:l?function(b,_){return n.call(b,_)}:function(b,_){return _ in b},get:l?function(b,_){return n.call(b,_)?b[_]:void 0}:function(b,_){return b[_]}},h=Object.getPrototypeOf(Function),m=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:xu(),g=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:_p(),x=typeof WeakMap=="function"?WeakMap:Cp(),w=o?Symbol.for("@reflect-metadata:registry"):void 0,y=yu(),S=gu(y);function T(b,_,k,V){if(N(k)){if(!ft(b))throw new TypeError;if(!Gt(_))throw new TypeError;return J(b,_)}else{if(!ft(b))throw new TypeError;if(!ee(_))throw new TypeError;if(!ee(V)&&!N(V)&&!ie(V))throw new TypeError;return ie(V)&&(V=void 0),k=Oe(k),le(b,_,k,V)}}e("decorate",T);function v(b,_){function k(V,se){if(!ee(V))throw new TypeError;if(!N(se)&&!gr(se))throw new TypeError;P(b,_,V,se)}return k}e("metadata",v);function L(b,_,k,V){if(!ee(k))throw new TypeError;return N(V)||(V=Oe(V)),P(b,_,k,V)}e("defineMetadata",L);function F(b,_,k){if(!ee(_))throw new TypeError;return N(k)||(k=Oe(k)),R(b,_,k)}e("hasMetadata",F);function K(b,_,k){if(!ee(_))throw new TypeError;return N(k)||(k=Oe(k)),U(b,_,k)}e("hasOwnMetadata",K);function O(b,_,k){if(!ee(_))throw new TypeError;return N(k)||(k=Oe(k)),I(b,_,k)}e("getMetadata",O);function M(b,_,k){if(!ee(_))throw new TypeError;return N(k)||(k=Oe(k)),E(b,_,k)}e("getOwnMetadata",M);function D(b,_){if(!ee(b))throw new TypeError;return N(_)||(_=Oe(_)),B(b,_)}e("getMetadataKeys",D);function ne(b,_){if(!ee(b))throw new TypeError;return N(_)||(_=Oe(_)),W(b,_)}e("getOwnMetadataKeys",ne);function G(b,_,k){if(!ee(_))throw new TypeError;if(N(k)||(k=Oe(k)),!ee(_))throw new TypeError;N(k)||(k=Oe(k));var V=Un(_,k,!1);return N(V)?!1:V.OrdinaryDeleteMetadata(b,_,k)}e("deleteMetadata",G);function J(b,_){for(var k=b.length-1;k>=0;--k){var V=b[k],se=V(_);if(!N(se)&&!ie(se)){if(!Gt(se))throw new TypeError;_=se}}return _}function le(b,_,k,V){for(var se=b.length-1;se>=0;--se){var Ye=b[se],rt=Ye(_,k,V);if(!N(rt)&&!ie(rt)){if(!ee(rt))throw new TypeError;V=rt}}return V}function R(b,_,k){var V=U(b,_,k);if(V)return!0;var se=Vi(_);return ie(se)?!1:R(b,se,k)}function U(b,_,k){var V=Un(_,k,!1);return N(V)?!1:Be(V.OrdinaryHasOwnMetadata(b,_,k))}function I(b,_,k){var V=U(b,_,k);if(V)return E(b,_,k);var se=Vi(_);if(!ie(se))return I(b,se,k)}function E(b,_,k){var V=Un(_,k,!1);if(!N(V))return V.OrdinaryGetOwnMetadata(b,_,k)}function P(b,_,k,V){var se=Un(k,V,!0);se.OrdinaryDefineOwnMetadata(b,_,k,V)}function B(b,_){var k=W(b,_),V=Vi(b);if(V===null)return k;var se=B(V,_);if(se.length<=0)return k;if(k.length<=0)return se;for(var Ye=new g,rt=[],ge=0,z=k;ge<z.length;ge++){var Y=z[ge],Q=Ye.has(Y);Q||(Ye.add(Y),rt.push(Y))}for(var te=0,we=se;te<we.length;te++){var Y=we[te],Q=Ye.has(Y);Q||(Ye.add(Y),rt.push(Y))}return rt}function W(b,_){var k=Un(b,_,!1);return k?k.OrdinaryOwnMetadataKeys(b,_):[]}function q(b){if(b===null)return 1;switch(typeof b){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return b===null?1:6;default:return 6}}function N(b){return b===void 0}function ie(b){return b===null}function ce(b){return typeof b=="symbol"}function ee(b){return typeof b=="object"?b!==null:typeof b=="function"}function be(b,_){switch(q(b)){case 0:return b;case 1:return b;case 2:return b;case 3:return b;case 4:return b;case 5:return b}var k=_===3?"string":_===5?"number":"default",V=pu(b,i);if(V!==void 0){var se=V.call(b,k);if(ee(se))throw new TypeError;return se}return Ne(b,k==="default"?"number":k)}function Ne(b,_){if(_==="string"){var k=b.toString;if(We(k)){var V=k.call(b);if(!ee(V))return V}var se=b.valueOf;if(We(se)){var V=se.call(b);if(!ee(V))return V}}else{var se=b.valueOf;if(We(se)){var V=se.call(b);if(!ee(V))return V}var Ye=b.toString;if(We(Ye)){var V=Ye.call(b);if(!ee(V))return V}}throw new TypeError}function Be(b){return!!b}function De(b){return""+b}function Oe(b){var _=be(b,3);return ce(_)?_:De(_)}function ft(b){return Array.isArray?Array.isArray(b):b instanceof Object?b instanceof Array:Object.prototype.toString.call(b)==="[object Array]"}function We(b){return typeof b=="function"}function Gt(b){return typeof b=="function"}function gr(b){switch(q(b)){case 3:return!0;case 4:return!0;default:return!1}}function nn(b,_){return b===_||b!==b&&_!==_}function pu(b,_){var k=b[_];if(k!=null){if(!We(k))throw new TypeError;return k}}function hu(b){var _=pu(b,s);if(!We(_))throw new TypeError;var k=_.call(b);if(!ee(k))throw new TypeError;return k}function du(b){return b.value}function mu(b){var _=b.next();return _.done?!1:_}function na(b){var _=b.return;_&&_.call(b)}function Vi(b){var _=Object.getPrototypeOf(b);if(typeof b!="function"||b===h||_!==h)return _;var k=b.prototype,V=k&&Object.getPrototypeOf(k);if(V==null||V===Object.prototype)return _;var se=V.constructor;return typeof se!="function"||se===b?_:se}function oa(){var b;!N(w)&&typeof t.Reflect<"u"&&!(w in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(b=wu(t.Reflect));var _,k,V,se=new x,Ye={registerProvider:rt,getProvider:z,setProvider:Q};return Ye;function rt(te){if(!Object.isExtensible(Ye))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case b===te:break;case N(_):_=te;break;case _===te:break;case N(k):k=te;break;case k===te:break;default:V===void 0&&(V=new g),V.add(te);break}}function ge(te,we){if(!N(_)){if(_.isProviderFor(te,we))return _;if(!N(k)){if(k.isProviderFor(te,we))return _;if(!N(V))for(var Me=hu(V);;){var Ze=mu(Me);if(!Ze)return;var wr=du(Ze);if(wr.isProviderFor(te,we))return na(Me),wr}}}if(!N(b)&&b.isProviderFor(te,we))return b}function z(te,we){var Me=se.get(te),Ze;return N(Me)||(Ze=Me.get(we)),N(Ze)&&(Ze=ge(te,we),N(Ze)||(N(Me)&&(Me=new m,se.set(te,Me)),Me.set(we,Ze))),Ze}function Y(te){if(N(te))throw new TypeError;return _===te||k===te||!N(V)&&V.has(te)}function Q(te,we,Me){if(!Y(Me))throw new Error("Metadata provider not registered.");var Ze=z(te,we);if(Ze!==Me){if(!N(Ze))return!1;var wr=se.get(te);N(wr)&&(wr=new m,se.set(te,wr)),wr.set(we,Me)}return!0}}function yu(){var b;return!N(w)&&ee(t.Reflect)&&Object.isExtensible(t.Reflect)&&(b=t.Reflect[w]),N(b)&&(b=oa()),!N(w)&&ee(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:b}),b}function gu(b){var _=new x,k={isProviderFor:function(Y,Q){var te=_.get(Y);return N(te)?!1:te.has(Q)},OrdinaryDefineOwnMetadata:rt,OrdinaryHasOwnMetadata:se,OrdinaryGetOwnMetadata:Ye,OrdinaryOwnMetadataKeys:ge,OrdinaryDeleteMetadata:z};return y.registerProvider(k),k;function V(Y,Q,te){var we=_.get(Y),Me=!1;if(N(we)){if(!te)return;we=new m,_.set(Y,we),Me=!0}var Ze=we.get(Q);if(N(Ze)){if(!te)return;if(Ze=new m,we.set(Q,Ze),!b.setProvider(Y,Q,k))throw we.delete(Q),Me&&_.delete(Y),new Error("Wrong provider for target.")}return Ze}function se(Y,Q,te){var we=V(Q,te,!1);return N(we)?!1:Be(we.has(Y))}function Ye(Y,Q,te){var we=V(Q,te,!1);if(!N(we))return we.get(Y)}function rt(Y,Q,te,we){var Me=V(te,we,!0);Me.set(Y,Q)}function ge(Y,Q){var te=[],we=V(Y,Q,!1);if(N(we))return te;for(var Me=we.keys(),Ze=hu(Me),wr=0;;){var ag=mu(Ze);if(!ag)return te.length=wr,te;var nA=du(ag);try{te[wr]=nA}catch(oA){try{na(Ze)}finally{throw oA}}wr++}}function z(Y,Q,te){var we=V(Q,te,!1);if(N(we)||!we.delete(Y))return!1;if(we.size===0){var Me=_.get(Q);N(Me)||(Me.delete(te),Me.size===0&&_.delete(Me))}return!0}}function wu(b){var _=b.defineMetadata,k=b.hasOwnMetadata,V=b.getOwnMetadata,se=b.getOwnMetadataKeys,Ye=b.deleteMetadata,rt=new x,ge={isProviderFor:function(z,Y){var Q=rt.get(z);return!N(Q)&&Q.has(Y)?!0:se(z,Y).length?(N(Q)&&(Q=new g,rt.set(z,Q)),Q.add(Y),!0):!1},OrdinaryDefineOwnMetadata:_,OrdinaryHasOwnMetadata:k,OrdinaryGetOwnMetadata:V,OrdinaryOwnMetadataKeys:se,OrdinaryDeleteMetadata:Ye};return ge}function Un(b,_,k){var V=y.getProvider(b,_);if(!N(V))return V;if(k){if(y.setProvider(b,_,S))return S;throw new Error("Illegal state.")}}function xu(){var b={},_=[],k=function(){function ge(z,Y,Q){this._index=0,this._keys=z,this._values=Y,this._selector=Q}return ge.prototype["@@iterator"]=function(){return this},ge.prototype[s]=function(){return this},ge.prototype.next=function(){var z=this._index;if(z>=0&&z<this._keys.length){var Y=this._selector(this._keys[z],this._values[z]);return z+1>=this._keys.length?(this._index=-1,this._keys=_,this._values=_):this._index++,{value:Y,done:!1}}return{value:void 0,done:!0}},ge.prototype.throw=function(z){throw this._index>=0&&(this._index=-1,this._keys=_,this._values=_),z},ge.prototype.return=function(z){return this._index>=0&&(this._index=-1,this._keys=_,this._values=_),{value:z,done:!0}},ge}(),V=function(){function ge(){this._keys=[],this._values=[],this._cacheKey=b,this._cacheIndex=-2}return Object.defineProperty(ge.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ge.prototype.has=function(z){return this._find(z,!1)>=0},ge.prototype.get=function(z){var Y=this._find(z,!1);return Y>=0?this._values[Y]:void 0},ge.prototype.set=function(z,Y){var Q=this._find(z,!0);return this._values[Q]=Y,this},ge.prototype.delete=function(z){var Y=this._find(z,!1);if(Y>=0){for(var Q=this._keys.length,te=Y+1;te<Q;te++)this._keys[te-1]=this._keys[te],this._values[te-1]=this._values[te];return this._keys.length--,this._values.length--,nn(z,this._cacheKey)&&(this._cacheKey=b,this._cacheIndex=-2),!0}return!1},ge.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=b,this._cacheIndex=-2},ge.prototype.keys=function(){return new k(this._keys,this._values,se)},ge.prototype.values=function(){return new k(this._keys,this._values,Ye)},ge.prototype.entries=function(){return new k(this._keys,this._values,rt)},ge.prototype["@@iterator"]=function(){return this.entries()},ge.prototype[s]=function(){return this.entries()},ge.prototype._find=function(z,Y){if(!nn(this._cacheKey,z)){this._cacheIndex=-1;for(var Q=0;Q<this._keys.length;Q++)if(nn(this._keys[Q],z)){this._cacheIndex=Q;break}}return this._cacheIndex<0&&Y&&(this._cacheIndex=this._keys.length,this._keys.push(z),this._values.push(void 0)),this._cacheIndex},ge}();return V;function se(ge,z){return ge}function Ye(ge,z){return z}function rt(ge,z){return[ge,z]}}function _p(){var b=function(){function _(){this._map=new m}return Object.defineProperty(_.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),_.prototype.has=function(k){return this._map.has(k)},_.prototype.add=function(k){return this._map.set(k,k),this},_.prototype.delete=function(k){return this._map.delete(k)},_.prototype.clear=function(){this._map.clear()},_.prototype.keys=function(){return this._map.keys()},_.prototype.values=function(){return this._map.keys()},_.prototype.entries=function(){return this._map.entries()},_.prototype["@@iterator"]=function(){return this.keys()},_.prototype[s]=function(){return this.keys()},_}();return b}function Cp(){var b=16,_=p.create(),k=V();return function(){function z(){this._key=V()}return z.prototype.has=function(Y){var Q=se(Y,!1);return Q!==void 0?p.has(Q,this._key):!1},z.prototype.get=function(Y){var Q=se(Y,!1);return Q!==void 0?p.get(Q,this._key):void 0},z.prototype.set=function(Y,Q){var te=se(Y,!0);return te[this._key]=Q,this},z.prototype.delete=function(Y){var Q=se(Y,!1);return Q!==void 0?delete Q[this._key]:!1},z.prototype.clear=function(){this._key=V()},z}();function V(){var z;do z="@@WeakMap@@"+ge();while(p.has(_,z));return _[z]=!0,z}function se(z,Y){if(!n.call(z,k)){if(!Y)return;Object.defineProperty(z,k,{value:p.create()})}return z[k]}function Ye(z,Y){for(var Q=0;Q<Y;++Q)z[Q]=Math.random()*255|0;return z}function rt(z){if(typeof Uint8Array=="function"){var Y=new Uint8Array(z);return typeof crypto<"u"?crypto.getRandomValues(Y):typeof msCrypto<"u"?msCrypto.getRandomValues(Y):Ye(Y,z),Y}return Ye(new Array(z),z)}function ge(){var z=rt(b);z[6]=z[6]&79|64,z[8]=z[8]&191|128;for(var Y="",Q=0;Q<b;++Q){var te=z[Q];(Q===4||Q===6||Q===8)&&(Y+="-"),te<16&&(Y+="0"),Y+=te.toString(16).toLowerCase()}return Y}}function ia(b){return b.__=void 0,delete b.__,b}})})(Zw||(Zw={}))});var gn=Ip(hs=>{"use strict";var u_="[object ArrayBuffer]",yn=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===u_}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Ud="string",l_=/^[0-9a-f\s]+$/i,f_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,p_=/^[a-zA-Z0-9-_]+$/,Vl=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=yn.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},sr=class{static toString(e,t=!1){let n=yn.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},$l=class r{static isHex(e){return typeof e===Ud&&l_.test(e)}static isBase64(e){return typeof e===Ud&&f_.test(e)}static isBase64Url(e){return typeof e===Ud&&p_.test(e)}static ToString(e,t="utf8"){let n=yn.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return sr.toString(n,!0);case"utf16":case"utf16be":return sr.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return sr.fromString(e,!0);case"utf16":case"utf16be":return sr.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=yn.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Vl.fromString(e);case"utf16":case"utf16be":return sr.fromString(e);case"utf16le":case"usc2":return sr.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Vl.toString(e);case"utf16":case"utf16be":return sr.toString(e);case"utf16le":case"usc2":return sr.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=yn.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=yn.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return sr.toString(e,t)}static FromUtf16String(e,t=!1){return sr.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};$l.DEFAULT_UTF8_ENCODING="utf8";function h_(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function d_(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function m_(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}hs.BufferSourceConverter=yn;hs.Convert=$l;hs.assign=h_;hs.combine=d_;hs.isEqual=m_});var qb=Ip((pV,jf)=>{var Cb,Ib,Tb,Bb,kb,Pb,Nb,Ob,Rb,Uf,Fm,Lb,Db,$s,Ub,jb,Mb,Kb,Hb,Vb,$b,Fb,Wb;(function(r){var e=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(n){r(t(e,t(n)))}):typeof jf=="object"&&typeof jf.exports=="object"?r(t(e,t(jf.exports))):r(t(e));function t(n,o){return n!==e&&(typeof Object.create=="function"?Object.defineProperty(n,"__esModule",{value:!0}):n.__esModule=!0),function(i,s){return n[i]=o?o(i,s):s}}})(function(r){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)n.hasOwnProperty(o)&&(t[o]=n[o])};Cb=function(t,n){e(t,n);function o(){this.constructor=t}t.prototype=n===null?Object.create(n):(o.prototype=n.prototype,new o)},Ib=Object.assign||function(t){for(var n,o=1,i=arguments.length;o<i;o++){n=arguments[o];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Tb=function(t,n){var o={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&n.indexOf(i)<0&&(o[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)n.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(o[i[s]]=t[i[s]]);return o},Bb=function(t,n,o,i){var s=arguments.length,a=s<3?n:i===null?i=Object.getOwnPropertyDescriptor(n,o):i,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(t,n,o,i);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(a=(s<3?c(a):s>3?c(n,o,a):c(n,o))||a);return s>3&&a&&Object.defineProperty(n,o,a),a},kb=function(t,n){return function(o,i){n(o,i,t)}},Pb=function(t,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,n)},Nb=function(t,n,o,i){function s(a){return a instanceof o?a:new o(function(c){c(a)})}return new(o||(o=Promise))(function(a,c){function l(m){try{h(i.next(m))}catch(g){c(g)}}function p(m){try{h(i.throw(m))}catch(g){c(g)}}function h(m){m.done?a(m.value):s(m.value).then(l,p)}h((i=i.apply(t,n||[])).next())})},Ob=function(t,n){var o={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,s,a,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(h){return function(m){return p([h,m])}}function p(h){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,s&&(a=h[0]&2?s.return:h[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,h[1])).done)return a;switch(s=0,a&&(h=[h[0]&2,a.value]),h[0]){case 0:case 1:a=h;break;case 4:return o.label++,{value:h[1],done:!1};case 5:o.label++,s=h[1],h=[0];continue;case 7:h=o.ops.pop(),o.trys.pop();continue;default:if(a=o.trys,!(a=a.length>0&&a[a.length-1])&&(h[0]===6||h[0]===2)){o=0;continue}if(h[0]===3&&(!a||h[1]>a[0]&&h[1]<a[3])){o.label=h[1];break}if(h[0]===6&&o.label<a[1]){o.label=a[1],a=h;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(h);break}a[2]&&o.ops.pop(),o.trys.pop();continue}h=n.call(t,o)}catch(m){h=[6,m],s=0}finally{i=a=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},Wb=function(t,n,o,i){i===void 0&&(i=o),t[i]=n[o]},Rb=function(t,n){for(var o in t)o!=="default"&&!n.hasOwnProperty(o)&&(n[o]=t[o])},Uf=function(t){var n=typeof Symbol=="function"&&Symbol.iterator,o=n&&t[n],i=0;if(o)return o.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},Fm=function(t,n){var o=typeof Symbol=="function"&&t[Symbol.iterator];if(!o)return t;var i=o.call(t),s,a=[],c;try{for(;(n===void 0||n-- >0)&&!(s=i.next()).done;)a.push(s.value)}catch(l){c={error:l}}finally{try{s&&!s.done&&(o=i.return)&&o.call(i)}finally{if(c)throw c.error}}return a},Lb=function(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(Fm(arguments[n]));return t},Db=function(){for(var t=0,n=0,o=arguments.length;n<o;n++)t+=arguments[n].length;for(var i=Array(t),s=0,n=0;n<o;n++)for(var a=arguments[n],c=0,l=a.length;c<l;c++,s++)i[s]=a[c];return i},$s=function(t){return this instanceof $s?(this.v=t,this):new $s(t)},Ub=function(t,n,o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=o.apply(t,n||[]),s,a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(x){i[x]&&(s[x]=function(w){return new Promise(function(y,S){a.push([x,w,y,S])>1||l(x,w)})})}function l(x,w){try{p(i[x](w))}catch(y){g(a[0][3],y)}}function p(x){x.value instanceof $s?Promise.resolve(x.value.v).then(h,m):g(a[0][2],x)}function h(x){l("next",x)}function m(x){l("throw",x)}function g(x,w){x(w),a.shift(),a.length&&l(a[0][0],a[0][1])}},jb=function(t){var n,o;return n={},i("next"),i("throw",function(s){throw s}),i("return"),n[Symbol.iterator]=function(){return this},n;function i(s,a){n[s]=t[s]?function(c){return(o=!o)?{value:$s(t[s](c)),done:s==="return"}:a?a(c):c}:a}},Mb=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t[Symbol.asyncIterator],o;return n?n.call(t):(t=typeof Uf=="function"?Uf(t):t[Symbol.iterator](),o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o);function i(a){o[a]=t[a]&&function(c){return new Promise(function(l,p){c=t[a](c),s(l,p,c.done,c.value)})}}function s(a,c,l,p){Promise.resolve(p).then(function(h){a({value:h,done:l})},c)}},Kb=function(t,n){return Object.defineProperty?Object.defineProperty(t,"raw",{value:n}):t.raw=n,t},Hb=function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var o in t)Object.hasOwnProperty.call(t,o)&&(n[o]=t[o]);return n.default=t,n},Vb=function(t){return t&&t.__esModule?t:{default:t}},$b=function(t,n){if(!n.has(t))throw new TypeError("attempted to get private field on non-instance");return n.get(t)},Fb=function(t,n,o){if(!n.has(t))throw new TypeError("attempted to set private field on non-instance");return n.set(t,o),o},r("__extends",Cb),r("__assign",Ib),r("__rest",Tb),r("__decorate",Bb),r("__param",kb),r("__metadata",Pb),r("__awaiter",Nb),r("__generator",Ob),r("__exportStar",Rb),r("__createBinding",Wb),r("__values",Uf),r("__read",Fm),r("__spread",Lb),r("__spreadArrays",Db),r("__await",$s),r("__asyncGenerator",Ub),r("__asyncDelegator",jb),r("__asyncValues",Mb),r("__makeTemplateObject",Kb),r("__importStar",Hb),r("__importDefault",Vb),r("__classPrivateFieldGet",$b),r("__classPrivateFieldSet",Fb)})});var gI={};pt(gI,{webRTC:()=>yI,webRTCDirect:()=>mI});var Tp=Symbol.for("@libp2p/peer-id");var vu=Symbol.for("@libp2p/transport");var ug;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(ug||(ug={}));var Au=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Su=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},ve=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},$i=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},sa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Eu=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}};var _u=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Io=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},To=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var Cu=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Iu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Tu=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Bu=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ku=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var jn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Mn=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Fi=Symbol.for("@libp2p/service-capabilities"),lg=Symbol.for("@libp2p/service-dependencies");var Op={};pt(Op,{base58btc:()=>ke,base58flickr:()=>yA});var WI=new Uint8Array(0);function fg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function on(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function pg(r){return new TextEncoder().encode(r)}function hg(r){return new TextDecoder().decode(r)}function fA(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function h(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var w=0,y=0,S=0,T=x.length;S!==T&&x[S]===0;)S++,w++;for(var v=(T-S)*p+1>>>0,L=new Uint8Array(v);S!==T;){for(var F=x[S],K=0,O=v-1;(F!==0||K<y)&&O!==-1;O--,K++)F+=256*L[O]>>>0,L[O]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");y=K,S++}for(var M=v-y;M!==v&&L[M]===0;)M++;for(var D=c.repeat(w);M<v;++M)D+=r.charAt(L[M]);return D}function m(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var w=0;if(x[w]!==" "){for(var y=0,S=0;x[w]===c;)y++,w++;for(var T=(x.length-w)*l+1>>>0,v=new Uint8Array(T);x[w];){var L=t[x.charCodeAt(w)];if(L===255)return;for(var F=0,K=T-1;(L!==0||F<S)&&K!==-1;K--,F++)L+=a*v[K]>>>0,v[K]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");S=F,w++}if(x[w]!==" "){for(var O=T-S;O!==T&&v[O]===0;)O++;for(var M=new Uint8Array(y+(T-O)),D=y;O!==T;)M[D++]=v[O++];return M}}}function g(x){var w=m(x);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:g}}var pA=fA,hA=pA,mg=hA;var Bp=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},kp=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 yg(this,e)}},Pp=class{decoders;constructor(e){this.decoders=e}or(e){return yg(this,e)}decode(e){let t=e[0],n=this.decoders[t];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 yg(r,e){return new Pp({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Np=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Bp(e,t,n),this.decoder=new kp(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Wi({name:r,prefix:e,encode:t,decode:n}){return new Np(r,e,t,n)}function Kn({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=mg(t,r);return Wi({prefix:e,name:r,encode:n,decode:i=>on(o(i))})}function dA(r,e,t,n){let o={};for(let p=0;p<e.length;++p)o[e[p]]=p;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let p=0;p<i;++p){let h=o[r[p]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|h,a+=t,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=t||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function mA(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function qe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Wi({prefix:e,name:r,encode(o){return mA(o,n,t)},decode(o){return dA(o,n,t,r)}})}var ke=Kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yA=Kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Rp={};pt(Rp,{base32:()=>sn,base32hex:()=>bA,base32hexpad:()=>AA,base32hexpadupper:()=>SA,base32hexupper:()=>vA,base32pad:()=>wA,base32padupper:()=>xA,base32upper:()=>gA,base32z:()=>EA});var sn=qe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),gA=qe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wA=qe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xA=qe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),bA=qe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vA=qe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),AA=qe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SA=qe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),EA=qe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Lp={};pt(Lp,{base36:()=>aa,base36upper:()=>_A});var aa=Kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_A=Kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var er={};pt(er,{Digest:()=>Bo,create:()=>St,decode:()=>Hn,equals:()=>Up,hasCode:()=>FA});var CA=xg,gg=128,IA=127,TA=~IA,BA=Math.pow(2,31);function xg(r,e,t){e=e||[],t=t||0;for(var n=t;r>=BA;)e[t++]=r&255|gg,r/=128;for(;r&TA;)e[t++]=r&255|gg,r>>>=7;return e[t]=r|0,xg.bytes=t-n+1,e}var kA=Dp,PA=128,wg=127;function Dp(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Dp.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&wg)<<o:(s&wg)*Math.pow(2,o),o+=7}while(s>=PA);return Dp.bytes=i-n,t}var NA=Math.pow(2,7),OA=Math.pow(2,14),RA=Math.pow(2,21),LA=Math.pow(2,28),DA=Math.pow(2,35),UA=Math.pow(2,42),jA=Math.pow(2,49),MA=Math.pow(2,56),KA=Math.pow(2,63),HA=function(r){return r<NA?1:r<OA?2:r<RA?3:r<LA?4:r<DA?5:r<UA?6:r<jA?7:r<MA?8:r<KA?9:10},VA={encode:CA,decode:kA,encodingLength:HA},$A=VA,ca=$A;function ua(r,e=0){return[ca.decode(r,e),ca.decode.bytes]}function qi(r,e,t=0){return ca.encode(r,e,t),e}function Gi(r){return ca.encodingLength(r)}function St(r,e){let t=e.byteLength,n=Gi(r),o=n+Gi(t),i=new Uint8Array(o+t);return qi(r,i,0),qi(t,i,n),i.set(e,o),new Bo(r,t,e,i)}function Hn(r){let e=on(r),[t,n]=ua(e),[o,i]=ua(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Bo(t,o,s,e)}function Up(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&fg(r.bytes,t.bytes)}}var Bo=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function FA(r,e){return r.code===e}function bg(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return qA(t,jp(r),e??ke.encoder);default:return GA(t,jp(r),e??sn.encoder)}}var vg=new WeakMap;function jp(r){let e=vg.get(r);if(e==null){let t=new Map;return vg.set(r,t),t}return e}var Je=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}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:t}=this;if(e!==la)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==zA)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=St(e,t);return r.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 r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Up(e.multihash,n.multihash)}toString(e){return bg(this,e)}toJSON(){return{"/":bg(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 t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??Ag(n,o,i.bytes))}else if(t[XA]===!0){let{version:n,multihash:o,code:i}=t,s=Hn(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="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(t!==la)throw new Error(`Version 0 CID must use dag-pb (code: ${la}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Ag(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,la,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=on(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Bo(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,m]=ua(e.subarray(t));return t+=m,h},o=n(),i=la;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,p=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:p,size:l}}static parse(e,t){let[n,o]=WA(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return jp(i).set(n,e),i}};function WA(r,e){switch(r[0]){case"Q":{let t=e??ke;return[ke.prefix,t.decode(`${ke.prefix}${r}`)]}case ke.prefix:{let t=e??ke;return[ke.prefix,t.decode(r)]}case sn.prefix:{let t=e??sn;return[sn.prefix,t.decode(r)]}case aa.prefix:{let t=e??aa;return[aa.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function qA(r,e,t){let{prefix:n}=t;if(n!==ke.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function GA(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var la=112,zA=18;function Ag(r,e,t){let n=Gi(r),o=n+Gi(e),i=new Uint8Array(o+t.byteLength);return qi(r,i,0),qi(e,i,n),i.set(t,o),i}var XA=Symbol.for("@ipld/js-cid/CID");var Mp={};pt(Mp,{identity:()=>xr});var Sg=0,YA="identity",Eg=on;function ZA(r){return St(Sg,Eg(r))}var xr={code:Sg,name:YA,encode:Eg,digest:ZA};function Ge(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function nt(r=0){return new Uint8Array(r)}function ot(r=0){return new Uint8Array(r)}function it(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=ot(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Cg=Symbol.for("@achingbrain/uint8arraylist");function _g(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Nu(r){return!!r?.[Cg]}var pe=class r{bufs;length;[Cg]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Nu(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nu(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=_g(this.bufs,e);return t.buf[t.index]}set(e,t){let n=_g(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Nu(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return it(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:it(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,p=t>a&&t<=c;if(l&&p){if(e===a&&t===c){n.push(s);break}let h=e-a;n.push(s.subarray(h,h+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(p){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nu(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let h=0;h<i;h++)s[h]=-1;for(let h=0;h<o;h++)s[n[h]]=h;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,p;for(let h=t;h<=c;h+=p){p=0;for(let m=l;m>=0;m--){let g=this.get(h+m);if(n[m]!==g){p=Math.max(1,m-a[g]);break}}if(p===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ge(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};var Kp={};pt(Kp,{base10:()=>QA});var QA=Kn({prefix:"9",name:"base10",alphabet:"0123456789"});var Hp={};pt(Hp,{base16:()=>eS,base16upper:()=>tS});var eS=qe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tS=qe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vp={};pt(Vp,{base2:()=>rS});var rS=qe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $p={};pt($p,{base256emoji:()=>aS});var Ig=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),nS=Ig.reduce((r,e,t)=>(r[t]=e,r),[]),oS=Ig.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function iS(r){return r.reduce((e,t)=>(e+=nS[t],e),"")}function sS(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=oS[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var aS=Wi({prefix:"\u{1F680}",name:"base256emoji",encode:iS,decode:sS});var Fp={};pt(Fp,{base64:()=>cS,base64pad:()=>uS,base64url:()=>ko,base64urlpad:()=>lS});var cS=qe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),uS=qe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ko=qe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lS=qe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wp={};pt(Wp,{base8:()=>fS});var fS=qe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qp={};pt(qp,{identity:()=>pS});var pS=Wi({prefix:"\0",name:"identity",encode:r=>hg(r),decode:r=>pg(r)});var IT=new TextEncoder,TT=new TextDecoder;var Xp={};pt(Xp,{sha256:()=>tr,sha512:()=>mS});function zp({name:r,code:e,encode:t}){return new Gp(r,e,t)}var Gp=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?St(this.code,t):t.then(n=>St(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Bg(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var tr=zp({name:"sha2-256",code:18,encode:Bg("SHA-256")}),mS=zp({name:"sha2-512",code:19,encode:Bg("SHA-512")});var Po={...qp,...Vp,...Wp,...Kp,...Hp,...Rp,...Lp,...Op,...Fp,...$p},KT={...Xp,...Mp};function Pg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var kg=Pg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Yp=Pg("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ot(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),yS={utf8:kg,"utf-8":kg,hex:Po.base16,latin1:Yp,ascii:Yp,binary:Yp,...Po},Ou=yS;function de(r,e="utf8"){let t=Ou[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ue(r,e="utf8"){let t=Ou[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var gS=parseInt("11111",2),Zp=parseInt("10000000",2),wS=parseInt("01111111",2),Ng={0:fa,1:fa,2:xS,3:AS,4:SS,5:vS,6:bS,16:fa,22:fa,48:fa};function an(r,e={offset:0}){let t=r[e.offset]&gS;if(e.offset++,Ng[t]!=null)return Ng[t](r,e);throw new Error("No decoder for tag "+t)}function pa(r,e){let t=0;if((r[e.offset]&Zp)===Zp){let n=r[e.offset]&wS,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function fa(r,e){pa(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=an(r,e);if(n===null)break;t.push(n)}return t}function xS(r,e){let t=pa(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function bS(r,e){let t=pa(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let p=0;for(let h=0;h<c.length;h++)p+=c[h]<<h*7;a+=`.${p}`,c=[]}}return a}function vS(r,e){return e.offset++,null}function AS(r,e){let t=pa(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function SS(r,e){let t=pa(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function ES(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new pe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ru(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=ES(r.byteLength);return new pe(Uint8Array.from([e.byteLength|Zp]),e)}function Bt(r){let e=new pe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new pe(Uint8Array.from([2]),Ru(e),e)}function ha(r){let e=Uint8Array.from([0]),t=new pe(e,r);return new pe(Uint8Array.from([3]),Ru(t),t)}function Og(r){return new pe(Uint8Array.from([4]),Ru(r),r)}function br(r,e=48){let t=new pe;for(let n of r)t.append(n);return new pe(Uint8Array.from([e]),Ru(t),t)}async function Rg(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Lg(r,e){let t=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]),n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Dg(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,e,t.subarray())}var _S=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),CS=Uint8Array.from([6,5,43,129,4,0,34]),IS=Uint8Array.from([6,5,43,129,4,0,35]),TS={ext:!0,kty:"EC",crv:"P-256"},BS={ext:!0,kty:"EC",crv:"P-384"},kS={ext:!0,kty:"EC",crv:"P-521"},Jp=32,Qp=48,eh=66;function th(r){let e=an(r);return Ug(e)}function Ug(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Jp*2+1)return n=ue(e.subarray(t,t+Jp),"base64url"),o=ue(e.subarray(t+Jp),"base64url"),new No({...TS,key_ops:["verify"],x:n,y:o});if(e.byteLength===Qp*2+1)return n=ue(e.subarray(t,t+Qp),"base64url"),o=ue(e.subarray(t+Qp),"base64url"),new No({...BS,key_ops:["verify"],x:n,y:o});if(e.byteLength===eh*2+1)return n=ue(e.subarray(t,t+eh),"base64url"),o=ue(e.subarray(t+eh),"base64url"),new No({...kS,key_ops:["verify"],x:n,y:o});throw new ve(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function jg(r){return br([Bt(Uint8Array.from([1])),Og(de(r.d??"","base64url")),br([Kg(r.crv)],160),br([ha(new pe(Uint8Array.from([4]),de(r.x??"","base64url"),de(r.y??"","base64url")))],161)]).subarray()}function Mg(r){return br([Bt(Uint8Array.from([1])),br([Kg(r.crv)],160),br([ha(new pe(Uint8Array.from([4]),de(r.x??"","base64url"),de(r.y??"","base64url")))],161)]).subarray()}function Kg(r){if(r==="P-256")return _S;if(r==="P-384")return CS;if(r==="P-521")return IS;throw new ve(`Invalid curve ${r}`)}async function Hg(r="P-256"){let e=await Rg(r);return new Lu(e.privateKey)}var No=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Mg(this.jwk)),this._raw}toMultihash(){return xr.digest(Vn(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ke.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}async verify(e,t){return Dg(this.jwk,t,e)}},Lu=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new No({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=jg(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}async sign(e){return Lg(this.jwk,e)}};function Du(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function PS(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function zi(r,...e){if(!PS(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function da(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Du(r.outputLen),Du(r.blockLen)}function Xi(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Vg(r,e){zi(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var Oo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Uu(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vr(r,e){return r<<32-e|r>>>e}function $g(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function $n(r){return typeof r=="string"&&(r=$g(r)),zi(r),r}function rh(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];zi(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}var Yi=class{clone(){return this._cloneInto()}};function ju(r){let e=n=>r().update($n(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ma(r=32){if(Oo&&typeof Oo.getRandomValues=="function")return Oo.getRandomValues(new Uint8Array(r));if(Oo&&typeof Oo.randomBytes=="function")return Oo.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function NS(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(t>>o&i),a=Number(t&i),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}function Fg(r,e,t){return r&e^~r&t}function Wg(r,e,t){return r&e^r&t^e&t}var Zi=class extends Yi{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Uu(this.buffer)}update(e){Xi(this);let{view:t,buffer:n,blockLen:o}=this;e=$n(e);let i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Uu(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xi(this),Vg(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let h=s;h<o;h++)t[h]=0;NS(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Uu(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,p=this.get();if(l>p.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,p[h],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=s,o%t&&e.buffer.set(n),e}};var Mu=BigInt(4294967295),nh=BigInt(32);function qg(r,e=!1){return e?{h:Number(r&Mu),l:Number(r>>nh&Mu)}:{h:Number(r>>nh&Mu)|0,l:Number(r&Mu)|0}}function OS(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=qg(r[o],e);[t[o],n[o]]=[i,s]}return[t,n]}var RS=(r,e)=>BigInt(r>>>0)<<nh|BigInt(e>>>0),LS=(r,e,t)=>r>>>t,DS=(r,e,t)=>r<<32-t|e>>>t,US=(r,e,t)=>r>>>t|e<<32-t,jS=(r,e,t)=>r<<32-t|e>>>t,MS=(r,e,t)=>r<<64-t|e>>>t-32,KS=(r,e,t)=>r>>>t-32|e<<64-t,HS=(r,e)=>e,VS=(r,e)=>r,$S=(r,e,t)=>r<<t|e>>>32-t,FS=(r,e,t)=>e<<t|r>>>32-t,WS=(r,e,t)=>e<<t-32|r>>>64-t,qS=(r,e,t)=>r<<t-32|e>>>64-t;function GS(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var zS=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),XS=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,YS=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),ZS=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,JS=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),QS=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var eE={fromBig:qg,split:OS,toBig:RS,shrSH:LS,shrSL:DS,rotrSH:US,rotrSL:jS,rotrBH:MS,rotrBL:KS,rotr32H:HS,rotr32L:VS,rotlSH:$S,rotlSL:FS,rotlBH:WS,rotlBL:qS,add:GS,add3L:zS,add3H:XS,add4L:YS,add4H:ZS,add5H:QS,add5L:JS},he=eE;var[tE,rE]=he.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(r=>BigInt(r))),Fn=new Uint32Array(80),Wn=new Uint32Array(80),oh=class extends Zi{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:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:p,Fh:h,Fl:m,Gh:g,Gl:x,Hh:w,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,p,h,m,g,x,w,y]}set(e,t,n,o,i,s,a,c,l,p,h,m,g,x,w,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=p|0,this.Fh=h|0,this.Fl=m|0,this.Gh=g|0,this.Gl=x|0,this.Hh=w|0,this.Hl=y|0}process(e,t){for(let v=0;v<16;v++,t+=4)Fn[v]=e.getUint32(t),Wn[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let L=Fn[v-15]|0,F=Wn[v-15]|0,K=he.rotrSH(L,F,1)^he.rotrSH(L,F,8)^he.shrSH(L,F,7),O=he.rotrSL(L,F,1)^he.rotrSL(L,F,8)^he.shrSL(L,F,7),M=Fn[v-2]|0,D=Wn[v-2]|0,ne=he.rotrSH(M,D,19)^he.rotrBH(M,D,61)^he.shrSH(M,D,6),G=he.rotrSL(M,D,19)^he.rotrBL(M,D,61)^he.shrSL(M,D,6),J=he.add4L(O,G,Wn[v-7],Wn[v-16]),le=he.add4H(J,K,ne,Fn[v-7],Fn[v-16]);Fn[v]=le|0,Wn[v]=J|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:p,Eh:h,El:m,Fh:g,Fl:x,Gh:w,Gl:y,Hh:S,Hl:T}=this;for(let v=0;v<80;v++){let L=he.rotrSH(h,m,14)^he.rotrSH(h,m,18)^he.rotrBH(h,m,41),F=he.rotrSL(h,m,14)^he.rotrSL(h,m,18)^he.rotrBL(h,m,41),K=h&g^~h&w,O=m&x^~m&y,M=he.add5L(T,F,O,rE[v],Wn[v]),D=he.add5H(M,S,L,K,tE[v],Fn[v]),ne=M|0,G=he.rotrSH(n,o,28)^he.rotrBH(n,o,34)^he.rotrBH(n,o,39),J=he.rotrSL(n,o,28)^he.rotrBL(n,o,34)^he.rotrBL(n,o,39),le=n&i^n&a^i&a,R=o&s^o&c^s&c;S=w|0,T=y|0,w=g|0,y=x|0,g=h|0,x=m|0,{h,l:m}=he.add(l|0,p|0,D|0,ne|0),l=a|0,p=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let U=he.add3L(ne,J,R);n=he.add3H(U,D,G,le),o=U|0}({h:n,l:o}=he.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=he.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=he.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=he.add(this.Dh|0,this.Dl|0,l|0,p|0),{h,l:m}=he.add(this.Eh|0,this.El|0,h|0,m|0),{h:g,l:x}=he.add(this.Fh|0,this.Fl|0,g|0,x|0),{h:w,l:y}=he.add(this.Gh|0,this.Gl|0,w|0,y|0),{h:S,l:T}=he.add(this.Hh|0,this.Hl|0,S|0,T|0),this.set(n,o,i,s,a,c,l,p,h,m,g,x,w,y,S,T)}roundClean(){Fn.fill(0),Wn.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 Gg=ju(()=>new oh);var Vu={};pt(Vu,{aInRange:()=>ht,abool:()=>Ar,abytes:()=>Ji,bitGet:()=>cE,bitLen:()=>ch,bitMask:()=>ga,bitSet:()=>uE,bytesToHex:()=>un,bytesToNumberBE:()=>ln,bytesToNumberLE:()=>Sr,concatBytes:()=>pn,createHmacDrbg:()=>uh,ensureBytes:()=>Ue,equalBytes:()=>sE,hexToBytes:()=>Lo,hexToNumber:()=>ah,inRange:()=>ya,isBytes:()=>qn,memoized:()=>Do,notImplemented:()=>fE,numberToBytesBE:()=>Gn,numberToBytesLE:()=>fn,numberToHexUnpadded:()=>Ro,numberToVarBytesBE:()=>iE,utf8ToBytes:()=>aE,validateObject:()=>rr});var Ku=BigInt(0),Hu=BigInt(1),nE=BigInt(2);function qn(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ji(r){if(!qn(r))throw new Error("Uint8Array expected")}function Ar(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var oE=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function un(r){Ji(r);let e="";for(let t=0;t<r.length;t++)e+=oE[r[t]];return e}function Ro(r){let e=r.toString(16);return e.length&1?"0"+e:e}function ah(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ku:BigInt("0x"+r)}var cn={_0:48,_9:57,A:65,F:70,a:97,f:102};function zg(r){if(r>=cn._0&&r<=cn._9)return r-cn._0;if(r>=cn.A&&r<=cn.F)return r-(cn.A-10);if(r>=cn.a&&r<=cn.f)return r-(cn.a-10)}function Lo(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=zg(r.charCodeAt(i)),a=zg(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ln(r){return ah(un(r))}function Sr(r){return Ji(r),ah(un(Uint8Array.from(r).reverse()))}function Gn(r,e){return Lo(r.toString(16).padStart(e*2,"0"))}function fn(r,e){return Gn(r,e).reverse()}function iE(r){return Lo(Ro(r))}function Ue(r,e,t){let n;if(typeof e=="string")try{n=Lo(e)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(qn(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function pn(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ji(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function sE(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function aE(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ih=r=>typeof r=="bigint"&&Ku<=r;function ya(r,e,t){return ih(r)&&ih(e)&&ih(t)&&e<=r&&r<t}function ht(r,e,t,n){if(!ya(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ch(r){let e;for(e=0;r>Ku;r>>=Hu,e+=1);return e}function cE(r,e){return r>>BigInt(e)&Hu}function uE(r,e,t){return r|(t?Hu:Ku)<<BigInt(e)}var ga=r=>(nE<<BigInt(r-1))-Hu,sh=r=>new Uint8Array(r),Xg=r=>Uint8Array.from(r);function uh(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=sh(r),o=sh(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...h)=>t(o,n,...h),c=(h=sh())=>{o=a(Xg([0]),h),n=a(),h.length!==0&&(o=a(Xg([1]),h),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){n=a();let g=n.slice();m.push(g),h+=n.length}return pn(...m)};return(h,m)=>{s(),c(h);let g;for(;!(g=m(l()));)c();return s(),g}}var lE={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||qn(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function rr(r,e,t={}){let n=(o,i,s)=>{let a=lE[i];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(e))n(o,i,!1);for(let[o,i]of Object.entries(t))n(o,i,!0);return r}var fE=()=>{throw new Error("not implemented")};function Do(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let i=r(t,...n);return e.set(t,i),i}}var st=BigInt(0),He=BigInt(1),Uo=BigInt(2),pE=BigInt(3),lh=BigInt(4),Yg=BigInt(5),Zg=BigInt(8),hE=BigInt(9),dE=BigInt(16);function _e(r,e){let t=r%e;return t>=st?t:e+t}function fh(r,e,t){if(e<st)throw new Error("invalid exponent, negatives unsupported");if(t<=st)throw new Error("invalid modulus");if(t===He)return st;let n=He;for(;e>st;)e&He&&(n=n*r%t),r=r*r%t,e>>=He;return n}function Ke(r,e,t){let n=r;for(;e-- >st;)n*=n,n%=t;return n}function $u(r,e){if(r===st)throw new Error("invert: expected non-zero number");if(e<=st)throw new Error("invert: expected positive modulus, got "+e);let t=_e(r,e),n=e,o=st,i=He,s=He,a=st;for(;t!==st;){let l=n/t,p=n%t,h=o-s*l,m=i-a*l;n=t,t=p,o=s,i=a,s=h,a=m}if(n!==He)throw new Error("invert: does not exist");return _e(o,e)}function mE(r){let e=(r-He)/Uo,t,n,o;for(t=r-He,n=0;t%Uo===st;t/=Uo,n++);for(o=Uo;o<r&&fh(o,e,r)!==r-He;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let s=(r+He)/lh;return function(c,l){let p=c.pow(l,s);if(!c.eql(c.sqr(p),l))throw new Error("Cannot find square root");return p}}let i=(t+He)/Uo;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,p=a.pow(a.mul(a.ONE,o),t),h=a.pow(c,i),m=a.pow(c,t);for(;!a.eql(m,a.ONE);){if(a.eql(m,a.ZERO))return a.ZERO;let g=1;for(let w=a.sqr(m);g<l&&!a.eql(w,a.ONE);g++)w=a.sqr(w);let x=a.pow(p,He<<BigInt(l-g-1));p=a.sqr(x),h=a.mul(h,x),m=a.mul(m,p),l=g}return h}}function yE(r){if(r%lh===pE){let e=(r+He)/lh;return function(n,o){let i=n.pow(o,e);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Zg===Yg){let e=(r-Yg)/Zg;return function(n,o){let i=n.mul(o,Uo),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,Uo),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%dE,mE(r)}var Jg=(r,e)=>(_e(r,e)&He)===He,gE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ph(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=gE.reduce((n,o)=>(n[o]="function",n),e);return rr(r,t)}function wE(r,e,t){if(t<st)throw new Error("invalid exponent, negatives unsupported");if(t===st)return r.ONE;if(t===He)return e;let n=r.ONE,o=e;for(;t>st;)t&He&&(n=r.mul(n,o)),o=r.sqr(o),t>>=He;return n}function xE(r,e){let t=new Array(e.length),n=e.reduce((i,s,a)=>r.is0(s)?i:(t[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return e.reduceRight((i,s,a)=>r.is0(s)?i:(t[a]=r.mul(i,t[a]),r.mul(i,s)),o),t}function hh(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function zn(r,e,t=!1,n={}){if(r<=st)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=hh(r,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:r,isLE:t,BITS:o,BYTES:i,MASK:ga(o),ZERO:st,ONE:He,create:c=>_e(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return st<=c&&c<r},is0:c=>c===st,isOdd:c=>(c&He)===He,neg:c=>_e(-c,r),eql:(c,l)=>c===l,sqr:c=>_e(c*c,r),add:(c,l)=>_e(c+l,r),sub:(c,l)=>_e(c-l,r),mul:(c,l)=>_e(c*l,r),pow:(c,l)=>wE(a,c,l),div:(c,l)=>_e(c*$u(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>$u(c,r),sqrt:n.sqrt||(c=>(s||(s=yE(r)),s(a,c))),invertBatch:c=>xE(a,c),cmov:(c,l,p)=>p?l:c,toBytes:c=>t?fn(c,i):Gn(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return t?Sr(c):ln(c)}});return Object.freeze(a)}function Qg(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function dh(r){let e=Qg(r);return e+Math.ceil(e/2)}function e0(r,e,t=!1){let n=r.length,o=Qg(e),i=dh(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?Sr(r):ln(r),a=_e(s,e-He)+He;return t?fn(a,o):Gn(a,o)}var t0=BigInt(0),Fu=BigInt(1);function mh(r,e){let t=e.negate();return r?t:e}function r0(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function yh(r,e){r0(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function bE(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function vE(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var gh=new WeakMap,n0=new WeakMap;function wh(r){return n0.get(r)||1}function Wu(r,e){return{constTimeNegate:mh,hasPrecomputes(t){return wh(t)!==1},unsafeLadder(t,n,o=r.ZERO){let i=t;for(;n>t0;)n&Fu&&(o=o.add(i)),i=i.double(),n>>=Fu;return o},precomputeWindow(t,n){let{windows:o,windowSize:i}=yh(n,e),s=[],a=t,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let p=1;p<i;p++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(t,n,o){let{windows:i,windowSize:s}=yh(t,e),a=r.ZERO,c=r.BASE,l=BigInt(2**t-1),p=2**t,h=BigInt(t);for(let m=0;m<i;m++){let g=m*s,x=Number(o&l);o>>=h,x>s&&(x-=p,o+=Fu);let w=g,y=g+Math.abs(x)-1,S=m%2!==0,T=x<0;x===0?c=c.add(mh(S,n[w])):a=a.add(mh(T,n[y]))}return{p:a,f:c}},wNAFUnsafe(t,n,o,i=r.ZERO){let{windows:s,windowSize:a}=yh(t,e),c=BigInt(2**t-1),l=2**t,p=BigInt(t);for(let h=0;h<s;h++){let m=h*a;if(o===t0)break;let g=Number(o&c);if(o>>=p,g>a&&(g-=l,o+=Fu),g===0)continue;let x=n[m+Math.abs(g)-1];g<0&&(x=x.negate()),i=i.add(x)}return i},getPrecomputes(t,n,o){let i=gh.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&gh.set(n,o(i))),i},wNAFCached(t,n,o){let i=wh(t);return this.wNAF(i,this.getPrecomputes(i,t,o),n)},wNAFCachedUnsafe(t,n,o,i){let s=wh(t);return s===1?this.unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,o),n,i)},setWindowSize(t,n){r0(n,e),n0.set(t,n),gh.delete(t)}}}function qu(r,e,t,n){if(bE(t,r),vE(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,i=ch(BigInt(t.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<<s)-1,c=new Array(a+1).fill(o),l=Math.floor((e.BITS-1)/s)*s,p=o;for(let h=l;h>=0;h-=s){c.fill(o);for(let g=0;g<n.length;g++){let x=n[g],w=Number(x>>BigInt(h)&BigInt(a));c[w]=c[w].add(t[g])}let m=o;for(let g=c.length-1,x=o;g>0;g--)x=x.add(c[g]),m=m.add(x);if(p=p.add(m),h!==0)for(let g=0;g<s;g++)p=p.double()}return p}function wa(r){return ph(r.Fp),rr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...hh(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Er=BigInt(0),Ot=BigInt(1),Gu=BigInt(2),AE=BigInt(8),SE={zip215:!0};function EE(r){let e=wa(r);return rr(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function o0(r){let e=EE(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,l=Gu<<BigInt(a*8)-Ot,p=t.create,h=zn(e.n,e.nBitLength),m=e.uvRatio||((I,E)=>{try{return{isValid:!0,value:t.sqrt(I*t.inv(E))}}catch{return{isValid:!1,value:Er}}}),g=e.adjustScalarBytes||(I=>I),x=e.domain||((I,E,P)=>{if(Ar("phflag",P),E.length||P)throw new Error("Contexts/pre-hash are not supported");return I});function w(I,E){ht("coordinate "+I,E,Er,l)}function y(I){if(!(I instanceof v))throw new Error("ExtendedPoint expected")}let S=Do((I,E)=>{let{ex:P,ey:B,ez:W}=I,q=I.is0();E==null&&(E=q?AE:t.inv(W));let N=p(P*E),ie=p(B*E),ce=p(W*E);if(q)return{x:Er,y:Ot};if(ce!==Ot)throw new Error("invZ was invalid");return{x:N,y:ie}}),T=Do(I=>{let{a:E,d:P}=e;if(I.is0())throw new Error("bad point: ZERO");let{ex:B,ey:W,ez:q,et:N}=I,ie=p(B*B),ce=p(W*W),ee=p(q*q),be=p(ee*ee),Ne=p(ie*E),Be=p(ee*p(Ne+ce)),De=p(be+p(P*p(ie*ce)));if(Be!==De)throw new Error("bad point: equation left != right (1)");let Oe=p(B*W),ft=p(q*N);if(Oe!==ft)throw new Error("bad point: equation left != right (2)");return!0});class v{constructor(E,P,B,W){this.ex=E,this.ey=P,this.ez=B,this.et=W,w("x",E),w("y",P),w("z",B),w("t",W),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof v)throw new Error("extended point not allowed");let{x:P,y:B}=E||{};return w("x",P),w("y",B),new v(P,B,Ot,p(P*B))}static normalizeZ(E){let P=t.invertBatch(E.map(B=>B.ez));return E.map((B,W)=>B.toAffine(P[W])).map(v.fromAffine)}static msm(E,P){return qu(v,h,E,P)}_setWindowSize(E){K.setWindowSize(this,E)}assertValidity(){T(this)}equals(E){y(E);let{ex:P,ey:B,ez:W}=this,{ex:q,ey:N,ez:ie}=E,ce=p(P*ie),ee=p(q*W),be=p(B*ie),Ne=p(N*W);return ce===ee&&be===Ne}is0(){return this.equals(v.ZERO)}negate(){return new v(p(-this.ex),this.ey,this.ez,p(-this.et))}double(){let{a:E}=e,{ex:P,ey:B,ez:W}=this,q=p(P*P),N=p(B*B),ie=p(Gu*p(W*W)),ce=p(E*q),ee=P+B,be=p(p(ee*ee)-q-N),Ne=ce+N,Be=Ne-ie,De=ce-N,Oe=p(be*Be),ft=p(Ne*De),We=p(be*De),Gt=p(Be*Ne);return new v(Oe,ft,Gt,We)}add(E){y(E);let{a:P,d:B}=e,{ex:W,ey:q,ez:N,et:ie}=this,{ex:ce,ey:ee,ez:be,et:Ne}=E;if(P===BigInt(-1)){let na=p((q-W)*(ee+ce)),Vi=p((q+W)*(ee-ce)),oa=p(Vi-na);if(oa===Er)return this.double();let yu=p(N*Gu*Ne),gu=p(ie*Gu*be),wu=gu+yu,Un=Vi+na,xu=gu-yu,_p=p(wu*oa),Cp=p(Un*xu),ia=p(wu*xu),b=p(oa*Un);return new v(_p,Cp,b,ia)}let Be=p(W*ce),De=p(q*ee),Oe=p(ie*B*Ne),ft=p(N*be),We=p((W+q)*(ce+ee)-Be-De),Gt=ft-Oe,gr=ft+Oe,nn=p(De-P*Be),pu=p(We*Gt),hu=p(gr*nn),du=p(We*nn),mu=p(Gt*gr);return new v(pu,hu,mu,du)}subtract(E){return this.add(E.negate())}wNAF(E){return K.wNAFCached(this,E,v.normalizeZ)}multiply(E){let P=E;ht("scalar",P,Ot,n);let{p:B,f:W}=this.wNAF(P);return v.normalizeZ([B,W])[0]}multiplyUnsafe(E,P=v.ZERO){let B=E;return ht("scalar",B,Er,n),B===Er?F:this.is0()||B===Ot?this:K.wNAFCachedUnsafe(this,B,v.normalizeZ,P)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return K.unsafeLadder(this,n).is0()}toAffine(E){return S(this,E)}clearCofactor(){let{h:E}=e;return E===Ot?this:this.multiplyUnsafe(E)}static fromHex(E,P=!1){let{d:B,a:W}=e,q=t.BYTES;E=Ue("pointHex",E,q),Ar("zip215",P);let N=E.slice(),ie=E[q-1];N[q-1]=ie&-129;let ce=Sr(N),ee=P?l:t.ORDER;ht("pointHex.y",ce,Er,ee);let be=p(ce*ce),Ne=p(be-Ot),Be=p(B*be-W),{isValid:De,value:Oe}=m(Ne,Be);if(!De)throw new Error("Point.fromHex: invalid y coordinate");let ft=(Oe&Ot)===Ot,We=(ie&128)!==0;if(!P&&Oe===Er&&We)throw new Error("Point.fromHex: x=0 and x_0=1");return We!==ft&&(Oe=p(-Oe)),v.fromAffine({x:Oe,y:ce})}static fromPrivateKey(E){return D(E).point}toRawBytes(){let{x:E,y:P}=this.toAffine(),B=fn(P,t.BYTES);return B[B.length-1]|=E&Ot?128:0,B}toHex(){return un(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ot,p(e.Gx*e.Gy)),v.ZERO=new v(Er,Ot,Ot,Er);let{BASE:L,ZERO:F}=v,K=Wu(v,a*8);function O(I){return _e(I,n)}function M(I){return O(Sr(I))}function D(I){let E=t.BYTES;I=Ue("private key",I,E);let P=Ue("hashed private key",i(I),2*E),B=g(P.slice(0,E)),W=P.slice(E,2*E),q=M(B),N=L.multiply(q),ie=N.toRawBytes();return{head:B,prefix:W,scalar:q,point:N,pointBytes:ie}}function ne(I){return D(I).pointBytes}function G(I=new Uint8Array,...E){let P=pn(...E);return M(i(x(P,Ue("context",I),!!o)))}function J(I,E,P={}){I=Ue("message",I),o&&(I=o(I));let{prefix:B,scalar:W,pointBytes:q}=D(E),N=G(P.context,B,I),ie=L.multiply(N).toRawBytes(),ce=G(P.context,ie,q,I),ee=O(N+ce*W);ht("signature.s",ee,Er,n);let be=pn(ie,fn(ee,t.BYTES));return Ue("result",be,t.BYTES*2)}let le=SE;function R(I,E,P,B=le){let{context:W,zip215:q}=B,N=t.BYTES;I=Ue("signature",I,2*N),E=Ue("message",E),P=Ue("publicKey",P,N),q!==void 0&&Ar("zip215",q),o&&(E=o(E));let ie=Sr(I.slice(N,2*N)),ce,ee,be;try{ce=v.fromHex(P,q),ee=v.fromHex(I.slice(0,N),q),be=L.multiplyUnsafe(ie)}catch{return!1}if(!q&&ce.isSmallOrder())return!1;let Ne=G(W,ee.toRawBytes(),ce.toRawBytes(),E);return ee.add(ce.multiplyUnsafe(Ne)).subtract(be).clearCofactor().equals(v.ZERO)}return L._setWindowSize(8),{CURVE:e,getPublicKey:ne,sign:J,verify:R,ExtendedPoint:v,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>s(t.BYTES),precompute(I=8,E=v.BASE){return E._setWindowSize(I),E.multiply(BigInt(3)),E}}}}var Qi=BigInt(0),xh=BigInt(1);function _E(r){return rr(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function i0(r){let e=_E(r),{P:t}=e,n=T=>_e(T,t),o=e.montgomeryBits,i=Math.ceil(o/8),s=e.nByteLength,a=e.adjustScalarBytes||(T=>T),c=e.powPminus2||(T=>fh(T,t-BigInt(2),t));function l(T,v,L){let F=n(T*(v-L));return v=n(v-F),L=n(L+F),[v,L]}let p=(e.a-BigInt(2))/BigInt(4);function h(T,v){ht("u",T,Qi,t),ht("scalar",v,Qi,t);let L=v,F=T,K=xh,O=Qi,M=T,D=xh,ne=Qi,G;for(let le=BigInt(o-1);le>=Qi;le--){let R=L>>le&xh;ne^=R,G=l(ne,K,M),K=G[0],M=G[1],G=l(ne,O,D),O=G[0],D=G[1],ne=R;let U=K+O,I=n(U*U),E=K-O,P=n(E*E),B=I-P,W=M+D,q=M-D,N=n(q*U),ie=n(W*E),ce=N+ie,ee=N-ie;M=n(ce*ce),D=n(F*n(ee*ee)),K=n(I*P),O=n(B*(I+n(p*B)))}G=l(ne,K,M),K=G[0],M=G[1],G=l(ne,O,D),O=G[0],D=G[1];let J=c(O);return n(K*J)}function m(T){return fn(n(T),i)}function g(T){let v=Ue("u coordinate",T,i);return s===32&&(v[31]&=127),Sr(v)}function x(T){let v=Ue("scalar",T),L=v.length;if(L!==i&&L!==s){let F=""+i+" or "+s;throw new Error("invalid scalar, expected "+F+" bytes, got "+L)}return Sr(a(v))}function w(T,v){let L=g(v),F=x(T),K=h(L,F);if(K===Qi)throw new Error("invalid private or public key received");return m(K)}let y=m(e.Gu);function S(T){return w(T,y)}return{scalarMult:w,scalarMultBase:S,getSharedSecret:(T,v)=>w(T,v),getPublicKey:T=>S(T),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}var xa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),s0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),WB=BigInt(0),CE=BigInt(1),a0=BigInt(2),IE=BigInt(3),TE=BigInt(5),BE=BigInt(8);function c0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=xa,a=r*r%i*r%i,c=Ke(a,a0,i)*a%i,l=Ke(c,CE,i)*r%i,p=Ke(l,TE,i)*l%i,h=Ke(p,e,i)*p%i,m=Ke(h,t,i)*h%i,g=Ke(m,n,i)*m%i,x=Ke(g,o,i)*g%i,w=Ke(x,o,i)*g%i,y=Ke(w,e,i)*p%i;return{pow_p_5_8:Ke(y,a0,i)*r%i,b2:a}}function u0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function kE(r,e){let t=xa,n=_e(e*e*e,t),o=_e(n*n*e,t),i=c0(r*o).pow_p_5_8,s=_e(r*n*i,t),a=_e(e*s*s,t),c=s,l=_e(s*s0,t),p=a===r,h=a===_e(-r,t),m=a===_e(-r*s0,t);return p&&(s=c),(h||m)&&(s=l),Jg(s,t)&&(s=_e(-s,t)),{isValid:p||h,value:s}}var PE=zn(xa,void 0,!0),NE={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:PE,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BE,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Gg,randomBytes:ma,adjustScalarBytes:u0,uvRatio:kE},ba=o0(NE);var va=i0({P:xa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=xa,{pow_p_5_8:t,b2:n}=c0(r);return _e(Ke(t,IE,e)*n,e)},adjustScalarBytes:u0,randomBytes:ma});var zu=32,Xu=64,bh=32;function l0(){let r=ba.utils.randomPrivateKey(),e=ba.getPublicKey(r);return{privateKey:OE(r,e),publicKey:e}}function f0(r,e){let t=r.subarray(0,bh);return ba.sign(e instanceof Uint8Array?e:e.subarray(),t)}function p0(r,e,t){return ba.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function OE(r,e){let t=new Uint8Array(Xu);for(let n=0;n<bh;n++)t[n]=r[n],t[bh+n]=e[n];return t}var Aa=class{type="Ed25519";raw;constructor(e){this.raw=Zu(e,zu)}toMultihash(){return xr.digest(Vn(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ke.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}verify(e,t){return p0(this.raw,t,e)}},Yu=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Zu(e,Xu),this.publicKey=new Aa(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}sign(e){return f0(this.raw,e)}};function vh(r){return r=Zu(r,zu),new Aa(r)}async function d0(){let{privateKey:r,publicKey:e}=l0();return new Yu(r,e)}function Zu(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new ve(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var RE=Math.pow(2,7),LE=Math.pow(2,14),DE=Math.pow(2,21),Ah=Math.pow(2,28),Sh=Math.pow(2,35),Eh=Math.pow(2,42),_h=Math.pow(2,49),Ie=128,Et=127;function Re(r){if(r<RE)return 1;if(r<LE)return 2;if(r<DE)return 3;if(r<Ah)return 4;if(r<Sh)return 5;if(r<Eh)return 6;if(r<_h)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ch(r,e,t=0){switch(Re(r)){case 8:e[t++]=r&255|Ie,r/=128;case 7:e[t++]=r&255|Ie,r/=128;case 6:e[t++]=r&255|Ie,r/=128;case 5:e[t++]=r&255|Ie,r/=128;case 4:e[t++]=r&255|Ie,r>>>=7;case 3:e[t++]=r&255|Ie,r>>>=7;case 2:e[t++]=r&255|Ie,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function UE(r,e,t=0){switch(Re(r)){case 8:e.set(t++,r&255|Ie),r/=128;case 7:e.set(t++,r&255|Ie),r/=128;case 6:e.set(t++,r&255|Ie),r/=128;case 5:e.set(t++,r&255|Ie),r/=128;case 4:e.set(t++,r&255|Ie),r>>>=7;case 3:e.set(t++,r&255|Ie),r>>>=7;case 2:e.set(t++,r&255|Ie),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ih(r,e){let t=r[e],n=0;if(n+=t&Et,t<Ie||(t=r[e+1],n+=(t&Et)<<7,t<Ie)||(t=r[e+2],n+=(t&Et)<<14,t<Ie)||(t=r[e+3],n+=(t&Et)<<21,t<Ie)||(t=r[e+4],n+=(t&Et)*Ah,t<Ie)||(t=r[e+5],n+=(t&Et)*Sh,t<Ie)||(t=r[e+6],n+=(t&Et)*Eh,t<Ie)||(t=r[e+7],n+=(t&Et)*_h,t<Ie))return n;throw new RangeError("Could not decode varint")}function jE(r,e){let t=r.get(e),n=0;if(n+=t&Et,t<Ie||(t=r.get(e+1),n+=(t&Et)<<7,t<Ie)||(t=r.get(e+2),n+=(t&Et)<<14,t<Ie)||(t=r.get(e+3),n+=(t&Et)<<21,t<Ie)||(t=r.get(e+4),n+=(t&Et)*Ah,t<Ie)||(t=r.get(e+5),n+=(t&Et)*Sh,t<Ie)||(t=r.get(e+6),n+=(t&Et)*Eh,t<Ie)||(t=r.get(e+7),n+=(t&Et)*_h,t<Ie))return n;throw new RangeError("Could not decode varint")}function nr(r,e,t=0){return e==null&&(e=ot(Re(r))),e instanceof Uint8Array?Ch(r,e,t):UE(r,e,t)}function zt(r,e=0){return r instanceof Uint8Array?Ih(r,e):jE(r,e)}var Th=new Float32Array([-0]),Xn=new Uint8Array(Th.buffer);function m0(r,e,t){Th[0]=r,e[t]=Xn[0],e[t+1]=Xn[1],e[t+2]=Xn[2],e[t+3]=Xn[3]}function y0(r,e){return Xn[0]=r[e],Xn[1]=r[e+1],Xn[2]=r[e+2],Xn[3]=r[e+3],Th[0]}var Bh=new Float64Array([-0]),_t=new Uint8Array(Bh.buffer);function g0(r,e,t){Bh[0]=r,e[t]=_t[0],e[t+1]=_t[1],e[t+2]=_t[2],e[t+3]=_t[3],e[t+4]=_t[4],e[t+5]=_t[5],e[t+6]=_t[6],e[t+7]=_t[7]}function w0(r,e){return _t[0]=r[e],_t[1]=r[e+1],_t[2]=r[e+2],_t[3]=r[e+3],_t[4]=r[e+4],_t[5]=r[e+5],_t[6]=r[e+6],_t[7]=r[e+7],Bh[0]}var ME=BigInt(Number.MAX_SAFE_INTEGER),KE=BigInt(Number.MIN_SAFE_INTEGER),Xt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return jo;if(e<ME&&e>KE)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>x0&&(o=0n,++n>x0&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return jo;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):jo}},jo=new Xt(0,0);jo.toBigInt=function(){return 0n};jo.zzEncode=jo.zzDecode=function(){return this};jo.length=function(){return 1};var x0=4294967296n;function b0(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function v0(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function kh(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function _r(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ju(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ph=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,_r(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw _r(this,4);return Ju(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw _r(this,4);return Ju(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw _r(this,4);let e=y0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw _r(this,4);let e=w0(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw _r(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return v0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw _r(this,e);this.pos+=e}else do if(this.pos>=this.len)throw _r(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Xt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw _r(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw _r(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw _r(this,8);let e=Ju(this.buf,this.pos+=4),t=Ju(this.buf,this.pos+=4);return new Xt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Ih(this.buf,this.pos);return this.pos+=Re(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Nh(r){return new Ph(r instanceof Uint8Array?r:r.subarray())}function Cr(r,e,t){let n=Nh(r);return e.decode(n,void 0,t)}function Oh(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return ot(s);o+s>e&&(n=ot(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var Mo=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Rh(){}var Dh=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},HE=Oh();function VE(r){return globalThis.Buffer!=null?ot(r):HE(r)}var Ea=class{len;head;tail;states;constructor(){this.len=0,this.head=new Mo(Rh,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Mo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Uh((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Qu,10,Xt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Xt.fromBigInt(e);return this._push(Qu,t.length(),t)}uint64Number(e){return this._push(Ch,Re(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Xt.fromBigInt(e).zzEncode();return this._push(Qu,t.length(),t)}sint64Number(e){let t=Xt.fromNumber(e).zzEncode();return this._push(Qu,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Lh,1,e?1:0)}fixed32(e){return this._push(Sa,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Xt.fromBigInt(e);return this._push(Sa,4,t.lo)._push(Sa,4,t.hi)}fixed64Number(e){let t=Xt.fromNumber(e);return this._push(Sa,4,t.lo)._push(Sa,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(m0,4,e)}double(e){return this._push(g0,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Lh,1,0):this.uint32(t)._push(FE,t,e)}string(e){let t=b0(e);return t!==0?this.uint32(t)._push(kh,t,e):this._push(Lh,1,0)}fork(){return this.states=new Dh(this),this.head=this.tail=new Mo(Rh,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Mo(Rh,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=VE(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Lh(r,e,t){e[t]=r&255}function $E(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Uh=class extends Mo{next;constructor(e,t){super($E,e,t),this.next=void 0}};function Qu(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Sa(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function FE(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ea.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(WE,e,r),this},Ea.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(qE,e,r),this});function WE(r,e,t){e.set(r,t)}function qE(r,e,t){r.length<40?kh(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(de(r),t)}function jh(){return new Ea}function Ir(r,e){let t=jh();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var ts;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(ts||(ts={}));function el(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ko(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return el("enum",ts.VARINT,t,n)}function Tr(r,e){return el("message",ts.LENGTH_DELIMITED,r,e)}var _a=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Qe||(Qe={}));var Mh;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Mh||(Mh={}));(function(r){r.codec=()=>Ko(Mh)})(Qe||(Qe={}));var Mr;(function(r){let e;r.codec=()=>(e==null&&(e=Tr((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Qe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=Qe.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Ir(t,r.codec()),r.decode=(t,n)=>Cr(t,r.codec(),n)})(Mr||(Mr={}));var Kh;(function(r){let e;r.codec=()=>(e==null&&(e=Tr((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Qe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=Qe.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Ir(t,r.codec()),r.decode=(t,n)=>Cr(t,r.codec(),n)})(Kh||(Kh={}));var Ca=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Ia=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},tl=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var E0={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new tl("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Yn=E0;var Ba={};pt(Ba,{MAX_RSA_KEY_SIZE:()=>Vh,generateRSAKeyPair:()=>Zh,jwkToJWKKeyPair:()=>T0,jwkToPkcs1:()=>ZE,jwkToPkix:()=>qh,jwkToRSAPrivateKey:()=>Yh,pkcs1MessageToJwk:()=>Fh,pkcs1MessageToRSAPrivateKey:()=>Gh,pkcs1ToJwk:()=>YE,pkcs1ToRSAPrivateKey:()=>I0,pkixMessageToJwk:()=>Wh,pkixMessageToRSAPublicKey:()=>Xh,pkixToJwk:()=>JE,pkixToRSAPublicKey:()=>zh});var GE=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]),Zn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jn=new Uint32Array(64),Hh=class extends Zi{constructor(){super(64,32,8,!1),this.A=Zn[0]|0,this.B=Zn[1]|0,this.C=Zn[2]|0,this.D=Zn[3]|0,this.E=Zn[4]|0,this.F=Zn[5]|0,this.G=Zn[6]|0,this.H=Zn[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)Jn[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let m=Jn[h-15],g=Jn[h-2],x=vr(m,7)^vr(m,18)^m>>>3,w=vr(g,17)^vr(g,19)^g>>>10;Jn[h]=w+Jn[h-7]+x+Jn[h-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:p}=this;for(let h=0;h<64;h++){let m=vr(a,6)^vr(a,11)^vr(a,25),g=p+m+Fg(a,c,l)+GE[h]+Jn[h]|0,w=(vr(n,2)^vr(n,13)^vr(n,22))+Wg(n,o,i)|0;p=l,l=c,c=a,a=s+g|0,s=i,i=o,o=n,n=g+w|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,p=p+this.H|0,this.set(n,o,i,s,a,c,l,p)}roundClean(){Jn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Kr=ju(()=>new Hh);var rs=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ba.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Je.createV1(114,this._multihash)}toString(){return ke.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}verify(e,t){return C0(this.jwk,t,e)}},Ta=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ba.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}sign(e){return _0(this.jwk,e)}};var Vh=8192,$h=18,zE=1062,XE=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function YE(r){let e=an(r);return Fh(e)}function Fh(r){return{n:ue(r[1],"base64url"),e:ue(r[2],"base64url"),d:ue(r[3],"base64url"),p:ue(r[4],"base64url"),q:ue(r[5],"base64url"),dp:ue(r[6],"base64url"),dq:ue(r[7],"base64url"),qi:ue(r[8],"base64url"),kty:"RSA"}}function ZE(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new ve("JWK was missing components");return br([Bt(Uint8Array.from([0])),Bt(de(r.n,"base64url")),Bt(de(r.e,"base64url")),Bt(de(r.d,"base64url")),Bt(de(r.p,"base64url")),Bt(de(r.q,"base64url")),Bt(de(r.dp,"base64url")),Bt(de(r.dq,"base64url")),Bt(de(r.qi,"base64url"))]).subarray()}function JE(r){let e=an(r,{offset:0});return Wh(e)}function Wh(r){let e=an(r[1],{offset:0});return{kty:"RSA",n:ue(e[0],"base64url"),e:ue(e[1],"base64url")}}function qh(r){if(r.n==null||r.e==null)throw new ve("JWK was missing components");return br([XE,ha(br([Bt(de(r.n,"base64url")),Bt(de(r.e,"base64url"))]))]).subarray()}function I0(r){let e=an(r);return Gh(e)}function Gh(r){let e=Fh(r);return Yh(e)}function zh(r,e){if(r.byteLength>=zE)throw new $i("Key size is too large");let t=an(r,{offset:0});return Xh(t,r,e)}function Xh(r,e,t){let n=Wh(r);if(t==null){let o=Kr(Mr.encode({Type:Qe.RSA,Data:e}));t=St($h,o)}return new rs(n,t)}function Yh(r){if(k0(r)>Vh)throw new ve("Key size is too large");let e=T0(r),t=Kr(Mr.encode({Type:Qe.RSA,Data:qh(e.publicKey)})),n=St($h,t);return new Ta(e.privateKey,new rs(e.publicKey,n))}async function Zh(r){if(r>Vh)throw new ve("Key size is too large");let e=await B0(r),t=Kr(Mr.encode({Type:Qe.RSA,Data:qh(e.publicKey)})),n=St($h,t);return new Ta(e.privateKey,new rs(e.publicKey,n))}function T0(r){if(r==null)throw new ve("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function B0(r){let e=await Yn.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await QE(e);return{privateKey:t[0],publicKey:t[1]}}async function _0(r,e){let t=await Yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Yn.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function C0(r,e,t){let n=await Yn.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Yn.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function QE(r){if(r.privateKey==null||r.publicKey==null)throw new ve("Private and public key are required");return Promise.all([Yn.get().subtle.exportKey("jwk",r.privateKey),Yn.get().subtle.exportKey("jwk",r.publicKey)])}function k0(r){if(r.kty!=="RSA")throw new ve("invalid key type");if(r.n==null)throw new ve("invalid key modulus");return de(r.n,"base64url").length*8}var rl=class extends Yi{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,da(e);let n=$n(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return Xi(this),this.iHash.update(e),this}digestInto(e){Xi(this),zi(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ns=(r,e,t)=>new rl(r,e).update(t).digest();ns.create=(r,e)=>new rl(r,e);function P0(r){r.lowS!==void 0&&Ar("lowS",r.lowS),r.prehash!==void 0&&Ar("prehash",r.prehash)}function e2(r){let e=wa(r);rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:t2,hexToBytes:r2}=Vu,Jh=class extends Error{constructor(e=""){super(e)}},hn={Err:Jh,_tlv:{encode:(r,e)=>{let{Err:t}=hn;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Ro(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?Ro(o.length/2|128):"";return Ro(r)+i+o+e},decode(r,e){let{Err:t}=hn,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of l)s=s<<8|p;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=hn;if(r<dn)throw new e("integer: negative integers are not allowed");let t=Ro(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=hn;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return t2(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=hn,o=typeof r=="string"?r2(r):r;Ji(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:p}=n.decode(2,c);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=hn,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}},dn=BigInt(0),ut=BigInt(1),gk=BigInt(2),N0=BigInt(3),wk=BigInt(4);function n2(r){let e=e2(r),{Fp:t}=e,n=zn(e.n,e.nBitLength),o=e.toBytes||((w,y,S)=>{let T=y.toAffine();return pn(Uint8Array.from([4]),t.toBytes(T.x),t.toBytes(T.y))}),i=e.fromBytes||(w=>{let y=w.subarray(1),S=t.fromBytes(y.subarray(0,t.BYTES)),T=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:S,y:T}});function s(w){let{a:y,b:S}=e,T=t.sqr(w),v=t.mul(T,w);return t.add(t.add(v,t.mul(w,y)),S)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function a(w){return ya(w,ut,e.n)}function c(w){let{allowedPrivateKeyLengths:y,nByteLength:S,wrapPrivateKey:T,n:v}=e;if(y&&typeof w!="bigint"){if(qn(w)&&(w=un(w)),typeof w!="string"||!y.includes(w.length))throw new Error("invalid private key");w=w.padStart(S*2,"0")}let L;try{L=typeof w=="bigint"?w:ln(Ue("private key",w,S))}catch{throw new Error("invalid private key, expected hex or "+S+" bytes, got "+typeof w)}return T&&(L=_e(L,v)),ht("private key",L,ut,v),L}function l(w){if(!(w instanceof m))throw new Error("ProjectivePoint expected")}let p=Do((w,y)=>{let{px:S,py:T,pz:v}=w;if(t.eql(v,t.ONE))return{x:S,y:T};let L=w.is0();y==null&&(y=L?t.ONE:t.inv(v));let F=t.mul(S,y),K=t.mul(T,y),O=t.mul(v,y);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:F,y:K}}),h=Do(w=>{if(w.is0()){if(e.allowInfinityPoint&&!t.is0(w.py))return;throw new Error("bad point: ZERO")}let{x:y,y:S}=w.toAffine();if(!t.isValid(y)||!t.isValid(S))throw new Error("bad point: x or y not FE");let T=t.sqr(S),v=s(y);if(!t.eql(T,v))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class m{constructor(y,S,T){if(this.px=y,this.py=S,this.pz=T,y==null||!t.isValid(y))throw new Error("x required");if(S==null||!t.isValid(S))throw new Error("y required");if(T==null||!t.isValid(T))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:S,y:T}=y||{};if(!y||!t.isValid(S)||!t.isValid(T))throw new Error("invalid affine point");if(y instanceof m)throw new Error("projective point not allowed");let v=L=>t.eql(L,t.ZERO);return v(S)&&v(T)?m.ZERO:new m(S,T,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let S=t.invertBatch(y.map(T=>T.pz));return y.map((T,v)=>T.toAffine(S[v])).map(m.fromAffine)}static fromHex(y){let S=m.fromAffine(i(Ue("pointHex",y)));return S.assertValidity(),S}static fromPrivateKey(y){return m.BASE.multiply(c(y))}static msm(y,S){return qu(m,n,y,S)}_setWindowSize(y){x.setWindowSize(this,y)}assertValidity(){h(this)}hasEvenY(){let{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);let{px:S,py:T,pz:v}=this,{px:L,py:F,pz:K}=y,O=t.eql(t.mul(S,K),t.mul(L,v)),M=t.eql(t.mul(T,K),t.mul(F,v));return O&&M}negate(){return new m(this.px,t.neg(this.py),this.pz)}double(){let{a:y,b:S}=e,T=t.mul(S,N0),{px:v,py:L,pz:F}=this,K=t.ZERO,O=t.ZERO,M=t.ZERO,D=t.mul(v,v),ne=t.mul(L,L),G=t.mul(F,F),J=t.mul(v,L);return J=t.add(J,J),M=t.mul(v,F),M=t.add(M,M),K=t.mul(y,M),O=t.mul(T,G),O=t.add(K,O),K=t.sub(ne,O),O=t.add(ne,O),O=t.mul(K,O),K=t.mul(J,K),M=t.mul(T,M),G=t.mul(y,G),J=t.sub(D,G),J=t.mul(y,J),J=t.add(J,M),M=t.add(D,D),D=t.add(M,D),D=t.add(D,G),D=t.mul(D,J),O=t.add(O,D),G=t.mul(L,F),G=t.add(G,G),D=t.mul(G,J),K=t.sub(K,D),M=t.mul(G,ne),M=t.add(M,M),M=t.add(M,M),new m(K,O,M)}add(y){l(y);let{px:S,py:T,pz:v}=this,{px:L,py:F,pz:K}=y,O=t.ZERO,M=t.ZERO,D=t.ZERO,ne=e.a,G=t.mul(e.b,N0),J=t.mul(S,L),le=t.mul(T,F),R=t.mul(v,K),U=t.add(S,T),I=t.add(L,F);U=t.mul(U,I),I=t.add(J,le),U=t.sub(U,I),I=t.add(S,v);let E=t.add(L,K);return I=t.mul(I,E),E=t.add(J,R),I=t.sub(I,E),E=t.add(T,v),O=t.add(F,K),E=t.mul(E,O),O=t.add(le,R),E=t.sub(E,O),D=t.mul(ne,I),O=t.mul(G,R),D=t.add(O,D),O=t.sub(le,D),D=t.add(le,D),M=t.mul(O,D),le=t.add(J,J),le=t.add(le,J),R=t.mul(ne,R),I=t.mul(G,I),le=t.add(le,R),R=t.sub(J,R),R=t.mul(ne,R),I=t.add(I,R),J=t.mul(le,I),M=t.add(M,J),J=t.mul(E,I),O=t.mul(U,O),O=t.sub(O,J),J=t.mul(U,le),D=t.mul(E,D),D=t.add(D,J),new m(O,M,D)}subtract(y){return this.add(y.negate())}is0(){return this.equals(m.ZERO)}wNAF(y){return x.wNAFCached(this,y,m.normalizeZ)}multiplyUnsafe(y){let{endo:S,n:T}=e;ht("scalar",y,dn,T);let v=m.ZERO;if(y===dn)return v;if(this.is0()||y===ut)return this;if(!S||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,y,m.normalizeZ);let{k1neg:L,k1:F,k2neg:K,k2:O}=S.splitScalar(y),M=v,D=v,ne=this;for(;F>dn||O>dn;)F&ut&&(M=M.add(ne)),O&ut&&(D=D.add(ne)),ne=ne.double(),F>>=ut,O>>=ut;return L&&(M=M.negate()),K&&(D=D.negate()),D=new m(t.mul(D.px,S.beta),D.py,D.pz),M.add(D)}multiply(y){let{endo:S,n:T}=e;ht("scalar",y,ut,T);let v,L;if(S){let{k1neg:F,k1:K,k2neg:O,k2:M}=S.splitScalar(y),{p:D,f:ne}=this.wNAF(K),{p:G,f:J}=this.wNAF(M);D=x.constTimeNegate(F,D),G=x.constTimeNegate(O,G),G=new m(t.mul(G.px,S.beta),G.py,G.pz),v=D.add(G),L=ne.add(J)}else{let{p:F,f:K}=this.wNAF(y);v=F,L=K}return m.normalizeZ([v,L])[0]}multiplyAndAddUnsafe(y,S,T){let v=m.BASE,L=(K,O)=>O===dn||O===ut||!K.equals(v)?K.multiplyUnsafe(O):K.multiply(O),F=L(this,S).add(L(y,T));return F.is0()?void 0:F}toAffine(y){return p(this,y)}isTorsionFree(){let{h:y,isTorsionFree:S}=e;if(y===ut)return!0;if(S)return S(m,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:S}=e;return y===ut?this:S?S(m,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return Ar("isCompressed",y),this.assertValidity(),o(m,this,y)}toHex(y=!0){return Ar("isCompressed",y),un(this.toRawBytes(y))}}m.BASE=new m(e.Gx,e.Gy,t.ONE),m.ZERO=new m(t.ZERO,t.ONE,t.ZERO);let g=e.nBitLength,x=Wu(m,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:m,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function o2(r){let e=wa(r);return rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function O0(r){let e=o2(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(R){return _e(R,n)}function a(R){return $u(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:p,isWithinCurveOrder:h}=n2({...e,toBytes(R,U,I){let E=U.toAffine(),P=t.toBytes(E.x),B=pn;return Ar("isCompressed",I),I?B(Uint8Array.from([U.hasEvenY()?2:3]),P):B(Uint8Array.from([4]),P,t.toBytes(E.y))},fromBytes(R){let U=R.length,I=R[0],E=R.subarray(1);if(U===o&&(I===2||I===3)){let P=ln(E);if(!ya(P,ut,t.ORDER))throw new Error("Point is not on curve");let B=p(P),W;try{W=t.sqrt(B)}catch(ie){let ce=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+ce)}let q=(W&ut)===ut;return(I&1)===1!==q&&(W=t.neg(W)),{x:P,y:W}}else if(U===i&&I===4){let P=t.fromBytes(E.subarray(0,t.BYTES)),B=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:P,y:B}}else{let P=o,B=i;throw new Error("invalid Point, expected length of "+P+", or uncompressed "+B+", got "+U)}}}),m=R=>un(Gn(R,e.nByteLength));function g(R){let U=n>>ut;return R>U}function x(R){return g(R)?s(-R):R}let w=(R,U,I)=>ln(R.slice(U,I));class y{constructor(U,I,E){this.r=U,this.s=I,this.recovery=E,this.assertValidity()}static fromCompact(U){let I=e.nByteLength;return U=Ue("compactSignature",U,I*2),new y(w(U,0,I),w(U,I,2*I))}static fromDER(U){let{r:I,s:E}=hn.toSig(Ue("DER",U));return new y(I,E)}assertValidity(){ht("r",this.r,ut,n),ht("s",this.s,ut,n)}addRecoveryBit(U){return new y(this.r,this.s,U)}recoverPublicKey(U){let{r:I,s:E,recovery:P}=this,B=K(Ue("msgHash",U));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");let W=P===2||P===3?I+e.n:I;if(W>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=(P&1)===0?"02":"03",N=c.fromHex(q+m(W)),ie=a(W),ce=s(-B*ie),ee=s(E*ie),be=c.BASE.multiplyAndAddUnsafe(N,ce,ee);if(!be)throw new Error("point at infinify");return be.assertValidity(),be}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Lo(this.toDERHex())}toDERHex(){return hn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Lo(this.toCompactHex())}toCompactHex(){return m(this.r)+m(this.s)}}let S={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=dh(e.n);return e0(e.randomBytes(R),e.n)},precompute(R=8,U=c.BASE){return U._setWindowSize(R),U.multiply(BigInt(3)),U}};function T(R,U=!0){return c.fromPrivateKey(R).toRawBytes(U)}function v(R){let U=qn(R),I=typeof R=="string",E=(U||I)&&R.length;return U?E===o||E===i:I?E===2*o||E===2*i:R instanceof c}function L(R,U,I=!0){if(v(R))throw new Error("first arg must be private key");if(!v(U))throw new Error("second arg must be public key");return c.fromHex(U).multiply(l(R)).toRawBytes(I)}let F=e.bits2int||function(R){if(R.length>8192)throw new Error("input is too large");let U=ln(R),I=R.length*8-e.nBitLength;return I>0?U>>BigInt(I):U},K=e.bits2int_modN||function(R){return s(F(R))},O=ga(e.nBitLength);function M(R){return ht("num < 2^"+e.nBitLength,R,dn,O),Gn(R,e.nByteLength)}function D(R,U,I=ne){if(["recovered","canonical"].some(Be=>Be in I))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:P}=e,{lowS:B,prehash:W,extraEntropy:q}=I;B==null&&(B=!0),R=Ue("msgHash",R),P0(I),W&&(R=Ue("prehashed msgHash",E(R)));let N=K(R),ie=l(U),ce=[M(ie),M(N)];if(q!=null&&q!==!1){let Be=q===!0?P(t.BYTES):q;ce.push(Ue("extraEntropy",Be))}let ee=pn(...ce),be=N;function Ne(Be){let De=F(Be);if(!h(De))return;let Oe=a(De),ft=c.BASE.multiply(De).toAffine(),We=s(ft.x);if(We===dn)return;let Gt=s(Oe*s(be+We*ie));if(Gt===dn)return;let gr=(ft.x===We?0:2)|Number(ft.y&ut),nn=Gt;return B&&g(Gt)&&(nn=x(Gt),gr^=1),new y(We,nn,gr)}return{seed:ee,k2sig:Ne}}let ne={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function J(R,U,I=ne){let{seed:E,k2sig:P}=D(R,U,I),B=e;return uh(B.hash.outputLen,B.nByteLength,B.hmac)(E,P)}c.BASE._setWindowSize(8);function le(R,U,I,E=G){let P=R;U=Ue("msgHash",U),I=Ue("publicKey",I);let{lowS:B,prehash:W,format:q}=E;if(P0(E),"strict"in E)throw new Error("options.strict was renamed to lowS");if(q!==void 0&&q!=="compact"&&q!=="der")throw new Error("format must be compact or der");let N=typeof P=="string"||qn(P),ie=!N&&!q&&typeof P=="object"&&P!==null&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!N&&!ie)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let ce,ee;try{if(ie&&(ce=new y(P.r,P.s)),N){try{q!=="compact"&&(ce=y.fromDER(P))}catch(gr){if(!(gr instanceof hn.Err))throw gr}!ce&&q!=="der"&&(ce=y.fromCompact(P))}ee=c.fromHex(I)}catch{return!1}if(!ce||B&&ce.hasHighS())return!1;W&&(U=e.hash(U));let{r:be,s:Ne}=ce,Be=K(U),De=a(Ne),Oe=s(Be*De),ft=s(be*De),We=c.BASE.multiplyAndAddUnsafe(ee,Oe,ft)?.toAffine();return We?s(We.x)===be:!1}return{CURVE:e,getPublicKey:T,getSharedSecret:L,sign:J,verify:le,ProjectivePoint:c,Signature:y,utils:S}}function i2(r){return{hash:r,hmac:(e,...t)=>ns(r,e,rh(...t)),randomBytes:ma}}function R0(r,e){let t=n=>O0({...r,...i2(n)});return{...t(e),create:t}}var U0=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),L0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),s2=BigInt(1),Qh=BigInt(2),D0=(r,e)=>(r+e/Qh)/e;function a2(r){let e=U0,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,p=l*l*r%e,h=Ke(p,t,e)*p%e,m=Ke(h,t,e)*p%e,g=Ke(m,Qh,e)*l%e,x=Ke(g,o,e)*g%e,w=Ke(x,i,e)*x%e,y=Ke(w,a,e)*w%e,S=Ke(y,c,e)*y%e,T=Ke(S,a,e)*w%e,v=Ke(T,t,e)*p%e,L=Ke(v,s,e)*x%e,F=Ke(L,n,e)*l%e,K=Ke(F,Qh,e);if(!ed.eql(ed.sqr(K),r))throw new Error("Cannot find square root");return K}var ed=zn(U0,void 0,void 0,{sqrt:a2}),or=R0({a:BigInt(0),b:BigInt(7),Fp:ed,n:L0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=L0,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-s2*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=D0(i*r,e),c=D0(-n*r,e),l=_e(r-a*t-c*o,e),p=_e(-a*n-c*i,e),h=l>s,m=p>s;if(h&&(l=e-l),m&&(p=e-p),l>s||p>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:h,k1:l,k2neg:m,k2:p}}}},Kr),Ik=BigInt(0);var Tk=or.ProjectivePoint;function td(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function j0(r,e){let t=tr.digest(e instanceof Uint8Array?e:e.subarray());if(td(t))return t.then(({digest:n})=>or.sign(n,r).toDERRawBytes()).catch(n=>{throw new Ca(String(n))});try{return or.sign(t.digest,r).toDERRawBytes()}catch(n){throw new Ca(String(n))}}function M0(r,e,t){let n=tr.digest(t instanceof Uint8Array?t:t.subarray());if(td(n))return n.then(({digest:o})=>or.verify(e,o,r)).catch(o=>{throw new Ia(String(o))});try{return or.verify(e,n.digest,r)}catch(o){throw new Ia(String(o))}}var ka=class{type="secp256k1";raw;_key;constructor(e){this._key=V0(e),this.raw=K0(this._key)}toMultihash(){return xr.digest(Vn(this))}toCID(){return Je.createV1(114,this.toMultihash())}toString(){return ke.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}verify(e,t){return M0(this._key,t,e)}},nl=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=H0(e),this.publicKey=new ka(t??$0(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ge(this.raw,e.raw)}sign(e){return j0(this.raw,e)}};function rd(r){return new ka(r)}async function F0(){let r=c2();return new nl(r)}function K0(r){return or.ProjectivePoint.fromHex(r).toRawBytes(!0)}function H0(r){try{return or.getPublicKey(r,!0),r}catch(e){throw new sa(String(e))}}function V0(r){try{return or.ProjectivePoint.fromHex(r),r}catch(e){throw new $i(String(e))}}function $0(r){try{return or.getPublicKey(r,!0)}catch(e){throw new sa(String(e))}}function c2(){return or.utils.randomPrivateKey()}async function W0(r,e){if(r==="Ed25519")return d0();if(r==="secp256k1")return F0();if(r==="RSA")return Zh(u2(e));if(r==="ECDSA")return Hg(l2(e));throw new jn}function Pa(r,e){let{Type:t,Data:n}=Mr.decode(r),o=n??new Uint8Array;switch(t){case Qe.RSA:return zh(o,e);case Qe.Ed25519:return vh(o);case Qe.secp256k1:return rd(o);case Qe.ECDSA:return th(o);default:throw new jn}}function q0(r){let{Type:e,Data:t}=Mr.decode(r.digest),n=t??new Uint8Array;switch(e){case Qe.Ed25519:return vh(n);case Qe.secp256k1:return rd(n);case Qe.ECDSA:return th(n);default:throw new jn}}function Vn(r){return Mr.encode({Type:Qe[r.type],Data:r.raw})}function u2(r){return r==null?2048:parseInt(r,10)}function l2(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new ve("Unsupported curve, should be P-256, P-384 or P-521")}async function ol(r){if(r.type==="RSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};if(r.type==="ECDSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"ECDSA",namedCurve:r.jwk.crv??"P-256"},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"ECDSA",namedCurve:r.publicKey.jwk.crv??"P-256"},!0,["verify"])};throw new ve("Only RSA and ECDSA keys are supported")}var G0=Symbol.for("nodejs.util.inspect.custom"),f2=114,Na=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Tp]=!0;toString(){return this.string==null&&(this.string=ke.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Je.createV1(f2,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ge(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ge(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[G0](){return`PeerId(${this.toString()})`}},Oa=class extends Na{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ra=class extends Na{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},La=class extends Na{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},p2=2336,Da=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=xr.digest(de(this.url))}[G0](){return`PeerId(${this.url})`}[Tp]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Je.createV1(p2,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ue(e)),e.toString()===this.toString())}};var h2=114,z0=2336;function os(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Hn(ke.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return d2(Je.parse(r));if(e==null)throw new ve('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Hn(e.decode(r))}return X0(t)}function nd(r){if(r.type==="Ed25519")return new Ra({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new La({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Oa({multihash:r.toCID().multihash,publicKey:r});throw new jn}function X0(r){if(y2(r))return new Oa({multihash:r});if(m2(r))try{let e=q0(r);if(e.type==="Ed25519")return new Ra({multihash:r,publicKey:e});if(e.type==="secp256k1")return new La({multihash:r,publicKey:e})}catch{let t=ue(r.digest);return new Da(new URL(t))}throw new Iu("Supplied PeerID Multihash is invalid")}function d2(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==h2&&r.code!==z0)throw new Cu("Supplied PeerID CID is invalid");if(r.code===z0){let e=ue(r.multihash.digest);return new Da(new URL(e))}return X0(r.multihash)}function m2(r){return r.code===xr.code}function y2(r){return r.code===tr.code}var il=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let p=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let m=Number.parseInt(h,e);if(!Number.isNaN(m))return m});if(p===void 0)break;if(i*=e,i+=p,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Y0=45,g2=15,is=new il;function od(r){if(!(r.length>g2))return is.new(r).parseWith(()=>is.readIPv4Addr())}function id(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Y0))return is.new(r).parseWith(()=>is.readIPv6Addr())}function sl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Y0)return;let t=is.new(r).parseWith(()=>is.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}var O5=parseInt("0xFFFF",16),R5=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function al(r){return!!od(r)}function cl(r){return!!id(r)}function ul(r){return!!sl(r)}var Q0=al,A2=cl,sd=function(r){let e=0;if(r=r.toString().trim(),Q0(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(A2(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Q0(t[n]),s;i&&(s=sd(t[n]),t[n]=ue(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,ue(s.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},ew=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ss={},ad={},E2=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];E2.forEach(r=>{let e=_2(...r);ad[e.code]=e,ss[e.name]=e});function _2(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Le(r){if(typeof r=="number"){if(ad[r]!=null)return ad[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ss[r]!=null)return ss[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var g4=Le("ip4"),w4=Le("ip6"),x4=Le("ipcidr");function fd(r,e){switch(Le(r).code){case 4:case 41:return I2(e);case 42:return ld(e);case 43:return ue(e,"base10");case 6:case 273:case 33:case 132:return nw(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ld(e);case 421:return P2(e);case 444:return rw(e);case 445:return rw(e);case 466:return k2(e);case 481:return globalThis.encodeURIComponent(ld(e));default:return ue(e,"base16")}}function pd(r,e){switch(Le(r).code){case 4:return tw(e);case 41:return tw(e);case 42:return ud(e);case 43:return de(e,"base10");case 6:case 273:case 33:case 132:return hd(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ud(e);case 421:return T2(e);case 444:return N2(e);case 445:return O2(e);case 466:return B2(e);case 481:return ud(globalThis.decodeURIComponent(e));default:return de(e,"base16")}}var cd=Object.values(Po).map(r=>r.decoder),C2=function(){let r=cd[0].or(cd[1]);return cd.slice(2).forEach(e=>r=r.or(e)),r}();function tw(r){if(!ul(r))throw new Error("invalid ip address");return sd(r)}function I2(r){let e=ew(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ul(e))throw new Error("invalid ip address");return e}function hd(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function nw(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ud(r){let e=de(r),t=Uint8Array.from(nr(e.length));return it([t,e],t.length+e.length)}function ld(r){let e=zt(r);if(r=r.slice(Re(e)),r.length!==e)throw new Error("inconsistent lengths");return ue(r)}function T2(r){let e;r[0]==="Q"||r[0]==="1"?e=Hn(ke.decode(`z${r}`)).bytes:e=Je.parse(r).multihash.bytes;let t=Uint8Array.from(nr(e.length));return it([t,e],t.length+e.length)}function B2(r){let e=C2.decode(r),t=Uint8Array.from(nr(e.length));return it([t,e],t.length+e.length)}function k2(r){let e=zt(r),t=r.slice(Re(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+ue(t,"base64url")}function P2(r){let e=zt(r),t=r.slice(Re(e));if(t.length!==e)throw new Error("inconsistent lengths");return ue(t,"base58btc")}function N2(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=sn.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hd(n);return it([t,o],t.length+o.length)}function O2(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=sn.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=hd(n);return it([t,o],t.length+o.length)}function rw(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=ue(e,"base32"),o=nw(t);return`${n}:${o}`}function ow(r){r=dd(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=Le(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw new ll("invalid address: "+r);if(a.path===!0){n=dd(o.slice(i).join("/")),e.push([a.code,pd(a.code,n)]),t.push([a.code,n]);break}let c=pd(a.code,o[i]);e.push([a.code,c]),t.push([a.code,fd(a.code,c)])}return{string:iw(t),bytes:fl(e),tuples:e,stringTuples:t,path:n}}function md(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=zt(r,o),s=Re(i),a=Le(i),c=R2(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw new ll("Invalid address Uint8Array: "+ue(r,"base16"));e.push([i,l]);let p=fd(i,l);if(t.push([i,p]),a.path===!0){n=p;break}}return{bytes:Uint8Array.from(r),string:iw(t),tuples:e,stringTuples:t,path:n}}function iw(r){let e=[];return r.map(t=>{let n=Le(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),dd(e.join("/"))}function fl(r){return it(r.map(e=>{let t=Le(e[0]),n=Uint8Array.from(nr(t.code));return e.length>1&&e[1]!=null&&(n=it([n,e[1]])),n}))}function R2(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=zt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Re(t)}}function dd(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var ll=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var L2=Symbol.for("nodejs.util.inspect.custom"),gd=Symbol.for("@multiformats/js-multiaddr/multiaddr"),D2=[Le("dns").code,Le("dns4").code,Le("dns6").code,Le("dnsaddr").code],yd=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},pl=class r{bytes;#e;#t;#r;#n;[gd]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=md(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=ow(e)}else if(aw(e))t=md(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=Le("tcp"),a=Le("udp"),c=Le("ip4"),l=Le("ip6"),p=Le("dns6"),h=Le("ip6zone");for(let[g,x]of this.stringTuples())g===h.code&&(i=`%${x??""}`),D2.includes(g)&&(t=s.name==="tcp"?"tcp":"udp",o=443,n=`${x??""}${i}`,e=g===p.code?6:4),(g===s.code||g===a.code)&&(t=Le(g).name==="tcp"?"tcp":"udp",o=parseInt(x??"")),(g===c.code||g===l.code)&&(t=Le(g).name==="tcp"?"tcp":"udp",n=`${x??""}${i}`,e=g===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},Le(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Le(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(fl(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===ss.p2p.code&&e.push([n,o]),n===ss["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?ue(ke.decode(`z${n}`),"base58btc"):ue(Je.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return Ge(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=sw.get(t.name);if(n==null)throw new yd(`no available resolver for ${t.name}`);return(await n(this,e)).map(i=>Hr(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[L2](){return`Multiaddr(${this.#e})`}};var sw=new Map;function aw(r){return!!r?.[gd]}function Hr(r){return new pl(r)}var U2=r=>r.toString().split("/").slice(1),as=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),xe=r=>({match:e=>as(t=>t===r).match(e),pattern:r}),Ho=()=>({match:r=>as(e=>typeof e=="string").match(r),pattern:"{string}"}),Ua=()=>({match:r=>as(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Te=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ke.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ja=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ko.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Ce=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ct=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Ae=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function je(...r){function e(o){let i=U2(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var j2=Te(),Y4=je(j2),dl=Ae(xe("dns4"),Ho()),ml=Ae(xe("dns6"),Ho()),yl=Ae(xe("dnsaddr"),Ho()),xd=Ae(xe("dns"),Ho()),Z4=je(dl,Ce(Te())),J4=je(ml,Ce(Te())),Q4=je(yl,Ce(Te())),e6=je(Ct(xd,yl,dl,ml),Ce(Te())),cw=Ae(xe("ip4"),as(al)),uw=Ae(xe("ip6"),as(cl)),bd=Ct(cw,uw),mn=Ct(bd,xd,dl,ml,yl),t6=je(Ct(bd,Ae(Ct(xd,yl,dl,ml),Ce(Te())))),r6=je(cw),n6=je(uw),o6=je(bd),vd=Ae(mn,xe("tcp"),Ua()),Ma=Ae(mn,xe("udp"),Ua()),i6=je(Ae(vd,Ce(Te()))),s6=je(Ma),Ad=Ae(Ma,xe("quic"),Ce(Te())),gl=Ae(Ma,xe("quic-v1"),Ce(Te())),M2=Ct(Ad,gl),a6=je(Ad),c6=je(gl),wd=Ct(mn,vd,Ma,Ad,gl),lw=Ct(Ae(wd,xe("ws"),Ce(Te()))),u6=je(lw),fw=Ct(Ae(wd,xe("wss"),Ce(Te())),Ae(wd,xe("tls"),Ce(Ae(xe("sni"),Ho())),xe("ws"),Ce(Te()))),l6=je(fw),pw=Ae(Ma,xe("webrtc-direct"),Ce(ja()),Ce(ja()),Ce(Te())),hw=je(pw),dw=Ae(gl,xe("webtransport"),Ce(ja()),Ce(ja()),Ce(Te())),f6=je(dw),hl=Ct(lw,fw,Ae(vd,Ce(Te())),Ae(M2,Ce(Te())),Ae(mn,Ce(Te())),pw,dw,Te()),mw=je(hl),K2=Ae(hl,xe("p2p-circuit"),Te()),p6=je(K2),H2=Ct(Ae(hl,xe("p2p-circuit"),xe("webrtc"),Ce(Te())),Ae(hl,xe("webrtc"),Ce(Te())),Ae(xe("webrtc"),Ce(Te()))),yw=je(H2),V2=Ct(Ae(mn,xe("tcp"),Ua(),xe("http"),Ce(Te())),Ae(mn,xe("http"),Ce(Te()))),h6=je(V2),$2=Ct(Ae(mn,xe("tcp"),Ct(Ae(xe("443"),xe("http")),Ae(Ua(),xe("https"))),Ce(Te())),Ae(mn,xe("tls"),xe("http"),Ce(Te())),Ae(mn,xe("https"),Ce(Te()))),d6=je($2),F2=Ct(Ae(xe("memory"),Ho(),Ce(Te()))),m6=je(F2);var It;(function(r){let e;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(t||(t={})),function(o){o.codec=()=>Ko(t)}(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Tr((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.flag!=null&&(i.uint32(8),r.Flag.codec().encode(o.flag,i)),o.message!=null&&(i.uint32(18),i.bytes(o.message)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ir(o,r.codec()),r.decode=(o,i)=>Cr(o,r.codec(),i)})(It||(It={}));var gw=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Sd=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),ww="libp2p+webrtc+v1/";var xw=466,bw=2*1024*1024,vw=30*1e3,cs=16*1024;function W2(r=cs){let e=Re(r-Re(r)),t=1+Re(Object.keys(It.Flag).length-1),n=1,o=r-e-t-n,i=Re(o);return e+t+n+i}var Aw=W2(),Sw=5e3,Ew=5e3,_w=3e4,Ed="/webrtc",Ka="/webrtc-signaling/0.0.1",Cw="/libp2p/webrtc-direct/certificate",Iw="webrtc-direct-certificate-private-key";var Tw=12096e5,_d=864e5;var Bw=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},q2=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"}return r}();var G2=function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r}();var z2=function(){function r(e,t,n,o){this.name=e,this.version=t,this.os=n,this.bot=o,this.type="bot-device"}return r}();var X2=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Y2=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Z2=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,J2=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,kw=3,Q2=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Z2]],Pw=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Ow(r){return r?Nw(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Y2:typeof navigator<"u"?Nw(navigator.userAgent):r_()}function e_(r){return r!==""&&Q2.reduce(function(e,t){var n=t[0],o=t[1];if(e)return e;var i=o.exec(r);return!!i&&[n,i]},!1)}function Nw(r){var e=e_(r);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new X2;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<kw&&(o=Bw(Bw([],o,!0),n_(kw-o.length),!0)):o=[];var i=o.join("."),s=t_(r),a=J2.exec(r);return a&&a[1]?new z2(t,i,s,a[1]):new q2(t,i,s)}function t_(r){for(var e=0,t=Pw.length;e<t;e++){var n=Pw[e],o=n[0],i=n[1],s=i.exec(r);if(s)return o}return null}function r_(){var r=typeof process<"u"&&process.version;return r?new G2(process.version.slice(1)):null}function n_(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}function Ee(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Cd=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Id=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rw=r=>globalThis.DOMException===void 0?new Id(r):new DOMException(r),Lw=r=>{let e=r.reason===void 0?Rw("This operation was aborted."):r.reason;return e instanceof Error?e:Rw(e)};function Ha(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((p,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:g}=e;g.aborted&&h(Lw(g)),a=()=>{h(Lw(g))},g.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(p,h);return}let m=new Cd;s=i.setTimeout.call(void 0,()=>{if(n){try{p(n())}catch(g){h(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?p():o instanceof Error?h(o):(m.message=o??`Promise timed out after ${t} milliseconds`,h(m))},t),(async()=>{try{p(await r)}catch(g){h(g)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}var Dw=Ow(),Va=Dw!=null&&Dw.name==="firefox",wl=async function*(){},xl=async r=>{};function Uw(r,e,t=_w,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",e,r.bufferedAmount);let o=Ee(),i=!1;r.bufferedAmountLowThreshold=0;let s=()=>{i||(n.log("%s drain channel closed before drain",e),o.resolve())};r.addEventListener("close",s,{once:!0}),r.addEventListener("bufferedamountlow",()=>{i=!0,r.removeEventListener("close",s),o.resolve()}),await Ha(o.promise,{milliseconds:t})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Td(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??gw.map(e=>({urls:[e]})),r}var jw=(r=32)=>ww+[...Array(r)].map(()=>Sd.at(Math.floor(Math.random()*Sd.length))).join("");var Vo=class{log;peerConnection;remoteAddr;timeline;metrics;source=wl();sink=xl;constructor(e,t){this.log=e.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection;let n=this.peerConnection,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(e){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(e){this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var bl=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},us=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new bl(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new bl(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Bd=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ls(r={}){return o_(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function o_(r,e){e=e??{};let t=e.onEnd,n=new us,o,i,s,a=Ee(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,S)=>{i=T=>{i=null,n.push(T);try{y(r(n))}catch(v){S(v)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ee()})}},l=y=>i!=null?i(y):(n.push(y),o),p=y=>(n=new us,i!=null?i({error:y}):(n.push({error:y}),o)),h=y=>{if(s)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},m=y=>s?o:(s=!0,y!=null?p(y):l({done:!0})),g=()=>(n=new us,m(),{done:!0}),x=y=>(m(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:x,push:h,end:m,get readableLength(){return n.size},onEmpty:async y=>{let S=y?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let T,v;S!=null&&(T=new Promise((L,F)=>{v=()=>{F(new Bd)},S.addEventListener("abort",v)}));try{await Promise.race([a.promise,T])}finally{v!=null&&S!=null&&S?.removeEventListener("abort",v)}}},t==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(y){return w.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return w.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(y){return w.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return w.readableLength},onEmpty:y=>w.onEmpty(y)},o}var vl=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function lt(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new vl(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new vl(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}function Mw(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Kw(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Hw(r,e){let t=Mw(r).return?.();Kw(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var i_=5e3;function kd(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Al=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Ee(),this.closed=Ee(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??i_,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=ls({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Io(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(t);kd(o)&&await o}let n=()=>{Hw(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of e){o=o instanceof Uint8Array?new pe(o):o;let i=this.sendData(o,t);kd(i)&&(this.sendingData=Ee(),await i,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await lt(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await lt(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await lt(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await lt(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();kd(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new _u("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function Pd(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Sl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},El=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},$a=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _l(r){return r[Symbol.asyncIterator]!=null}function Vw(r,e){if(r.byteLength>e)throw new fs("Message length too long")}var Il=r=>{let e=Re(r),t=ot(e);return nr(r,t),Il.bytes=e,t};Il.bytes=0;function Fa(r,e){e=e??{};let t=e.lengthEncoder??Il,n=e?.maxDataLength??4194304;function*o(i){Vw(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return _l(r)?async function*(){for await(let i of r)yield*o(i)}():function*(){for(let i of r)yield*o(i)}()}Fa.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Il,n=e?.maxDataLength??4194304;return Vw(r,n),new pe(t(r.byteLength),r)};var $o;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})($o||($o={}));var Nd=r=>{let e=zt(r);return Nd.bytes=Re(e),e};Nd.bytes=0;function Fo(r,e){let t=new pe,n=$o.LENGTH,o=-1,i=e?.lengthDecoder??Nd,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===$o.LENGTH)try{if(o=i(t),o<0)throw new Sl("Invalid message length");if(o>a)throw new fs("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=$o.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new El("Message length length too long");break}throw l}if(n===$o.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=$o.LENGTH}}}return _l(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new $a("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new $a("Unexpected end of input")}()}Fo.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}}();return Fo(n,{...e??{},onLength:i=>{t=i}})};var Od=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Wa(r,e,t,n){let o=new Od(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){t?.removeEventListener("abort",p),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=h=>{try{if(n?.filter?.(h)===!1)return}catch(m){a(),s(m);return}a(),i(h)},l=h=>{a(),s(h.detail)},p=()=>{a(),s(o)};t?.addEventListener("abort",p),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Rd=class extends Al{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;constructor(e){let t=e.onEnd;switch(e.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await Ha(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(i){this.log.error("error receiving FIN_ACK",i)}}).then(()=>{this.incomingData.end(),this.channel.close(),t?.(o)}).catch(i=>{this.log.error("error ending stream",i)})},super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=ls(),this.bufferedAmountLowEventTimeout=e.bufferedAmountLowEventTimeout??vw,this.maxBufferedAmount=e.maxBufferedAmount??bw,this.maxMessageSize=(e.maxMessageSize??cs)-Aw,this.receiveFinAck=Ee(),this.finAckTimeout=e.closeTimeout??Sw,this.openTimeout=e.openTimeout??Ew,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Io("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(i=>{this.log.error("error closing stream after channel closed",i)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let i=o.error;this.abort(i)},this.channel.onmessage=async o=>{let{data:i}=o;i===null||i.byteLength===0||this.incomingData.push(new Uint8Array(i,0,i.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Fo(this.incomingData)){let i=n.processIncomingProtobuf(o);i!=null&&n.sourcePush(new pe(i))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(e,t=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Io(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=Pd([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Wa(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(t&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=Pd([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Wa(this.channel,"bufferedamountlow",o)}catch(i){throw n.aborted?new Bu(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):i}finally{o.clear()}}try{this.channel.send(e.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(e){for(this.log.trace("-> will send %d bytes",e.byteLength),e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxMessageSize),n=e.subarray(0,t),o=It.encode({message:n}),i=Fa.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(i),this.log.trace("-> sent message %s",this.channel.readyState),e.consume(t)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(It.Flag.RESET)}catch(e){this.log.error("failed to send reset - %e",e)}}async sendCloseWrite(e){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(It.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await lt(this.receiveFinAck.promise,e?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(It.Flag.STOP_SENDING)}processIncomingProtobuf(e){let t=It.decode(e);if(t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===It.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(It.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),t.flag===It.Flag.RESET&&this.reset(),t.flag===It.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===It.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return t.message}async _sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,e.toString()),!1;this.log.trace("sending flag %s",e.toString());let t=It.encode({flag:e}),n=Fa.single(t);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}};function ps(r){let{channel:e,direction:t}=r;return new Rd({id:t==="inbound"?`i${e.id}`:`r${e.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${t}:${e.id}`),...r})}var Qn=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(e,t){this.components=e,this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??Ed,this.dataChannelOptions=t.dataChannelOptions??{},this.log=e.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},i=ps({channel:n,direction:"inbound",onEnd:s=>{o.onEnd(s)},logger:e.logger,...this.dataChannelOptions});o.stream=i,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(s=>s.stream.id!==i.id)},this.bufferedStreams.push(o)}}createStreamMuxer(e){return new Ld(this.components,{...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Ld=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(e,t){this.init=t,this.log=e.logger.forComponent("libp2p:webrtc:muxer"),this.logger=e.logger,this.streams=t.streams.map(n=>n.stream),this.peerConnection=t.peerConnection,this.protocol=t.protocol??Ed,this.metrics=t.metrics,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,i=ps({channel:n,direction:"inbound",onEnd:()=>{this.#e(i,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(i),this.metrics?.increment({incoming_stream:!0}),t?.onIncomingStream?.(i)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#e(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#e(e,t){this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),Uw(t,`${e.direction} ${e.id} ${e.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==e.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(e)}async close(e){try{await Promise.all(this.streams.map(async t=>t.close(e)))}catch(t){this.abort(t)}}abort(e){for(let t of this.streams)t.abort(e)}source=wl();sink=xl;newStream(){let e=this.peerConnection.createDataChannel(""),t=e.id;this.log.trace("opened outgoing datachannel with channel id %s",t);let n=ps({channel:e,direction:"outbound",onEnd:()=>{this.#e(n,e),this.log("outgoing channel %s ended",t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var Tl=globalThis.RTCPeerConnection,Bl=globalThis.RTCSessionDescription,$w=globalThis.RTCIceCandidate;var Dd=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ee(),this.haveNext=Ee()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ee(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ee(),await lt(this.readNext.promise,t?.signal,t)}};function Fw(){return new Dd}var kl=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ww(r,e){let t=Fw();r.sink(t).catch(async s=>{await t.end(s)}),r.sink=async s=>{for await(let a of s)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new pe;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await lt(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await lt(n.next(),s?.signal);if(l===!0)throw new kl("unexpected end of input");o.append(c)}let a=o.sublist(0,s.bytes);return o.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await t.push(s,a):await t.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var Pl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Nl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ol=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function qw(r,e={}){let t=Ww(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Re(e.maxDataLength));let n=e?.lengthDecoder??zt,o=e?.lengthEncoder??nr;return{read:async s=>{let a=-1,c=new pe;for(;;){c.append(await t.read({...s,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Pl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ol("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Nl("message length too long");return t.read({...s,bytes:a})},write:async(s,a)=>{await t.write(new pe(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new pe(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function Rl(r,e){let t=qw(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Yt=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var eo=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},ir=class extends eo{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Ll=class extends eo{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var Dl=class extends eo{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Ul=class extends eo{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Rt;(function(r){let e;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(o){o.codec=()=>Ko(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Tr((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.data!=null&&(i.uint32(18),i.string(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ir(o,r.codec()),r.decode=(o,i)=>Cr(o,r.codec(),i)})(Rt||(Rt={}));var jl=async(r,e,t)=>{try{let n=Ee();for(c_(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal}).catch(()=>{})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Rt.Type.ICE_CANDIDATE)throw new Tu("ICE candidate message expected");let i=JSON.parse(o.data??"null");if(i===""||i===null){t.onProgress?.(new Yt("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let s=new $w(i);t.log.trace("%s received new ICE candidate %o",t.direction,i);try{t.onProgress?.(new Yt("webrtc:add-ice-candidate",s.candidate)),await r.addIceCandidate(s)}catch(a){t.log.error("%s bad candidate received",t.direction,i,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate",t.direction,n),t.signal?.aborted===!0&&Ml(r)!=="connected")throw n}};function Ml(r){return Va?r.iceConnectionState:r.connectionState}function c_(r,e){r[Va?"oniceconnectionstatechange":"onconnectionstatechange"]=t=>{switch(Ml(r)){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new Eu("RTCPeerConnection was closed"));break;default:break}}}async function Gw({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:i,transportManager:s,log:a,logger:c,onProgress:l}){let{baseAddr:p}=zw(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",p);let h=p.getPeerId();if(h==null)throw new ve("Relay peer was missing");let m=i.getConnections(os(h)),g,x=!1;m.length===0?(l?.(new Yt("webrtc:dial-relay")),g=await s.dial(p,{signal:t,onProgress:l}),x=!0):(l?.(new Yt("webrtc:reuse-relay-connection")),g=m[0]);try{l?.(new Yt("webrtc:open-signaling-stream"));let w=await g.newStream(Ka,{signal:t,runOnLimitedConnection:!0}),y=Rl(w).pb(Rt),S=new Tl(r),T=new Qn({logger:c},{peerConnection:S,dataChannelOptions:e});try{let v=S.createDataChannel("init");S.onicecandidate=({candidate:O})=>{let M=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),y.write({type:Rt.Type.ICE_CANDIDATE,data:M},{signal:t}).catch(D=>{a.error("error sending ICE candidate",D)})},S.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let L=await S.createOffer().catch(O=>{throw a.error("could not execute createOffer",O),new ir("Failed to set createOffer")});a.trace("initiator send SDP offer %s",L.sdp),l?.(new Yt("webrtc:send-sdp-offer")),await y.write({type:Rt.Type.SDP_OFFER,data:L.sdp},{signal:t}),await S.setLocalDescription(L).catch(O=>{throw a.error("could not execute setLocalDescription",O),new ir("Failed to set localDescription")}),l?.(new Yt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let F=await y.read({signal:t});if(F.type!==Rt.Type.SDP_ANSWER)throw new ir("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",F.data);let K=new Bl({type:"answer",sdp:F.data});return await S.setRemoteDescription(K).catch(O=>{throw a.error("could not execute setRemoteDescription",O),new ir("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Yt("webrtc:read-ice-candidates")),await jl(S,y,{direction:"initiator",signal:t,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),v.close(),l?.(new Yt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await w.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:S,muxerFactory:T}}catch(v){throw a.error("outgoing signaling error",v),S.close(),w.abort(v),v}finally{S.onicecandidate=null,S.onicecandidateerror=null}}finally{if(x)try{await g.close({signal:t})}catch(w){g.abort(w)}}}var Xw=je(mw.matchers[0],xe("p2p-circuit")),Kl=class r extends Mn{transportManager;shutdownController;events;constructor(e,t){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=t.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>Xw.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>Xw.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Yw({peerConnection:r,stream:e,signal:t,connection:n,log:o}){o.trace("new inbound signaling stream");let i=Rl(e).pb(Rt);try{r.onicecandidate=({candidate:p})=>{let h=JSON.stringify(p?.toJSON()??null);o.trace("recipient sending ICE candidate %s",h),i.write({type:Rt.Type.ICE_CANDIDATE,data:h},{signal:t}).catch(m=>{o.error("error sending ICE candidate",m)})},o.trace("recipient read SDP offer");let a=await i.read({signal:t});if(a.type!==Rt.Type.SDP_OFFER)throw new ir(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Bl({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(p=>{throw o.error("could not execute setRemoteDescription",p),new ir("Failed to set remoteDescription")});let l=await r.createAnswer().catch(p=>{throw o.error("could not execute createAnswer",p),new ir("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await i.write({type:Rt.Type.SDP_ANSWER,data:l.sdp},{signal:t}),await r.setLocalDescription(l).catch(p=>{throw o.error("could not execute setLocalDescription",p),new ir("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await jl(r,i,{direction:"recipient",signal:t,log:o})}catch(a){if(Ml(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let s=Hr(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",s),{remoteAddress:s}}var Hl=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[vu]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Fi]=["@libp2p/transport"];[lg]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Ka,e=>{let t=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,t).catch(n=>{this.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,n)}).finally(()=>{t.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Ka),this._started=!1}createListener(e){return new Kl(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(yw.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:i}=await Gw({rtcConfiguration:await Td(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),s=new Vo(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await t.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:i,onProgress:t.onProgress,signal:t.signal});return this._closeOnShutdown(o,s),a}async _onProtocol({connection:e,stream:t},n){let o=new Tl(await Td(this.init.rtcConfiguration)),i=new Qn(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:s}=await Yw({peerConnection:o,connection:e,stream:t,signal:n,log:this.log});await t.close({signal:n});let a=new Vo(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:s,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:i,signal:n}),this._closeOnShutdown(o,a)}catch(s){throw this.log.error("incoming signaling error",s),o.close(),t.abort(s),s}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function zw(r){let e=r.toString().split("/webrtc/");if(e.length!==2)throw new ve("webrtc protocol was not present in multiaddr");if(!e[0].includes("/p2p-circuit"))throw new ve("p2p-circuit protocol was not present in multiaddr");let t=Hr(e[0]),o=Hr("/"+e[1]).getPeerId();if(o==null)throw new ve("destination peer id was missing");let i=t.protos().pop();if(i===void 0)throw new ve("invalid multiaddr");return i.name!=="p2p"&&(t=t.encapsulate(`/p2p/${o}`)),{baseAddr:t,peerId:os(o)}}var NG=jr(Jw());var Wr={};pt(Wr,{Any:()=>$r,BaseBlock:()=>et,BaseStringBlock:()=>Xa,BitString:()=>Pr,BmpString:()=>Xo,Boolean:()=>qo,CharacterString:()=>oi,Choice:()=>ms,Constructed:()=>at,DATE:()=>tc,DateTime:()=>nc,Duration:()=>oc,EndOfContent:()=>Ya,Enumerated:()=>Go,GeneralString:()=>ni,GeneralizedTime:()=>ii,GraphicString:()=>ri,HexBlock:()=>Fr,IA5String:()=>ti,Integer:()=>bn,Null:()=>Br,NumericString:()=>Zo,ObjectIdentifier:()=>zo,OctetString:()=>kr,Primitive:()=>xn,PrintableString:()=>Jo,RawData:()=>Kd,RelativeObjectIdentifier:()=>ec,Repeated:()=>si,Sequence:()=>Ut,Set:()=>jt,TIME:()=>ic,TeletexString:()=>Qo,TimeOfDay:()=>rc,UTCTime:()=>oo,UniversalString:()=>Yo,Utf8String:()=>ar,ValueBlock:()=>dt,VideotexString:()=>ei,ViewWriter:()=>ds,VisibleString:()=>no,compareSchema:()=>ro,fromBER:()=>An,verifySchema:()=>B_});var me=jr(gn());function Wo(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function to(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let p=a-1;p>=0;p--){let h=Math.pow(2,p*e);l[i-p-1]=Math.floor(o/h),o-=l[i-p-1]*h}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function Fl(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function jd(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Wo(t,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,Wo(i,8)-n}function Qw(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=to(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=to(e,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function ex(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Lt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var FN=Math.log(2);function Wl(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Hd(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function vn(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ds=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Hd(this.items)}},qa=[new Uint8Array([1])],tx="0123456789",Md="name",rx="valueHexView",g_="isHexOnly",w_="idBlock",x_="tagClass",b_="tagNumber",v_="isConstructed",A_="fromBER",S_="toBER",E_="local",Dt="",Nr=new ArrayBuffer(0),af=new Uint8Array(0),za="EndOfContent",ox="OCTET STRING",ix="BIT STRING";function Fr(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?me.BufferSourceConverter.toUint8Array(i.valueHex):af}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vn(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Nr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:me.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var wn=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Dt,warnings:n=[],valueBeforeDecode:o=af}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=me.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:me.Convert.ToHex(this.valueBeforeDecodeView)}}};wn.NAME="baseBlock";var dt=class extends wn{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};dt.NAME="valueBlock";var ql=class extends Fr(wn){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?me.BufferSourceConverter.toUint8Array(e.valueHex):af,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Nr}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=to(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),p=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===p){p+=255;let m=new Uint8Array(p);for(let g=0;g<l.length;g++)m[g]=l[g];l=this.valueHexView=new Uint8Array(p)}}this.blockLength=c+1,l[c-1]=i[c]&127;let h=new Uint8Array(c);for(let m=0;m<c;m++)h[m]=l[m];l=this.valueHexView=new Uint8Array(c),l.set(h),this.blockLength<=9?this.tagNumber=Wo(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ql.NAME="identificationBlock";var Gl=class extends wn{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Wo(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=to(this.length,8);if(o.byteLength>127)return this.error="Too big length",Nr;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Gl.NAME="lengthBlock";var X={},et=class extends wn{constructor({name:e=Dt,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ql(o),this.lenBlock=new Gl(o),this.valueBlock=i?new i(o):new dt(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new ds;t||sx(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?Nr:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():me.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=me.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return ex(t,n)}};et.NAME="BaseBlock";function sx(r){var e;if(r instanceof X.Constructed)for(let t of r.valueBlock.value)sx(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var Xa=class extends et{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Dt,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Xa.NAME="BaseStringBlock";var zl=class extends Fr(dt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};zl.NAME="PrimitiveValueBlock";var ax,xn=class extends et{constructor(e={}){super(e,zl),this.idBlock.isConstructed=!1}};ax=xn;X.Primitive=ax;xn.NAME="PRIMITIVE";function __(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function ys(r,e=0,t=r.length){let n=e,o=new et({},dt),i=new wn;if(!vn(i,r,e,t))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=et;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=X.EndOfContent;break;case 1:c=X.Boolean;break;case 2:c=X.Integer;break;case 3:c=X.BitString;break;case 4:c=X.OctetString;break;case 5:c=X.Null;break;case 6:c=X.ObjectIdentifier;break;case 10:c=X.Enumerated;break;case 12:c=X.Utf8String;break;case 13:c=X.RelativeObjectIdentifier;break;case 14:c=X.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=X.Sequence;break;case 17:c=X.Set;break;case 18:c=X.NumericString;break;case 19:c=X.PrintableString;break;case 20:c=X.TeletexString;break;case 21:c=X.VideotexString;break;case 22:c=X.IA5String;break;case 23:c=X.UTCTime;break;case 24:c=X.GeneralizedTime;break;case 25:c=X.GraphicString;break;case 26:c=X.VisibleString;break;case 27:c=X.GeneralString;break;case 28:c=X.UniversalString;break;case 29:c=X.CharacterString;break;case 30:c=X.BmpString;break;case 31:c=X.DATE;break;case 32:c=X.TimeOfDay;break;case 33:c=X.DateTime;break;case 34:c=X.Duration;break;default:{let l=o.idBlock.isConstructed?new X.Constructed:new X.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?X.Constructed:X.Primitive}return o=__(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function An(r){if(!r.byteLength){let e=new et({},dt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ys(me.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function C_(r,e){return r?1:e}var Vr=class extends dt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let i=t;for(;C_(this.isIndefiniteForm,n)>0;){let s=ys(o,i,n);if(s.offset===-1)return this.error=s.result.error,this.warnings.concat(s.result.warnings),-1;if(i=s.offset,this.blockLength+=s.result.blockLength,n-=s.result.blockLength,this.value.push(s.result),this.isIndefiniteForm&&s.result.constructor.NAME===za)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===za?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new ds;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Nr:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Vr.NAME="ConstructedValueBlock";var cx,at=class extends et{constructor(e={}){super(e,Vr),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
3
+ `).map(o=>` ${o}`).join(`
4
+ `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
+ ${e.join(`
6
+ `)}`:`${t} :`}};cx=at;X.Constructed=cx;at.NAME="CONSTRUCTED";var Xl=class extends dt{fromBER(e,t,n){return t}toBER(e){return Nr}};Xl.override="EndOfContentValueBlock";var ux,Ya=class extends et{constructor(e={}){super(e,Xl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};ux=Ya;X.EndOfContent=ux;Ya.NAME=za;var lx,Br=class extends et{constructor(e={}){super(e,dt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};lx=Br;X.Null=lx;Br.NAME="NULL";var Yl=class extends Fr(dt){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=me.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=me.BufferSourceConverter.toUint8Array(e);return vn(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,jd.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Yl.NAME="BooleanValueBlock";var fx,qo=class extends et{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Yl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};fx=qo;X.Boolean=fx;qo.NAME="BOOLEAN";var Zl=class extends Fr(Vr){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Vr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===za){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==ox)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?Vr.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Zl.NAME="OctetStringValueBlock";var Vd,kr=class extends et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Zl),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=ys(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return at.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=me.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof Vd&&e.push(t.valueBlock.valueHexView);return me.BufferSourceConverter.concat(e)}};Vd=kr;X.OctetString=Vd;kr.NAME=ox;var Jl=class extends Fr(Vr){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=Vr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===za){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==ix)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=ys(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return Vr.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Nr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Jl.NAME="BitStringValueBlock";var px,Pr=class extends et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Jl),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return at.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,i=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${i}`}}};px=Pr;X.BitString=px;Pr.NAME=ix;var hx;function I_(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,p=c<s?s:c,h=0;for(let m=p;m>=0;m--,h++){switch(!0){case h<a.length:l=i[s-h]+a[c-h]+t[0];break;default:l=i[s-h]+t[0]}switch(t[0]=l/10,!0){case h>=i.length:i=Fl(new Uint8Array([l%10]),i);break;default:i[s-h]=l%10}}return t[0]>0&&(i=Fl(t,i)),i}function nx(r){if(r>=qa.length)for(let e=qa.length;e<=r;e++){let t=new Uint8Array([0]),n=qa[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=Fl(t,n)),qa.push(n)}return qa[r]}function T_(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,p=0;for(let h=c;h>=0;h--,p++)switch(l=i[s-p]-a[c-p]-t,!0){case l<0:t=1,i[s-p]=l+10;break;default:t=0,i[s-p]=l}if(t>0)for(let h=s-c+1;h>=0;h--,p++)if(l=i[s-p]-t,l<0)t=1,i[s-p]=l+10;else{t=0,i[s-p]=l;break}return i.slice()}var Za=class extends Fr(dt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=jd.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Qw(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&(s[1]&128)!==0?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=T_(nx(n),t),s="-";break;default:t=I_(t,nx(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=tx.charAt(t[c]));return a===!1&&(s+=tx.charAt(0)),s}};hx=Za;Za.NAME="IntegerValueBlock";Object.defineProperty(hx.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ga,bn=class extends et{constructor(e={}){super(e,Za),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Wl(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Wl();let t=BigInt(e),n=new ds,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(me.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${me.Convert.ToHex(a)}`)+t,p=me.BufferSourceConverter.toUint8Array(me.Convert.FromHex(l.toString(16)));p[0]|=128,n.write(p)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new Ga({valueHex:n.final()})}convertToDER(){let e=new Ga({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ga({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ga=bn;X.Integer=Ga;bn.NAME="INTEGER";var dx,Go=class extends bn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};dx=Go;X.Enumerated=dx;Go.NAME="ENUMERATED";var Ja=class extends Fr(dt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Wo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Wl();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=to(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Nr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=me.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ja.NAME="sidBlock";var Ql=class extends dt{constructor({value:e=Dt,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ja;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Nr;t.push(o)}return Hd(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new Ja;if(o>Number.MAX_SAFE_INTEGER){Wl();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ql.NAME="ObjectIdentifierValueBlock";var mx,zo=class extends et{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ql),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mx=zo;X.ObjectIdentifier=mx;zo.NAME="OBJECT IDENTIFIER";var Qa=class extends Fr(wn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=me.BufferSourceConverter.toUint8Array(e);if(!vn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(i[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Wo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=to(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Nr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=me.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Qa.NAME="relativeSidBlock";var ef=class extends dt{constructor({value:e=Dt,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Qa;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Nr;n.push(i)}return Hd(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Qa;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};ef.NAME="RelativeObjectIdentifierValueBlock";var yx,ec=class extends et{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ef),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};yx=ec;X.RelativeObjectIdentifier=yx;ec.NAME="RelativeObjectIdentifier";var gx,Ut=class extends at{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};gx=Ut;X.Sequence=gx;Ut.NAME="SEQUENCE";var wx,jt=class extends at{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};wx=jt;X.Set=wx;jt.NAME="SET";var tf=class extends Fr(dt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Dt}toJSON(){return{...super.toJSON(),value:this.value}}};tf.NAME="StringValueBlock";var rf=class extends tf{};rf.NAME="SimpleStringValueBlock";var kt=class extends Xa{constructor({...e}={}){super(e,rf)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,me.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};kt.NAME="SIMPLE STRING";var nf=class extends kt{fromBuffer(e){this.valueBlock.valueHexView=me.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=me.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=me.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(me.Convert.FromUtf8String(e)),this.valueBlock.value=e}};nf.NAME="Utf8StringValueBlock";var xx,ar=class extends nf{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};xx=ar;X.Utf8String=xx;ar.NAME="UTF8String";var of=class extends kt{fromBuffer(e){this.valueBlock.value=me.Convert.ToUtf16String(e),this.valueBlock.valueHexView=me.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(me.Convert.FromUtf16String(e))}};of.NAME="BmpStringValueBlock";var bx,Xo=class extends of{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bx=Xo;X.BmpString=bx;Xo.NAME="BMPString";var sf=class extends kt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=to(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};sf.NAME="UniversalStringValueBlock";var vx,Yo=class extends sf{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};vx=Yo;X.UniversalString=vx;Yo.NAME="UniversalString";var Ax,Zo=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Ax=Zo;X.NumericString=Ax;Zo.NAME="NumericString";var Sx,Jo=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Sx=Jo;X.PrintableString=Sx;Jo.NAME="PrintableString";var Ex,Qo=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Ex=Qo;X.TeletexString=Ex;Qo.NAME="TeletexString";var _x,ei=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};_x=ei;X.VideotexString=_x;ei.NAME="VideotexString";var Cx,ti=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Cx=ti;X.IA5String=Cx;ti.NAME="IA5String";var Ix,ri=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ix=ri;X.GraphicString=Ix;ri.NAME="GraphicString";var Tx,no=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Tx=no;X.VisibleString=Tx;no.NAME="VisibleString";var Bx,ni=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Bx=ni;X.GeneralString=Bx;ni.NAME="GeneralString";var kx,oi=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};kx=oi;X.CharacterString=kx;oi.NAME="CharacterString";var Px,oo=class extends no{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,me.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Lt(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Lt(this.month,2),t[2]=Lt(this.day,2),t[3]=Lt(this.hour,2),t[4]=Lt(this.minute,2),t[5]=Lt(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Px=oo;X.UTCTime=Px;oo.NAME="UTCTime";var Nx,ii=class extends oo{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let h=new Number(e[e.length-1]);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let h=1,m=n.indexOf("+"),g="";if(m===-1&&(m=n.indexOf("-"),h=-1),m!==-1){if(g=n.substring(m+1),n=n.substring(0,m),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(g.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=h*x,g.length===4){if(x=parseInt(g.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=h*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let h=new Number(`0${n.substring(l)}`);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");i=h.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let h=60*i;this.minute=Math.floor(h),h=60*(h-this.minute),this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let h=60*i;this.second=Math.floor(h),h=1e3*(h-this.second),this.millisecond=Math.floor(h)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let h=1e3*i;this.millisecond=Math.floor(h)}break;default:throw new Error("Wrong input string for conversion")}let p=s.exec(o);if(p===null)throw new Error("Wrong input string for conversion");for(let h=1;h<p.length;h++)switch(h){case 1:this.year=parseInt(p[h],10);break;case 2:this.month=parseInt(p[h],10);break;case 3:this.day=parseInt(p[h],10);break;case 4:this.hour=parseInt(p[h],10)+a;break;case 5:this.minute=parseInt(p[h],10)+c;break;case 6:this.second=parseInt(p[h],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let h=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=h.getUTCFullYear(),this.month=h.getUTCMonth(),this.day=h.getUTCDay(),this.hour=h.getUTCHours(),this.minute=h.getUTCMinutes(),this.second=h.getUTCSeconds(),this.millisecond=h.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Lt(this.year,4)),t.push(Lt(this.month,2)),t.push(Lt(this.day,2)),t.push(Lt(this.hour,2)),t.push(Lt(this.minute,2)),t.push(Lt(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Lt(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nx=ii;X.GeneralizedTime=Nx;ii.NAME="GeneralizedTime";var Ox,tc=class extends ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ox=tc;X.DATE=Ox;tc.NAME="DATE";var Rx,rc=class extends ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Rx=rc;X.TimeOfDay=Rx;rc.NAME="TimeOfDay";var Lx,nc=class extends ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Lx=nc;X.DateTime=Lx;nc.NAME="DateTime";var Dx,oc=class extends ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Dx=oc;X.Duration=Dx;oc.NAME="Duration";var Ux,ic=class extends ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ux=ic;X.TIME=Ux;ic.NAME="TIME";var $r=class{constructor({name:e=Dt,optional:t=!1}={}){this.name=e,this.optional=t}},ms=class extends $r{constructor({value:e=[],...t}={}){super(t),this.value=e}},si=class extends $r{constructor({value:e=new $r,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Kd=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=me.BufferSourceConverter.toUint8Array(e)}constructor({data:e=af}={}){this.dataView=me.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,n){let o=t+n;return this.dataView=me.BufferSourceConverter.toUint8Array(e).subarray(t,o),o}toBER(e){return this.dataView.slice().buffer}};function ro(r,e,t){if(t instanceof ms){for(let i of t.value)if(ro(r,e,i).verified)return{verified:!0,result:r};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(Md)&&(i.name=t.name),i}}if(t instanceof $r)return t.hasOwnProperty(Md)&&(r[t.name]=e),{verified:!0,result:r};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(w_ in t))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(A_ in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(S_ in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=t.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(t.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(t.idBlock.hasOwnProperty(x_)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(b_)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:r};if(t.idBlock.hasOwnProperty(v_)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:r};if(!(g_ in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:r};if(t.idBlock.isHexOnly){if(!(rx in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=t.idBlock.valueHexView,s=e.idBlock.valueHexView;if(i.length!==s.length)return{verified:!1,result:r};for(let a=0;a<i.length;a++)if(i[a]!==s[1])return{verified:!1,result:r}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&(r[t.name]=e)),t instanceof X.Constructed){let i=0,s={verified:!1,result:{error:"Unknown error"}},a=t.valueBlock.value.length;if(a>0&&t.valueBlock.value[0]instanceof si&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:r};if(e.valueBlock.value.length===0&&t.valueBlock.value.length!==0){let c=!0;for(let l=0;l<t.valueBlock.value.length;l++)c=c&&(t.valueBlock.value[l].optional||!1);return c?{verified:!0,result:r}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&delete r[t.name]),r.error="Inconsistent object length",{verified:!1,result:r})}for(let c=0;c<a;c++)if(c-i>=e.valueBlock.value.length){if(t.valueBlock.value[c].optional===!1){let l={verified:!1,result:r};return r.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&(delete r[t.name],l.name=t.name)),l}}else if(t.valueBlock.value[0]instanceof si){if(s=ro(r,e.valueBlock.value[c],t.valueBlock.value[0].value),s.verified===!1)if(t.valueBlock.value[0].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&delete r[t.name]),s;if(Md in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let l={};E_ in t.valueBlock.value[0]&&t.valueBlock.value[0].local?l=e:l=r,typeof l[t.valueBlock.value[0].name]>"u"&&(l[t.valueBlock.value[0].name]=[]),l[t.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(s=ro(r,e.valueBlock.value[c-i],t.valueBlock.value[c]),s.verified===!1)if(t.valueBlock.value[c].optional)i++;else return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&delete r[t.name]),s;if(s.verified===!1){let c={verified:!1,result:r};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&(delete r[t.name],c.name=t.name)),c}return{verified:!0,result:r}}if(t.primitiveSchema&&rx in e.valueBlock){let i=ys(e.valueBlock.valueHexView);if(i.offset===-1){let s={verified:!1,result:i.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,Dt),t.name&&(delete r[t.name],s.name=t.name)),s}return ro(r,i.result,t.primitiveSchema)}return{verified:!0,result:r}}function B_(r,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let t=ys(me.BufferSourceConverter.toUint8Array(r));return t.offset===-1?{verified:!1,result:t.result}:ro(t.result,t.result,e)}var A;(function(r){r[r.Sequence=0]="Sequence",r[r.Set=1]="Set",r[r.Choice=2]="Choice"})(A||(A={}));var d;(function(r){r[r.Any=1]="Any",r[r.Boolean=2]="Boolean",r[r.OctetString=3]="OctetString",r[r.BitString=4]="BitString",r[r.Integer=5]="Integer",r[r.Enumerated=6]="Enumerated",r[r.ObjectIdentifier=7]="ObjectIdentifier",r[r.Utf8String=8]="Utf8String",r[r.BmpString=9]="BmpString",r[r.UniversalString=10]="UniversalString",r[r.NumericString=11]="NumericString",r[r.PrintableString=12]="PrintableString",r[r.TeletexString=13]="TeletexString",r[r.VideotexString=14]="VideotexString",r[r.IA5String=15]="IA5String",r[r.GraphicString=16]="GraphicString",r[r.VisibleString=17]="VisibleString",r[r.GeneralString=18]="GeneralString",r[r.CharacterString=19]="CharacterString",r[r.UTCTime=20]="UTCTime",r[r.GeneralizedTime=21]="GeneralizedTime",r[r.DATE=22]="DATE",r[r.TimeOfDay=23]="TimeOfDay",r[r.DateTime=24]="DateTime",r[r.Duration=25]="Duration",r[r.TIME=26]="TIME",r[r.Null=27]="Null"})(d||(d={}));var $d=jr(gn()),qr=class{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if(typeof e=="number")this.fromNumber(e);else if($d.BufferSourceConverter.isBufferSource(e))this.unusedBits=t,this.value=$d.BufferSourceConverter.toArrayBuffer(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof Pr))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new Pr({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Pr({name:e})}toNumber(){let e="",t=new Uint8Array(this.value);for(let n of t)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2),n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;let o=new Uint8Array(n);t=t.padStart(n<<3,"0").split("").reverse().join("");let i=0;for(;i<n;)o[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=o.buffer}};var Fd=jr(gn()),oe=class{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Fd.BufferSourceConverter.isBufferSource(e)?this.buffer=Fd.BufferSourceConverter.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof kr))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new kr({valueHex:this.buffer})}toSchema(e){return new kr({name:e})}};var k_={fromASN:r=>r instanceof Br?null:r.valueBeforeDecodeView,toASN:r=>{if(r===null)return new Br;let e=An(r);if(e.result.error)throw new Error(e.result.error);return e.result}},P_={fromASN:r=>r.valueBlock.valueHexView.byteLength>=4?r.valueBlock.toString():r.valueBlock.valueDec,toASN:r=>new bn({value:+r})},N_={fromASN:r=>r.valueBlock.valueDec,toASN:r=>new Go({value:r})},ye={fromASN:r=>r.valueBlock.valueHexView,toASN:r=>new bn({valueHex:r})};var O_={fromASN:r=>r.valueBlock.valueHexView,toASN:r=>new Pr({valueHex:r})},R_={fromASN:r=>r.valueBlock.toString(),toASN:r=>new zo({value:r})},L_={fromASN:r=>r.valueBlock.value,toASN:r=>new qo({value:r})},gs={fromASN:r=>r.valueBlock.valueHexView,toASN:r=>new kr({valueHex:r})},jx={fromASN:r=>new oe(r.getValue()),toASN:r=>r.toASN()};function cr(r){return{fromASN:e=>e.valueBlock.value,toASN:e=>new r({value:e})}}var Wd=cr(ar),D_=cr(Xo),U_=cr(Yo),j_=cr(Zo),M_=cr(Jo),K_=cr(Qo),H_=cr(ei),V_=cr(ti),$_=cr(ri),F_=cr(no),W_=cr(ni),q_=cr(oi),G_={fromASN:r=>r.toDate(),toASN:r=>new oo({valueDate:r})},z_={fromASN:r=>r.toDate(),toASN:r=>new ii({valueDate:r})},X_={fromASN:()=>null,toASN:()=>new Br};function ws(r){switch(r){case d.Any:return k_;case d.BitString:return O_;case d.BmpString:return D_;case d.Boolean:return L_;case d.CharacterString:return q_;case d.Enumerated:return N_;case d.GeneralString:return W_;case d.GeneralizedTime:return z_;case d.GraphicString:return $_;case d.IA5String:return V_;case d.Integer:return P_;case d.Null:return X_;case d.NumericString:return j_;case d.ObjectIdentifier:return R_;case d.OctetString:return gs;case d.PrintableString:return M_;case d.TeletexString:return K_;case d.UTCTime:return G_;case d.UniversalString:return U_;case d.Utf8String:return Wd;case d.VideotexString:return H_;case d.VisibleString:return F_;default:return null}}function ur(r){return typeof r=="function"&&r.prototype?r.prototype.toASN&&r.prototype.fromASN?!0:ur(r.prototype):!!(r&&typeof r=="object"&&"toASN"in r&&"fromASN"in r)}function Gd(r){var e;if(r){let t=Object.getPrototypeOf(r);return((e=t?.prototype)===null||e===void 0?void 0:e.constructor)===Array?!0:Gd(t)}return!1}function Mx(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}var cf=class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){let n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){let t={type:A.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(t,n),t.items=Object.assign({},t.items,n.items)),t}create(e,t){let n=this.items.get(e)||this.createDefault(e),o=[];for(let i in n.items){let s=n.items[i],a=t?i:"",c;if(typeof s.type=="number"){let p=d[s.type],h=Wr[p];if(!h)throw new Error(`Cannot get ASN1 class by name '${p}'`);c=new h({name:a})}else ur(s.type)?c=new s.type().toSchema(a):s.optional?this.get(s.type).type===A.Choice?c=new $r({name:a}):(c=this.create(s.type,!1),c.name=a):c=new $r({name:a});let l=!!s.optional||s.defaultValue!==void 0;if(s.repeated){c.name="";let p=s.repeated==="set"?jt:Ut;c=new p({name:"",value:[new si({name:a,value:c})]})}if(s.context!==null&&s.context!==void 0)if(s.implicit)if(typeof s.type=="number"||ur(s.type)){let p=s.repeated?at:xn;o.push(new p({name:a,optional:l,idBlock:{tagClass:3,tagNumber:s.context}}))}else{this.cache(s.type);let p=!!s.repeated,h=p?c:this.get(s.type,!0).schema;h="valueBlock"in h?h.valueBlock.value:h.value,o.push(new at({name:p?"":a,optional:l,idBlock:{tagClass:3,tagNumber:s.context},value:h}))}else o.push(new at({optional:l,idBlock:{tagClass:3,tagNumber:s.context},value:[c]}));else c.optional=l,o.push(c)}switch(n.type){case A.Sequence:return new Ut({value:o,name:""});case A.Set:return new jt({value:o,name:""});case A.Choice:return new ms({value:o,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}};var Pt=new cf;var C=r=>e=>{let t;Pt.has(e)?t=Pt.get(e):(t=Pt.createDefault(e),Pt.set(e,t)),Object.assign(t,r)};var f=r=>(e,t)=>{let n;Pt.has(e.constructor)?n=Pt.get(e.constructor):(n=Pt.createDefault(e.constructor),Pt.set(e.constructor,n));let o=Object.assign({},r);if(typeof o.type=="number"&&!o.converter){let i=ws(r.type);if(!i)throw new Error(`Cannot get default converter for property '${t}' of ${e.constructor.name}`);o.converter=i}n.items[t]=o};var sc=class extends Error{constructor(){super(...arguments),this.schemas=[]}};var ac=class{static parse(e,t){let n=An(e);if(n.result.error)throw new Error(n.result.error);return this.fromASN(n.result,t)}static fromASN(e,t){var n;try{if(ur(t))return new t().fromASN(e);let o=Pt.get(t);Pt.cache(t);let i=o.schema;if(e.constructor===at&&o.type!==A.Choice){i=new at({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:o.schema.valueBlock.value});for(let c in o.items)delete e[c]}let s=ro({},e,i);if(!s.verified)throw new sc(`Data does not match to ${t.name} ASN1 schema. ${s.result.error}`);let a=new t;if(Gd(t)){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=o.itemType;if(typeof c=="number"){let l=ws(c);if(!l)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,p=>l.fromASN(p))}else return t.from(e.valueBlock.value,l=>this.fromASN(l,c))}for(let c in o.items){let l=s.result[c];if(!l)continue;let p=o.items[c],h=p.type;if(typeof h=="number"||ur(h)){let m=(n=p.converter)!==null&&n!==void 0?n:ur(h)?new h:null;if(!m)throw new Error("Converter is empty");if(p.repeated)if(p.implicit){let g=p.repeated==="sequence"?Ut:jt,x=new g;x.valueBlock=l.valueBlock;let w=An(x.toBER(!1));if(w.offset===-1)throw new Error(`Cannot parse the child item. ${w.result.error}`);if(!("value"in w.result.valueBlock&&Array.isArray(w.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let y=w.result.valueBlock.value;a[c]=Array.from(y,S=>m.fromASN(S))}else a[c]=Array.from(l,g=>m.fromASN(g));else{let g=l;if(p.implicit){let x;if(ur(h))x=new h().toSchema("");else{let w=d[h],y=Wr[w];if(!y)throw new Error(`Cannot get '${w}' class from asn1js module`);x=new y}x.valueBlock=g.valueBlock,g=An(x.toBER(!1)).result}a[c]=m.fromASN(g)}}else if(p.repeated){if(!Array.isArray(l))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");a[c]=Array.from(l,m=>this.fromASN(m,h))}else a[c]=this.fromASN(l,h)}return a}catch(o){throw o instanceof sc&&o.schemas.push(t.name),o}}};var cc=class r{static serialize(e){return e instanceof et?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&ur(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let t=e.constructor,n=Pt.get(t);Pt.cache(t);let o=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){let s=ws(n.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);o=e.map(a=>s.toASN(a))}else o=e.map(s=>this.toAsnItem({type:n.itemType},"[]",t,s))}else for(let s in n.items){let a=n.items[s],c=e[s];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&Mx(this.serialize(a.defaultValue),this.serialize(c)))continue;let l=r.toAsnItem(a,s,t,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||ur(a.type))){let p={};p.valueHex=l instanceof Br?l.valueBeforeDecodeView:l.valueBlock.toBER(),o.push(new xn({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...p}))}else o.push(new at({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:l.valueBlock.value}));else o.push(new at({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[l]}));else a.repeated?o=o.concat(l):o.push(l)}let i;switch(n.type){case A.Sequence:i=new Ut({value:o});break;case A.Set:i=new jt({value:o});break;case A.Choice:if(!o[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);i=o[0];break}return i}static toAsnItem(e,t,n,o){let i;if(typeof e.type=="number"){let s=e.converter;if(!s)throw new Error(`Property '${t}' doesn't have converter for type ${d[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(o,l=>s.toASN(l)),c=e.repeated==="sequence"?Ut:jt;i=new c({value:a})}else i=s.toASN(o)}else if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");let s=Array.from(o,c=>this.toASN(c)),a=e.repeated==="sequence"?Ut:jt;i=new a({value:s})}else i=this.toASN(o);return i}};var re=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let t of e)this.push(t)}}};var zd=jr(gn());var $=class r{static serialize(e){return cc.serialize(e)}static parse(e,t){return ac.parse(e,t)}static toString(e){let t=zd.BufferSourceConverter.isBufferSource(e)?zd.BufferSourceConverter.toArrayBuffer(e):r.serialize(e),n=An(t);if(n.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}};function u(r,e,t,n){var o=arguments.length,i=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(s=r[a])&&(i=(o<3?s(i):o>3?s(e,t,i):s(e,t))||i);return o>3&&i&&Object.defineProperty(e,t,i),i}var Kx=jr(gn()),uc=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(".");if(t.length!==4)throw new Error("Invalid IPv4 address");return t.map(n=>{let o=parseInt(n,10);if(isNaN(o)||o<0||o>255)throw new Error("Invalid IPv4 address part");return o})}static parseIPv6(e){let n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((o,i)=>{let s=parseInt(i,16);if(isNaN(s)||s<0||s>65535)throw new Error("Invalid IPv6 address part");return o.push(s>>8&255),o.push(s&255),o},[])}static expandIPv6(e){if(!e.includes("::"))return e;let t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");let n=t[0]?t[0].split(":"):[],o=t[1]?t[1].split(":"):[],i=8-(n.length+o.length);if(i<0)throw new Error("Invalid IPv6 address");return[...n,...Array(i).fill("0"),...o].join(":")}static formatIPv6(e){let t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){let t=e.split(":"),n=-1,o=0,i=-1,s=0;for(let a=0;a<t.length;a++)t[a]==="0"?(i===-1&&(i=a),s++):(s>o&&(n=i,o=s),i=-1,s=0);if(s>o&&(n=i,o=s),o>1){let a=t.slice(0,n).join(":"),c=t.slice(n+o).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[t,n]=e.split("/"),o=parseInt(n,10);if(this.isIPv4(t)){if(o<0||o>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),o]}else{if(o<0||o>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),o]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let t=parseInt(e.slice(8),16).toString(2).split("").reduce((o,i)=>o+ +i,0),n=e.slice(0,8).replace(/(.{2})/g,o=>`${parseInt(o,16)}.`);return n=n.slice(0,-1),`${n}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(".");if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let n=t.length/2,o=t.slice(0,n),i=t.slice(n);if(t.every(c=>c===0))return t.length===8?"0.0.0.0/0":"::/0";let a=i.reduce((c,l)=>c+(l.toString(2).match(/1/g)||[]).length,0);return t.length===8?`${Array.from(o).join(".")}/${a}`:`${this.formatIPv6(o)}/${a}`}return this.decodeIP(Kx.Convert.ToHex(e))}static fromString(e){if(e.includes("/")){let[n,o]=this.parseCIDR(e),i=new Uint8Array(n.length),s=o;for(let c=0;c<i.length;c++)s>=8?(i[c]=255,s-=8):s>0&&(i[c]=255<<8-s,s=0);let a=new Uint8Array(n.length*2);return a.set(n,0),a.set(i,n.length),a.buffer}let t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}};var Hx=jr(gn()),Xd,Yd,Zd,tt=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};u([f({type:d.TeletexString})],tt.prototype,"teletexString",void 0);u([f({type:d.PrintableString})],tt.prototype,"printableString",void 0);u([f({type:d.UniversalString})],tt.prototype,"universalString",void 0);u([f({type:d.Utf8String})],tt.prototype,"utf8String",void 0);u([f({type:d.BmpString})],tt.prototype,"bmpString",void 0);tt=u([C({type:A.Choice})],tt);var xs=class extends tt{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Hx.Convert.ToHex(this.anyValue):super.toString())}};u([f({type:d.IA5String})],xs.prototype,"ia5String",void 0);u([f({type:d.Any})],xs.prototype,"anyValue",void 0);xs=u([C({type:A.Choice})],xs);var ai=class{constructor(e={}){this.type="",this.value=new xs,Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],ai.prototype,"type",void 0);u([f({type:xs})],ai.prototype,"value",void 0);var io=Xd=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Xd.prototype)}};io=Xd=u([C({type:A.Set,itemType:ai})],io);var Jd=Yd=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Yd.prototype)}};Jd=Yd=u([C({type:A.Sequence,itemType:io})],Jd);var Pe=Zd=class extends Jd{constructor(e){super(e),Object.setPrototypeOf(this,Zd.prototype)}};Pe=Zd=u([C({type:A.Sequence})],Pe);var Y_={fromASN:r=>uc.toString(gs.fromASN(r)),toASN:r=>gs.toASN(uc.fromString(r))},so=class{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],so.prototype,"typeId",void 0);u([f({type:d.Any,context:0})],so.prototype,"value",void 0);var lc=class{constructor(e={}){this.partyName=new tt,Object.assign(this,e)}};u([f({type:tt,optional:!0,context:0,implicit:!0})],lc.prototype,"nameAssigner",void 0);u([f({type:tt,context:1,implicit:!0})],lc.prototype,"partyName",void 0);var ae=class{constructor(e={}){Object.assign(this,e)}};u([f({type:so,context:0,implicit:!0})],ae.prototype,"otherName",void 0);u([f({type:d.IA5String,context:1,implicit:!0})],ae.prototype,"rfc822Name",void 0);u([f({type:d.IA5String,context:2,implicit:!0})],ae.prototype,"dNSName",void 0);u([f({type:d.Any,context:3,implicit:!0})],ae.prototype,"x400Address",void 0);u([f({type:Pe,context:4,implicit:!1})],ae.prototype,"directoryName",void 0);u([f({type:lc,context:5})],ae.prototype,"ediPartyName",void 0);u([f({type:d.IA5String,context:6,implicit:!0})],ae.prototype,"uniformResourceIdentifier",void 0);u([f({type:d.OctetString,context:7,implicit:!0,converter:Y_})],ae.prototype,"iPAddress",void 0);u([f({type:d.ObjectIdentifier,context:8,implicit:!0})],ae.prototype,"registeredID",void 0);ae=u([C({type:A.Choice})],ae);var ao="1.3.6.1.5.5.7",co=`${ao}.1`,Vx=`${ao}.2`,ci=`${ao}.3`,uf=`${ao}.48`,eO=`${Vx}.1`,tO=`${Vx}.2`,Qd=`${uf}.1`,em=`${uf}.2`,tm=`${uf}.3`,rm=`${uf}.5`,fe="2.5.29";var nm,lf=`${co}.1`,Sn=class{constructor(e={}){this.accessMethod="",this.accessLocation=new ae,Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Sn.prototype,"accessMethod",void 0);u([f({type:ae})],Sn.prototype,"accessLocation",void 0);var ui=nm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,nm.prototype)}};ui=nm=u([C({type:A.Sequence,itemType:Sn})],ui);var ff=`${fe}.35`,li=class extends oe{},Gr=class{constructor(e={}){e&&Object.assign(this,e)}};u([f({type:li,context:0,optional:!0,implicit:!0})],Gr.prototype,"keyIdentifier",void 0);u([f({type:ae,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Gr.prototype,"authorityCertIssuer",void 0);u([f({type:d.Integer,context:2,optional:!0,implicit:!0,converter:ye})],Gr.prototype,"authorityCertSerialNumber",void 0);var pf=`${fe}.19`,fi=class{constructor(e={}){this.cA=!1,Object.assign(this,e)}};u([f({type:d.Boolean,defaultValue:!1})],fi.prototype,"cA",void 0);u([f({type:d.Integer,optional:!0})],fi.prototype,"pathLenConstraint",void 0);var om,Ve=om=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,om.prototype)}};Ve=om=u([C({type:A.Sequence,itemType:ae})],Ve);var im,Z_=`${fe}.29`,$x=im=class extends Ve{constructor(e){super(e),Object.setPrototypeOf(this,im.prototype)}};$x=im=u([C({type:A.Sequence})],$x);var sm,df=`${fe}.32`,OO=`${df}.0`,En=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};u([f({type:d.IA5String})],En.prototype,"ia5String",void 0);u([f({type:d.VisibleString})],En.prototype,"visibleString",void 0);u([f({type:d.BmpString})],En.prototype,"bmpString",void 0);u([f({type:d.Utf8String})],En.prototype,"utf8String",void 0);En=u([C({type:A.Choice})],En);var fc=class{constructor(e={}){this.organization=new En,this.noticeNumbers=[],Object.assign(this,e)}};u([f({type:En})],fc.prototype,"organization",void 0);u([f({type:d.Integer,repeated:"sequence"})],fc.prototype,"noticeNumbers",void 0);var pc=class{constructor(e={}){Object.assign(this,e)}};u([f({type:fc,optional:!0})],pc.prototype,"noticeRef",void 0);u([f({type:En,optional:!0})],pc.prototype,"explicitText",void 0);var hf=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.IA5String})],hf.prototype,"cPSuri",void 0);u([f({type:pc})],hf.prototype,"userNotice",void 0);hf=u([C({type:A.Choice})],hf);var hc=class{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],hc.prototype,"policyQualifierId",void 0);u([f({type:d.Any})],hc.prototype,"qualifier",void 0);var pi=class{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],pi.prototype,"policyIdentifier",void 0);u([f({type:hc,repeated:"sequence",optional:!0})],pi.prototype,"policyQualifiers",void 0);var dc=sm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,sm.prototype)}};dc=sm=u([C({type:A.Sequence,itemType:pi})],dc);var HO=`${fe}.20`,mc=class{constructor(e=0){this.value=e}};u([f({type:d.Integer})],mc.prototype,"value",void 0);mc=u([C({type:A.Choice})],mc);var zO=`${fe}.27`,Fx=class extends mc{};Fx=u([C({type:A.Choice})],Fx);var am,mf=`${fe}.31`,Or;(function(r){r[r.unused=1]="unused",r[r.keyCompromise=2]="keyCompromise",r[r.cACompromise=4]="cACompromise",r[r.affiliationChanged=8]="affiliationChanged",r[r.superseded=16]="superseded",r[r.cessationOfOperation=32]="cessationOfOperation",r[r.certificateHold=64]="certificateHold",r[r.privilegeWithdrawn=128]="privilegeWithdrawn",r[r.aACompromise=256]="aACompromise"})(Or||(Or={}));var yc=class extends qr{toJSON(){let e=[],t=this.toNumber();return t&Or.aACompromise&&e.push("aACompromise"),t&Or.affiliationChanged&&e.push("affiliationChanged"),t&Or.cACompromise&&e.push("cACompromise"),t&Or.certificateHold&&e.push("certificateHold"),t&Or.cessationOfOperation&&e.push("cessationOfOperation"),t&Or.keyCompromise&&e.push("keyCompromise"),t&Or.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&Or.superseded&&e.push("superseded"),t&Or.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},_n=class{constructor(e={}){Object.assign(this,e)}};u([f({type:ae,context:0,repeated:"sequence",implicit:!0})],_n.prototype,"fullName",void 0);u([f({type:io,context:1,implicit:!0})],_n.prototype,"nameRelativeToCRLIssuer",void 0);_n=u([C({type:A.Choice})],_n);var zr=class{constructor(e={}){Object.assign(this,e)}};u([f({type:_n,context:0,optional:!0})],zr.prototype,"distributionPoint",void 0);u([f({type:yc,context:1,optional:!0,implicit:!0})],zr.prototype,"reasons",void 0);u([f({type:ae,context:2,optional:!0,repeated:"sequence",implicit:!0})],zr.prototype,"cRLIssuer",void 0);var uo=am=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,am.prototype)}};uo=am=u([C({type:A.Sequence,itemType:zr})],uo);var cm,uR=`${fe}.46`,Wx=cm=class extends uo{constructor(e){super(e),Object.setPrototypeOf(this,cm.prototype)}};Wx=cm=u([C({type:A.Sequence,itemType:zr})],Wx);var gR=`${fe}.28`,Zt=class r{constructor(e={}){this.onlyContainsUserCerts=r.ONLY,this.onlyContainsCACerts=r.ONLY,this.indirectCRL=r.ONLY,this.onlyContainsAttributeCerts=r.ONLY,Object.assign(this,e)}};Zt.ONLY=!1;u([f({type:_n,context:0,optional:!0})],Zt.prototype,"distributionPoint",void 0);u([f({type:d.Boolean,context:1,defaultValue:Zt.ONLY,implicit:!0})],Zt.prototype,"onlyContainsUserCerts",void 0);u([f({type:d.Boolean,context:2,defaultValue:Zt.ONLY,implicit:!0})],Zt.prototype,"onlyContainsCACerts",void 0);u([f({type:yc,context:3,optional:!0,implicit:!0})],Zt.prototype,"onlySomeReasons",void 0);u([f({type:d.Boolean,context:4,defaultValue:Zt.ONLY,implicit:!0})],Zt.prototype,"indirectCRL",void 0);u([f({type:d.Boolean,context:5,defaultValue:Zt.ONLY,implicit:!0})],Zt.prototype,"onlyContainsAttributeCerts",void 0);var qx=`${fe}.21`,gc;(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(gc||(gc={}));var wc=class{constructor(e=gc.unspecified){this.reason=gc.unspecified,this.reason=e}toJSON(){return gc[this.reason]}toString(){return this.toJSON()}};u([f({type:d.Enumerated})],wc.prototype,"reason",void 0);wc=u([C({type:A.Choice})],wc);var um,yf=`${fe}.37`,xc=um=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,um.prototype)}};xc=um=u([C({type:A.Sequence,itemType:d.ObjectIdentifier})],xc);var TR=`${yf}.0`,Gx=`${ci}.1`,zx=`${ci}.2`,Xx=`${ci}.3`,Yx=`${ci}.4`,Zx=`${ci}.8`,Jx=`${ci}.9`;var OR=`${fe}.54`,lm=class{constructor(e=new ArrayBuffer(0)){this.value=e}};u([f({type:d.Integer,converter:ye})],lm.prototype,"value",void 0);lm=u([C({type:A.Choice})],lm);var Qx=`${fe}.24`,bc=class{constructor(e){this.value=new Date,e&&(this.value=e)}};u([f({type:d.GeneralizedTime})],bc.prototype,"value",void 0);bc=u([C({type:A.Choice})],bc);var fm,WR=`${fe}.18`,eb=fm=class extends Ve{constructor(e){super(e),Object.setPrototypeOf(this,fm.prototype)}};eb=fm=u([C({type:A.Sequence})],eb);var gf=`${fe}.15`,Rr;(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(Rr||(Rr={}));var bs=class extends qr{toJSON(){let e=this.toNumber(),t=[];return e&Rr.cRLSign&&t.push("crlSign"),e&Rr.dataEncipherment&&t.push("dataEncipherment"),e&Rr.decipherOnly&&t.push("decipherOnly"),e&Rr.digitalSignature&&t.push("digitalSignature"),e&Rr.encipherOnly&&t.push("encipherOnly"),e&Rr.keyAgreement&&t.push("keyAgreement"),e&Rr.keyCertSign&&t.push("keyCertSign"),e&Rr.keyEncipherment&&t.push("keyEncipherment"),e&Rr.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}};var pm,tL=`${fe}.30`,vs=class{constructor(e={}){this.base=new ae,this.minimum=0,Object.assign(this,e)}};u([f({type:ae})],vs.prototype,"base",void 0);u([f({type:d.Integer,context:0,defaultValue:0,implicit:!0})],vs.prototype,"minimum",void 0);u([f({type:d.Integer,context:1,optional:!0,implicit:!0})],vs.prototype,"maximum",void 0);var wf=pm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,pm.prototype)}};wf=pm=u([C({type:A.Sequence,itemType:vs})],wf);var xf=class{constructor(e={}){Object.assign(this,e)}};u([f({type:wf,context:0,optional:!0,implicit:!0})],xf.prototype,"permittedSubtrees",void 0);u([f({type:wf,context:1,optional:!0,implicit:!0})],xf.prototype,"excludedSubtrees",void 0);var aL=`${fe}.36`,bf=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.Integer,context:0,implicit:!0,optional:!0,converter:ye})],bf.prototype,"requireExplicitPolicy",void 0);u([f({type:d.Integer,context:1,implicit:!0,optional:!0,converter:ye})],bf.prototype,"inhibitPolicyMapping",void 0);var hm,pL=`${fe}.33`,vc=class{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],vc.prototype,"issuerDomainPolicy",void 0);u([f({type:d.ObjectIdentifier})],vc.prototype,"subjectDomainPolicy",void 0);var tb=hm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,hm.prototype)}};tb=hm=u([C({type:A.Sequence,itemType:vc})],tb);var dm,mm=`${fe}.17`,vf=dm=class extends Ve{constructor(e){super(e),Object.setPrototypeOf(this,dm.prototype)}};vf=dm=u([C({type:A.Sequence})],vf);var mt=class{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],mt.prototype,"type",void 0);u([f({type:d.Any,repeated:"set"})],mt.prototype,"values",void 0);var ym,TL=`${fe}.9`,rb=ym=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,ym.prototype)}};rb=ym=u([C({type:A.Sequence,itemType:mt})],rb);var gm=`${fe}.14`,Mt=class extends li{};var UL=`${fe}.16`,Af=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.GeneralizedTime,context:0,implicit:!0,optional:!0})],Af.prototype,"notBefore",void 0);u([f({type:d.GeneralizedTime,context:1,implicit:!0,optional:!0})],Af.prototype,"notAfter",void 0);var Ac;(function(r){r[r.keyUpdateAllowed=1]="keyUpdateAllowed",r[r.newExtensions=2]="newExtensions",r[r.pKIXCertificate=4]="pKIXCertificate"})(Ac||(Ac={}));var Sf=class extends qr{toJSON(){let e=[],t=this.toNumber();return t&Ac.pKIXCertificate&&e.push("pKIXCertificate"),t&Ac.newExtensions&&e.push("newExtensions"),t&Ac.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Ef=class{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Sf,Object.assign(this,e)}};u([f({type:d.GeneralString})],Ef.prototype,"entrustVers",void 0);u([f({type:Sf})],Ef.prototype,"entrustInfoFlags",void 0);var wm,qL=`${co}.11`,nb=wm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,wm.prototype)}};nb=wm=u([C({type:A.Sequence,itemType:Sn})],nb);var ob=jr(gn()),j=class r{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof r&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&ob.isEqual(e.parameters,this.parameters)||e.parameters===this.parameters)}};u([f({type:d.ObjectIdentifier})],j.prototype,"algorithm",void 0);u([f({type:d.Any,optional:!0})],j.prototype,"parameters",void 0);var yt=class{constructor(e={}){this.algorithm=new j,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:j})],yt.prototype,"algorithm",void 0);u([f({type:d.BitString})],yt.prototype,"subjectPublicKey",void 0);var ze=class{constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};u([f({type:d.UTCTime})],ze.prototype,"utcTime",void 0);u([f({type:d.GeneralizedTime})],ze.prototype,"generalTime",void 0);ze=u([C({type:A.Choice})],ze);var Cn=class{constructor(e){this.notBefore=new ze(new Date),this.notAfter=new ze(new Date),e&&(this.notBefore=new ze(e.notBefore),this.notAfter=new ze(e.notAfter))}};u([f({type:ze})],Cn.prototype,"notBefore",void 0);u([f({type:ze})],Cn.prototype,"notAfter",void 0);var xm,gt=class r{constructor(e={}){this.extnID="",this.critical=r.CRITICAL,this.extnValue=new oe,Object.assign(this,e)}};gt.CRITICAL=!1;u([f({type:d.ObjectIdentifier})],gt.prototype,"extnID",void 0);u([f({type:d.Boolean,defaultValue:gt.CRITICAL})],gt.prototype,"critical",void 0);u([f({type:oe})],gt.prototype,"extnValue",void 0);var Jt=xm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,xm.prototype)}};Jt=xm=u([C({type:A.Sequence,itemType:gt})],Jt);var Xr;(function(r){r[r.v1=0]="v1",r[r.v2=1]="v2",r[r.v3=2]="v3"})(Xr||(Xr={}));var wt=class{constructor(e={}){this.version=Xr.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new j,this.issuer=new Pe,this.validity=new Cn,this.subject=new Pe,this.subjectPublicKeyInfo=new yt,Object.assign(this,e)}};u([f({type:d.Integer,context:0,defaultValue:Xr.v1})],wt.prototype,"version",void 0);u([f({type:d.Integer,converter:ye})],wt.prototype,"serialNumber",void 0);u([f({type:j})],wt.prototype,"signature",void 0);u([f({type:Pe})],wt.prototype,"issuer",void 0);u([f({type:Cn})],wt.prototype,"validity",void 0);u([f({type:Pe})],wt.prototype,"subject",void 0);u([f({type:yt})],wt.prototype,"subjectPublicKeyInfo",void 0);u([f({type:d.BitString,context:1,implicit:!0,optional:!0})],wt.prototype,"issuerUniqueID",void 0);u([f({type:d.BitString,context:2,implicit:!0,optional:!0})],wt.prototype,"subjectUniqueID",void 0);u([f({type:Jt,context:3,optional:!0})],wt.prototype,"extensions",void 0);var lr=class{constructor(e={}){this.tbsCertificate=new wt,this.signatureAlgorithm=new j,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:wt})],lr.prototype,"tbsCertificate",void 0);u([f({type:j})],lr.prototype,"signatureAlgorithm",void 0);u([f({type:d.BitString})],lr.prototype,"signatureValue",void 0);var hi=class{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new ze,Object.assign(this,e)}};u([f({type:d.Integer,converter:ye})],hi.prototype,"userCertificate",void 0);u([f({type:ze})],hi.prototype,"revocationDate",void 0);u([f({type:gt,optional:!0,repeated:"sequence"})],hi.prototype,"crlEntryExtensions",void 0);var Qt=class{constructor(e={}){this.signature=new j,this.issuer=new Pe,this.thisUpdate=new ze,Object.assign(this,e)}};u([f({type:d.Integer,optional:!0})],Qt.prototype,"version",void 0);u([f({type:j})],Qt.prototype,"signature",void 0);u([f({type:Pe})],Qt.prototype,"issuer",void 0);u([f({type:ze})],Qt.prototype,"thisUpdate",void 0);u([f({type:ze,optional:!0})],Qt.prototype,"nextUpdate",void 0);u([f({type:hi,repeated:"sequence",optional:!0})],Qt.prototype,"revokedCertificates",void 0);u([f({type:gt,optional:!0,context:0,repeated:"sequence"})],Qt.prototype,"crlExtensions",void 0);var di=class{constructor(e={}){this.tbsCertList=new Qt,this.signatureAlgorithm=new j,this.signature=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:Qt})],di.prototype,"tbsCertList",void 0);u([f({type:j})],di.prototype,"signatureAlgorithm",void 0);u([f({type:d.BitString})],di.prototype,"signature",void 0);var H=jr(gn());var Lr=class{constructor(e={}){this.issuer=new Pe,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:Pe})],Lr.prototype,"issuer",void 0);u([f({type:d.Integer,converter:ye})],Lr.prototype,"serialNumber",void 0);var mi=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Mt,context:0,implicit:!0})],mi.prototype,"subjectKeyIdentifier",void 0);u([f({type:Lr})],mi.prototype,"issuerAndSerialNumber",void 0);mi=u([C({type:A.Choice})],mi);var xt;(function(r){r[r.v0=0]="v0",r[r.v1=1]="v1",r[r.v2=2]="v2",r[r.v3=3]="v3",r[r.v4=4]="v4",r[r.v5=5]="v5"})(xt||(xt={}));var yi=class extends j{};yi=u([C({type:A.Sequence})],yi);var Sc=class extends j{};Sc=u([C({type:A.Sequence})],Sc);var Kt=class extends j{};Kt=u([C({type:A.Sequence})],Kt);var Ec=class extends j{};Ec=u([C({type:A.Sequence})],Ec);var sb=class extends j{};sb=u([C({type:A.Sequence})],sb);var _f=class extends j{};_f=u([C({type:A.Sequence})],_f);var Dr=class{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Dr.prototype,"attrType",void 0);u([f({type:d.Any,repeated:"set"})],Dr.prototype,"attrValues",void 0);var bm,Ht=class{constructor(e={}){this.version=xt.v0,this.sid=new mi,this.digestAlgorithm=new yi,this.signatureAlgorithm=new Sc,this.signature=new oe,Object.assign(this,e)}};u([f({type:d.Integer})],Ht.prototype,"version",void 0);u([f({type:mi})],Ht.prototype,"sid",void 0);u([f({type:yi})],Ht.prototype,"digestAlgorithm",void 0);u([f({type:Dr,repeated:"set",context:0,implicit:!0,optional:!0})],Ht.prototype,"signedAttrs",void 0);u([f({type:Sc})],Ht.prototype,"signatureAlgorithm",void 0);u([f({type:oe})],Ht.prototype,"signature",void 0);u([f({type:Dr,repeated:"set",context:1,implicit:!0,optional:!0})],Ht.prototype,"unsignedAttrs",void 0);var _c=bm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,bm.prototype)}};_c=bm=u([C({type:A.Set,itemType:Ht})],_c);var ab=class extends ze{};ab=u([C({type:A.Choice})],ab);var cb=class extends Ht{};cb=u([C({type:A.Sequence})],cb);var Cc=class{constructor(e={}){this.acIssuer=new ae,this.acSerial=0,this.attrs=[],Object.assign(this,e)}};u([f({type:ae})],Cc.prototype,"acIssuer",void 0);u([f({type:d.Integer})],Cc.prototype,"acSerial",void 0);u([f({type:mt,repeated:"sequence"})],Cc.prototype,"attrs",void 0);var vm,Ic=vm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,vm.prototype)}};Ic=vm=u([C({type:A.Sequence,itemType:d.ObjectIdentifier})],Ic);var As=class{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}};u([f({type:d.Integer,optional:!0})],As.prototype,"pathLenConstraint",void 0);u([f({type:Ic,implicit:!0,context:0,optional:!0})],As.prototype,"permittedAttrs",void 0);u([f({type:Ic,implicit:!0,context:1,optional:!0})],As.prototype,"excludedAttrs",void 0);u([f({type:d.Boolean,defaultValue:!0})],As.prototype,"permitUnSpecified",void 0);var fr=class{constructor(e={}){this.issuer=new Ve,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:Ve})],fr.prototype,"issuer",void 0);u([f({type:d.Integer,converter:ye})],fr.prototype,"serial",void 0);u([f({type:d.BitString,optional:!0})],fr.prototype,"issuerUID",void 0);var Am;(function(r){r[r.publicKey=0]="publicKey",r[r.publicKeyCert=1]="publicKeyCert",r[r.otherObjectTypes=2]="otherObjectTypes"})(Am||(Am={}));var pr=class{constructor(e={}){this.digestedObjectType=Am.publicKey,this.digestAlgorithm=new j,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.Enumerated})],pr.prototype,"digestedObjectType",void 0);u([f({type:d.ObjectIdentifier,optional:!0})],pr.prototype,"otherObjectTypeID",void 0);u([f({type:j})],pr.prototype,"digestAlgorithm",void 0);u([f({type:d.BitString})],pr.prototype,"objectDigest",void 0);var gi=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Ve,optional:!0})],gi.prototype,"issuerName",void 0);u([f({type:fr,context:0,implicit:!0,optional:!0})],gi.prototype,"baseCertificateID",void 0);u([f({type:pr,context:1,implicit:!0,optional:!0})],gi.prototype,"objectDigestInfo",void 0);var wi=class{constructor(e={}){Object.assign(this,e)}};u([f({type:ae,repeated:"sequence"})],wi.prototype,"v1Form",void 0);u([f({type:gi,context:0,implicit:!0})],wi.prototype,"v2Form",void 0);wi=u([C({type:A.Choice})],wi);var xi=class{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}};u([f({type:d.GeneralizedTime})],xi.prototype,"notBeforeTime",void 0);u([f({type:d.GeneralizedTime})],xi.prototype,"notAfterTime",void 0);var lo=class{constructor(e={}){Object.assign(this,e)}};u([f({type:fr,implicit:!0,context:0,optional:!0})],lo.prototype,"baseCertificateID",void 0);u([f({type:Ve,implicit:!0,context:1,optional:!0})],lo.prototype,"entityName",void 0);u([f({type:pr,implicit:!0,context:2,optional:!0})],lo.prototype,"objectDigestInfo",void 0);var Sm;(function(r){r[r.v2=1]="v2"})(Sm||(Sm={}));var Vt=class{constructor(e={}){this.version=Sm.v2,this.holder=new lo,this.issuer=new wi,this.signature=new j,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new xi,this.attributes=[],Object.assign(this,e)}};u([f({type:d.Integer})],Vt.prototype,"version",void 0);u([f({type:lo})],Vt.prototype,"holder",void 0);u([f({type:wi})],Vt.prototype,"issuer",void 0);u([f({type:j})],Vt.prototype,"signature",void 0);u([f({type:d.Integer,converter:ye})],Vt.prototype,"serialNumber",void 0);u([f({type:xi})],Vt.prototype,"attrCertValidityPeriod",void 0);u([f({type:mt,repeated:"sequence"})],Vt.prototype,"attributes",void 0);u([f({type:d.BitString,optional:!0})],Vt.prototype,"issuerUniqueID",void 0);u([f({type:Jt,optional:!0})],Vt.prototype,"extensions",void 0);var bi=class{constructor(e={}){this.acinfo=new Vt,this.signatureAlgorithm=new j,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:Vt})],bi.prototype,"acinfo",void 0);u([f({type:j})],bi.prototype,"signatureAlgorithm",void 0);u([f({type:d.BitString})],bi.prototype,"signatureValue",void 0);var Tc;(function(r){r[r.unmarked=1]="unmarked",r[r.unclassified=2]="unclassified",r[r.restricted=4]="restricted",r[r.confidential=8]="confidential",r[r.secret=16]="secret",r[r.topSecret=32]="topSecret"})(Tc||(Tc={}));var Ss=class extends qr{};var Es=class{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier,implicit:!0,context:0})],Es.prototype,"type",void 0);u([f({type:d.Any,implicit:!0,context:1})],Es.prototype,"value",void 0);var Bc=class{constructor(e={}){this.policyId="",this.classList=new Ss(Tc.unclassified),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Bc.prototype,"policyId",void 0);u([f({type:Ss,defaultValue:new Ss(Tc.unclassified)})],Bc.prototype,"classList",void 0);u([f({type:Es,repeated:"set"})],Bc.prototype,"securityCategories",void 0);var _s=class{constructor(e={}){Object.assign(this,e)}};u([f({type:oe})],_s.prototype,"cotets",void 0);u([f({type:d.ObjectIdentifier})],_s.prototype,"oid",void 0);u([f({type:d.Utf8String})],_s.prototype,"string",void 0);var Cf=class{constructor(e={}){this.values=[],Object.assign(this,e)}};u([f({type:Ve,implicit:!0,context:0,optional:!0})],Cf.prototype,"policyAuthority",void 0);u([f({type:_s,repeated:"sequence"})],Cf.prototype,"values",void 0);var Cj=`${co}.4`,Ij=`${co}.6`,Tj=`${co}.10`,Bj=`${fe}.55`,kc=`${ao}.10`,kj=`${kc}.1`,Pj=`${kc}.2`,Nj=`${kc}.3`,Oj=`${kc}.4`,Rj=`${kc}.6`,Em="2.5.4",Lj=`${Em}.72`;var _m,Cs=class{constructor(e={}){this.targetCertificate=new fr,Object.assign(this,e)}};u([f({type:fr})],Cs.prototype,"targetCertificate",void 0);u([f({type:ae,optional:!0})],Cs.prototype,"targetName",void 0);u([f({type:pr,optional:!0})],Cs.prototype,"certDigestInfo",void 0);var Is=class{constructor(e={}){Object.assign(this,e)}};u([f({type:ae,context:0,implicit:!0})],Is.prototype,"targetName",void 0);u([f({type:ae,context:1,implicit:!0})],Is.prototype,"targetGroup",void 0);u([f({type:Cs,context:2,implicit:!0})],Is.prototype,"targetCert",void 0);Is=u([C({type:A.Choice})],Is);var If=_m=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,_m.prototype)}};If=_m=u([C({type:A.Sequence,itemType:Is})],If);var Cm,ub=Cm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Cm.prototype)}};ub=Cm=u([C({type:A.Sequence,itemType:If})],ub);var Tf=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Ve,implicit:!0,context:0,optional:!0})],Tf.prototype,"roleAuthority",void 0);u([f({type:ae,implicit:!0,context:1})],Tf.prototype,"roleName",void 0);var Pc=class{constructor(e={}){this.service=new ae,this.ident=new ae,Object.assign(this,e)}};u([f({type:ae})],Pc.prototype,"service",void 0);u([f({type:ae})],Pc.prototype,"ident",void 0);u([f({type:oe,optional:!0})],Pc.prototype,"authInfo",void 0);var Im,Nc=class{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Nc.prototype,"otherCertFormat",void 0);u([f({type:d.Any})],Nc.prototype,"otherCert",void 0);var vi=class{constructor(e={}){Object.assign(this,e)}};u([f({type:lr})],vi.prototype,"certificate",void 0);u([f({type:bi,context:2,implicit:!0})],vi.prototype,"v2AttrCert",void 0);u([f({type:Nc,context:3,implicit:!0})],vi.prototype,"other",void 0);vi=u([C({type:A.Choice})],vi);var Ai=Im=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Im.prototype)}};Ai=Im=u([C({type:A.Set,itemType:vi})],Ai);var hr=class{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],hr.prototype,"contentType",void 0);u([f({type:d.Any,context:0})],hr.prototype,"content",void 0);var Ts=class{constructor(e={}){Object.assign(this,e)}};u([f({type:oe})],Ts.prototype,"single",void 0);u([f({type:d.Any})],Ts.prototype,"any",void 0);Ts=u([C({type:A.Choice})],Ts);var Si=class{constructor(e={}){this.eContentType="",Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Si.prototype,"eContentType",void 0);u([f({type:Ts,context:0,optional:!0})],Si.prototype,"eContent",void 0);var Oc=class{constructor(e={}){Object.assign(this,e)}};u([f({type:oe,context:0,implicit:!0,optional:!0})],Oc.prototype,"value",void 0);u([f({type:oe,converter:jx,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Oc.prototype,"constructedValue",void 0);Oc=u([C({type:A.Choice})],Oc);var fo=class{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new Ec,Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],fo.prototype,"contentType",void 0);u([f({type:Ec})],fo.prototype,"contentEncryptionAlgorithm",void 0);u([f({type:Oc,optional:!0})],fo.prototype,"encryptedContent",void 0);var po=class{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],po.prototype,"keyAttrId",void 0);u([f({type:d.Any,optional:!0})],po.prototype,"keyAttr",void 0);var Tm,Bs=class{constructor(e={}){this.subjectKeyIdentifier=new Mt,Object.assign(this,e)}};u([f({type:Mt})],Bs.prototype,"subjectKeyIdentifier",void 0);u([f({type:d.GeneralizedTime,optional:!0})],Bs.prototype,"date",void 0);u([f({type:po,optional:!0})],Bs.prototype,"other",void 0);var ks=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Bs,context:0,implicit:!0,optional:!0})],ks.prototype,"rKeyId",void 0);u([f({type:Lr,optional:!0})],ks.prototype,"issuerAndSerialNumber",void 0);ks=u([C({type:A.Choice})],ks);var Rc=class{constructor(e={}){this.rid=new ks,this.encryptedKey=new oe,Object.assign(this,e)}};u([f({type:ks})],Rc.prototype,"rid",void 0);u([f({type:oe})],Rc.prototype,"encryptedKey",void 0);var Bf=Tm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Tm.prototype)}};Bf=Tm=u([C({type:A.Sequence,itemType:Rc})],Bf);var Lc=class{constructor(e={}){this.algorithm=new j,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:j})],Lc.prototype,"algorithm",void 0);u([f({type:d.BitString})],Lc.prototype,"publicKey",void 0);var Ei=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Mt,context:0,implicit:!0,optional:!0})],Ei.prototype,"subjectKeyIdentifier",void 0);u([f({type:Lc,context:1,implicit:!0,optional:!0})],Ei.prototype,"originatorKey",void 0);u([f({type:Lr,optional:!0})],Ei.prototype,"issuerAndSerialNumber",void 0);Ei=u([C({type:A.Choice})],Ei);var In=class{constructor(e={}){this.version=xt.v3,this.originator=new Ei,this.keyEncryptionAlgorithm=new Kt,this.recipientEncryptedKeys=new Bf,Object.assign(this,e)}};u([f({type:d.Integer})],In.prototype,"version",void 0);u([f({type:Ei,context:0})],In.prototype,"originator",void 0);u([f({type:oe,context:1,optional:!0})],In.prototype,"ukm",void 0);u([f({type:Kt})],In.prototype,"keyEncryptionAlgorithm",void 0);u([f({type:Bf})],In.prototype,"recipientEncryptedKeys",void 0);var Ps=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Mt,context:0,implicit:!0})],Ps.prototype,"subjectKeyIdentifier",void 0);u([f({type:Lr})],Ps.prototype,"issuerAndSerialNumber",void 0);Ps=u([C({type:A.Choice})],Ps);var ho=class{constructor(e={}){this.version=xt.v0,this.rid=new Ps,this.keyEncryptionAlgorithm=new Kt,this.encryptedKey=new oe,Object.assign(this,e)}};u([f({type:d.Integer})],ho.prototype,"version",void 0);u([f({type:Ps})],ho.prototype,"rid",void 0);u([f({type:Kt})],ho.prototype,"keyEncryptionAlgorithm",void 0);u([f({type:oe})],ho.prototype,"encryptedKey",void 0);var _i=class{constructor(e={}){this.keyIdentifier=new oe,Object.assign(this,e)}};u([f({type:oe})],_i.prototype,"keyIdentifier",void 0);u([f({type:d.GeneralizedTime,optional:!0})],_i.prototype,"date",void 0);u([f({type:po,optional:!0})],_i.prototype,"other",void 0);var mo=class{constructor(e={}){this.version=xt.v4,this.kekid=new _i,this.keyEncryptionAlgorithm=new Kt,this.encryptedKey=new oe,Object.assign(this,e)}};u([f({type:d.Integer})],mo.prototype,"version",void 0);u([f({type:_i})],mo.prototype,"kekid",void 0);u([f({type:Kt})],mo.prototype,"keyEncryptionAlgorithm",void 0);u([f({type:oe})],mo.prototype,"encryptedKey",void 0);var yo=class{constructor(e={}){this.version=xt.v0,this.keyEncryptionAlgorithm=new Kt,this.encryptedKey=new oe,Object.assign(this,e)}};u([f({type:d.Integer})],yo.prototype,"version",void 0);u([f({type:_f,context:0,optional:!0})],yo.prototype,"keyDerivationAlgorithm",void 0);u([f({type:Kt})],yo.prototype,"keyEncryptionAlgorithm",void 0);u([f({type:oe})],yo.prototype,"encryptedKey",void 0);var Dc=class{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Dc.prototype,"oriType",void 0);u([f({type:d.Any})],Dc.prototype,"oriValue",void 0);var Tn=class{constructor(e={}){Object.assign(this,e)}};u([f({type:ho,optional:!0})],Tn.prototype,"ktri",void 0);u([f({type:In,context:1,implicit:!0,optional:!0})],Tn.prototype,"kari",void 0);u([f({type:mo,context:2,implicit:!0,optional:!0})],Tn.prototype,"kekri",void 0);u([f({type:yo,context:3,implicit:!0,optional:!0})],Tn.prototype,"pwri",void 0);u([f({type:Dc,context:4,implicit:!0,optional:!0})],Tn.prototype,"ori",void 0);Tn=u([C({type:A.Choice})],Tn);var Bm,Uc=Bm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Bm.prototype)}};Uc=Bm=u([C({type:A.Set,itemType:Tn})],Uc);var km,lb=`${ao}.16`,RK=`${lb}.2`,LK=`${lb}.4`,Ns=class{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Ns.prototype,"otherRevInfoFormat",void 0);u([f({type:d.Any})],Ns.prototype,"otherRevInfo",void 0);var kf=class{constructor(e={}){this.other=new Ns,Object.assign(this,e)}};u([f({type:Ns,context:1,implicit:!0})],kf.prototype,"other",void 0);kf=u([C({type:A.Choice})],kf);var Os=km=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,km.prototype)}};Os=km=u([C({type:A.Set,itemType:kf})],Os);var Rs=class{constructor(e={}){Object.assign(this,e)}};u([f({type:Ai,context:0,implicit:!0,optional:!0})],Rs.prototype,"certs",void 0);u([f({type:Os,context:1,implicit:!0,optional:!0})],Rs.prototype,"crls",void 0);var Pm,Nm=Pm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Pm.prototype)}};Nm=Pm=u([C({type:A.Set,itemType:Dr})],Nm);var Ci=class{constructor(e={}){this.version=xt.v0,this.recipientInfos=new Uc,this.encryptedContentInfo=new fo,Object.assign(this,e)}};u([f({type:d.Integer})],Ci.prototype,"version",void 0);u([f({type:Rs,context:0,implicit:!0,optional:!0})],Ci.prototype,"originatorInfo",void 0);u([f({type:Uc})],Ci.prototype,"recipientInfos",void 0);u([f({type:fo})],Ci.prototype,"encryptedContentInfo",void 0);u([f({type:Nm,context:1,implicit:!0,optional:!0})],Ci.prototype,"unprotectedAttrs",void 0);var fb="1.2.840.113549.1.7.2";var Om,Pf=Om=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Om.prototype)}};Pf=Om=u([C({type:A.Set,itemType:yi})],Pf);var Bn=class{constructor(e={}){this.version=xt.v0,this.digestAlgorithms=new Pf,this.encapContentInfo=new Si,this.signerInfos=new _c,Object.assign(this,e)}};u([f({type:d.Integer})],Bn.prototype,"version",void 0);u([f({type:Pf})],Bn.prototype,"digestAlgorithms",void 0);u([f({type:Si})],Bn.prototype,"encapContentInfo",void 0);u([f({type:Ai,context:0,implicit:!0,optional:!0})],Bn.prototype,"certificates",void 0);u([f({type:Os,context:1,implicit:!0,optional:!0})],Bn.prototype,"crls",void 0);u([f({type:_c})],Bn.prototype,"signerInfos",void 0);var Ii="1.2.840.10045.2.1";var jc="1.2.840.10045.4.1",Nf="1.2.840.10045.4.3.1",Mc="1.2.840.10045.4.3.2",Kc="1.2.840.10045.4.3.3",Hc="1.2.840.10045.4.3.4";var Rm="1.2.840.10045.3.1.7";var Lm="1.3.132.0.34";var Dm="1.3.132.0.35";function Vc(r){return new j({algorithm:r})}var hb=Vc(jc),PH=Vc(Nf),db=Vc(Mc),mb=Vc(Kc),yb=Vc(Hc);var $c=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],$c.prototype,"fieldType",void 0);u([f({type:d.Any})],$c.prototype,"parameters",void 0);$c=u([C({type:A.Sequence})],$c);var Um=class extends oe{};var Ls=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.OctetString})],Ls.prototype,"a",void 0);u([f({type:d.OctetString})],Ls.prototype,"b",void 0);u([f({type:d.BitString,optional:!0})],Ls.prototype,"seed",void 0);Ls=u([C({type:A.Sequence})],Ls);var jm;(function(r){r[r.ecpVer1=1]="ecpVer1"})(jm||(jm={}));var Yr=class{constructor(e={}){this.version=jm.ecpVer1,Object.assign(this,e)}};u([f({type:d.Integer})],Yr.prototype,"version",void 0);u([f({type:$c})],Yr.prototype,"fieldID",void 0);u([f({type:Ls})],Yr.prototype,"curve",void 0);u([f({type:Um})],Yr.prototype,"base",void 0);u([f({type:d.Integer,converter:ye})],Yr.prototype,"order",void 0);u([f({type:d.Integer,optional:!0})],Yr.prototype,"cofactor",void 0);Yr=u([C({type:A.Sequence})],Yr);var Zr=class{constructor(e={}){Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Zr.prototype,"namedCurve",void 0);u([f({type:d.Null})],Zr.prototype,"implicitCurve",void 0);u([f({type:Yr})],Zr.prototype,"specifiedCurve",void 0);Zr=u([C({type:A.Choice})],Zr);var Ds=class{constructor(e={}){this.version=1,this.privateKey=new oe,Object.assign(this,e)}};u([f({type:d.Integer})],Ds.prototype,"version",void 0);u([f({type:oe})],Ds.prototype,"privateKey",void 0);u([f({type:Zr,context:0,optional:!0})],Ds.prototype,"parameters",void 0);u([f({type:d.BitString,context:1,optional:!0})],Ds.prototype,"publicKey",void 0);var Ti=class{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.Integer,converter:ye})],Ti.prototype,"r",void 0);u([f({type:d.Integer,converter:ye})],Ti.prototype,"s",void 0);var $t="1.2.840.113549.1.1",Jr=`${$t}.1`,gb=`${$t}.7`,wb=`${$t}.9`,go=`${$t}.10`,xb=`${$t}.2`,bb=`${$t}.4`,Us=`${$t}.5`,vb=`${$t}.14`;var Of=`${$t}.11`,js=`${$t}.12`,Ms=`${$t}.13`,Mm=`${$t}.15`,Km=`${$t}.16`,Bi="1.3.14.3.2.26",Rf="2.16.840.1.101.3.4.2.4",ki="2.16.840.1.101.3.4.2.1",Pi="2.16.840.1.101.3.4.2.2",Ni="2.16.840.1.101.3.4.2.3",Ab="2.16.840.1.101.3.4.2.5",Sb="2.16.840.1.101.3.4.2.6",Eb="1.2.840.113549.2.2",_b="1.2.840.113549.2.5",wo=`${$t}.8`;function ct(r){return new j({algorithm:r,parameters:null})}var i7=ct(Eb),s7=ct(_b),kn=ct(Bi),a7=ct(Rf),c7=ct(ki),u7=ct(Pi),l7=ct(Ni),f7=ct(Ab),p7=ct(Sb),Lf=new j({algorithm:wo,parameters:$.serialize(kn)}),Hm=new j({algorithm:wb,parameters:$.serialize(gs.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),h7=ct(Jr),d7=ct(xb),m7=ct(bb),y7=ct(Us),g7=ct(Mm),w7=ct(Km),x7=ct(js),b7=ct(Ms),v7=ct(Mm),A7=ct(Km);var Ks=class{constructor(e={}){this.hashAlgorithm=new j(kn),this.maskGenAlgorithm=new j({algorithm:wo,parameters:$.serialize(kn)}),this.pSourceAlgorithm=new j(Hm),Object.assign(this,e)}};u([f({type:j,context:0,defaultValue:kn})],Ks.prototype,"hashAlgorithm",void 0);u([f({type:j,context:1,defaultValue:Lf})],Ks.prototype,"maskGenAlgorithm",void 0);u([f({type:j,context:2,defaultValue:Hm})],Ks.prototype,"pSourceAlgorithm",void 0);var B7=new j({algorithm:gb,parameters:$.serialize(new Ks)});var Qr=class{constructor(e={}){this.hashAlgorithm=new j(kn),this.maskGenAlgorithm=new j({algorithm:wo,parameters:$.serialize(kn)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}};u([f({type:j,context:0,defaultValue:kn})],Qr.prototype,"hashAlgorithm",void 0);u([f({type:j,context:1,defaultValue:Lf})],Qr.prototype,"maskGenAlgorithm",void 0);u([f({type:d.Integer,context:2,defaultValue:20})],Qr.prototype,"saltLength",void 0);u([f({type:d.Integer,context:3,defaultValue:1})],Qr.prototype,"trailerField",void 0);var D7=new j({algorithm:go,parameters:$.serialize(new Qr)});var Oi=class{constructor(e={}){this.digestAlgorithm=new j,this.digest=new oe,Object.assign(this,e)}};u([f({type:j})],Oi.prototype,"digestAlgorithm",void 0);u([f({type:oe})],Oi.prototype,"digest",void 0);var Vm,Hs=class{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.Integer,converter:ye})],Hs.prototype,"prime",void 0);u([f({type:d.Integer,converter:ye})],Hs.prototype,"exponent",void 0);u([f({type:d.Integer,converter:ye})],Hs.prototype,"coefficient",void 0);var Df=Vm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Vm.prototype)}};Df=Vm=u([C({type:A.Sequence,itemType:Hs})],Df);var dr=class{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.Integer})],dr.prototype,"version",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"modulus",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"publicExponent",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"privateExponent",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"prime1",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"prime2",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"exponent1",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"exponent2",void 0);u([f({type:d.Integer,converter:ye})],dr.prototype,"coefficient",void 0);u([f({type:Df,optional:!0})],dr.prototype,"otherPrimeInfos",void 0);var Vs=class{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.Integer,converter:ye})],Vs.prototype,"modulus",void 0);u([f({type:d.Integer,converter:ye})],Vs.prototype,"publicExponent",void 0);var $m;(function(r){r[r.Transient=0]="Transient",r[r.Singleton=1]="Singleton",r[r.ResolutionScoped=2]="ResolutionScoped",r[r.ContainerScoped=3]="ContainerScoped"})($m||($m={}));var bt=$m;var Gb=jr(qb(),1),{__extends:Fs,__assign:hV,__rest:nC,__decorate:dV,__param:mV,__metadata:yV,__awaiter:zb,__generator:Xb,__exportStar:gV,__createBinding:wV,__values:Fc,__read:Wc,__spread:Ur,__spreadArrays:xV,__await:bV,__asyncGenerator:vV,__asyncDelegator:AV,__asyncValues:SV,__makeTemplateObject:EV,__importStar:_V,__importDefault:CV,__classPrivateFieldGet:IV,__classPrivateFieldSet:TV}=Gb.default;var oC="injectionTokens";function Wm(r){var e=Reflect.getMetadata("design:paramtypes",r)||[],t=Reflect.getOwnMetadata(oC,r)||{};return Object.keys(t).forEach(function(n){e[+n]=t[n]}),e}function qc(r){return!!r.useClass}function Ws(r){return!!r.useFactory}var Mf=function(){function r(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return r.prototype.createProxy=function(e){var t=this,n={},o=!1,i,s=function(){return o||(i=e(t.wrap()),o=!0),i};return new Proxy(n,this.createHandler(s))},r.prototype.createHandler=function(e){var t={},n=function(o){t[o]=function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];i[0]=e();var a=Reflect[o];return a.apply(void 0,Ur(i))}};return this.reflectMethods.forEach(n),t},r}();function xo(r){return typeof r=="string"||typeof r=="symbol"}function qm(r){return typeof r=="object"&&"token"in r&&"multiple"in r}function Kf(r){return typeof r=="object"&&"token"in r&&"transform"in r}function Yb(r){return typeof r=="function"||r instanceof Mf}function Ri(r){return!!r.useToken}function Li(r){return r.useValue!=null}function Zb(r){return qc(r)||Li(r)||Ri(r)||Ws(r)}var iC=function(){function r(){this._registryMap=new Map}return r.prototype.entries=function(){return this._registryMap.entries()},r.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},r.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},r.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},r.prototype.setAll=function(e,t){this._registryMap.set(e,t)},r.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},r.prototype.clear=function(){this._registryMap.clear()},r.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},r}(),Gc=iC;var sC=function(r){Fs(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gc),Jb=sC;var aC=function(){function r(){this.scopedResolutions=new Map}return r}(),zc=aC;function cC(r,e){if(r===null)return"at position #"+e;var t=r.split(",")[e].trim();return'"'+t+'" at position #'+e}function uC(r,e,t){return t===void 0&&(t=" "),Ur([r],e.message.split(`
7
+ `).map(function(n){return t+n})).join(`
8
+ `)}function Gm(r,e,t){var n=Wc(r.toString().match(/constructor\(([\w, ]+)\)/)||[],2),o=n[1],i=o===void 0?null:o,s=cC(i,e);return uC("Cannot inject the dependency "+s+' of "'+r.name+'" constructor. Reason:',t)}function Qb(r){if(typeof r.dispose!="function")return!1;var e=r.dispose;return!(e.length>0)}var lC=function(r){Fs(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gc);var fC=function(r){Fs(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Gc);var pC=function(){function r(){this.preResolution=new lC,this.postResolution=new fC}return r}(),ev=pC;var zm=new Map,hC=function(){function r(e){this.parent=e,this._registry=new Jb,this.interceptors=new ev,this.disposed=!1,this.disposables=new Set}return r.prototype.register=function(e,t,n){n===void 0&&(n={lifecycle:bt.Transient}),this.ensureNotDisposed();var o;if(Zb(t)?o=t:o={useClass:t},Ri(o))for(var i=[e],s=o;s!=null;){var a=s.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Ur(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);c&&Ri(c.provider)?s=c.provider:s=null}if((n.lifecycle===bt.Singleton||n.lifecycle==bt.ContainerScoped||n.lifecycle==bt.ResolutionScoped)&&(Li(o)||Ws(o)))throw new Error('Cannot use lifecycle "'+bt[n.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:o,options:n}),this},r.prototype.registerType=function(e,t){return this.ensureNotDisposed(),xo(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},r.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},r.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),xo(e)){if(xo(t))return this.register(e,{useToken:t},{lifecycle:bt.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:bt.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return t&&!xo(t)&&(n=t),this.register(e,{useClass:n},{lifecycle:bt.Singleton})},r.prototype.resolve=function(e,t,n){t===void 0&&(t=new zc),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getRegistration(e);if(!o&&xo(e)){if(n)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),o){var i=this.resolveRegistration(o,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(Yb(e)){var i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},r.prototype.executePreResolutionInterceptor=function(e,t){var n,o;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var s=Fc(this.interceptors.preResolution.getAll(e)),a=s.next();!a.done;a=s.next()){var c=a.value;c.options.frequency!="Once"&&i.push(c),c.callback(e,t)}}catch(l){n={error:l}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,i)}},r.prototype.executePostResolutionInterceptor=function(e,t,n){var o,i;if(this.interceptors.postResolution.has(e)){var s=[];try{for(var a=Fc(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var l=c.value;l.options.frequency!="Once"&&s.push(l),l.callback(e,t,n)}}catch(p){o={error:p}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}this.interceptors.postResolution.setAll(e,s)}},r.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===bt.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var n=e.options.lifecycle===bt.Singleton,o=e.options.lifecycle===bt.ContainerScoped,i=n||o,s;return Li(e.provider)?s=e.provider.useValue:Ri(e.provider)?s=i?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):qc(e.provider)?s=i?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):Ws(e.provider)?s=e.provider.useFactory(this):s=this.construct(e.provider,t),e.options.lifecycle===bt.ResolutionScoped&&t.scopedResolutions.set(e,s),s},r.prototype.resolveAll=function(e,t,n){var o=this;t===void 0&&(t=new zc),n===void 0&&(n=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&xo(e)){if(n)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var s=i.map(function(c){return o.resolveRegistration(c,t)});return this.executePostResolutionInterceptor(e,s,"All"),s}var a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},r.prototype.isRegistered=function(e,t){return t===void 0&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},r.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},r.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var n=Fc(this._registry.entries()),o=n.next();!o.done;o=n.next()){var i=Wc(o.value,2),s=i[0],a=i[1];this._registry.setAll(s,a.filter(function(c){return!Li(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},r.prototype.createChildContainer=function(){var e,t;this.ensureNotDisposed();var n=new r(this);try{for(var o=Fc(this._registry.entries()),i=o.next();!i.done;i=o.next()){var s=Wc(i.value,2),a=s[0],c=s[1];c.some(function(l){var p=l.options;return p.lifecycle===bt.ContainerScoped})&&n._registry.setAll(a,c.map(function(l){return l.options.lifecycle===bt.ContainerScoped?{provider:l.provider,options:l.options}:l}))}}catch(l){e={error:l}}finally{try{i&&!i.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return n},r.prototype.beforeResolution=function(e,t,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:n})},r.prototype.afterResolution=function(e,t,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:n})},r.prototype.dispose=function(){return zb(this,void 0,void 0,function(){var e;return Xb(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(n){var o=n.dispose();o&&e.push(o)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},r.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},r.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},r.prototype.construct=function(e,t){var n=this;if(e instanceof Mf)return e.createProxy(function(i){return n.resolve(i,t)});var o=function(){var i=zm.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var s=i.map(n.resolveParams(t,e));return new(e.bind.apply(e,Ur([void 0],s)))}();return Qb(o)&&this.disposables.add(o),o},r.prototype.resolveParams=function(e,t){var n=this;return function(o,i){var s,a,c;try{return qm(o)?Kf(o)?o.multiple?(s=n.resolve(o.transform)).transform.apply(s,Ur([n.resolveAll(o.token,new zc,o.isOptional)],o.transformArgs)):(a=n.resolve(o.transform)).transform.apply(a,Ur([n.resolve(o.token,e,o.isOptional)],o.transformArgs)):o.multiple?n.resolveAll(o.token,new zc,o.isOptional):n.resolve(o.token,e,o.isOptional):Kf(o)?(c=n.resolve(o.transform,e)).transform.apply(c,Ur([n.resolve(o.token,e)],o.transformArgs)):n.resolve(o,e)}catch(l){throw new Error(Gm(t,i,l))}}},r.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},r}(),$e=new hC;function dC(){return function(r){zm.set(r,Wm(r))}}var bo=dC;if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var Ym,Di=class{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}};u([f({type:d.ObjectIdentifier})],Di.prototype,"attrId",void 0);u([f({type:d.Any,repeated:"set"})],Di.prototype,"attrValues",void 0);var tv=Ym=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Ym.prototype)}};tv=Ym=u([C({type:A.Sequence,itemType:Di})],tv);var Zm,rv=Zm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Zm.prototype)}};rv=Zm=u([C({type:A.Sequence,itemType:hr})],rv);var mC="1.2.840.113549",yC=`${mC}.1`,nv=`${yC}.12`,qs=`${nv}.1`,jF=`${qs}.1`,MF=`${qs}.2`,KF=`${qs}.3`,HF=`${qs}.4`,VF=`${qs}.5`,$F=`${qs}.6`,Ui=`${nv}.10.1`;var qF=`${Ui}.1`,GF=`${Ui}.2`,zF=`${Ui}.3`,XF=`${Ui}.4`,YF=`${Ui}.5`,ZF=`${Ui}.6`,Hf="1.2.840.113549.1.9";var Vf=class{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Vf.prototype,"certId",void 0);u([f({type:d.Any,context:0})],Vf.prototype,"certValue",void 0);var ov=`${Hf}.22`,rW=`${ov}.1`,nW=`${ov}.2`;var $f=class{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],$f.prototype,"crlId",void 0);u([f({type:d.Any,context:0})],$f.prototype,"crltValue",void 0);var gC=`${Hf}.23`,cW=`${gC}.1`;var Ff=class extends oe{},vo=class{constructor(e={}){this.encryptionAlgorithm=new j,this.encryptedData=new Ff,Object.assign(this,e)}};u([f({type:j})],vo.prototype,"encryptionAlgorithm",void 0);u([f({type:Ff})],vo.prototype,"encryptedData",void 0);var Jm,Qm;(function(r){r[r.v1=0]="v1"})(Qm||(Qm={}));var Wf=class extends oe{},ey=Jm=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,Jm.prototype)}};ey=Jm=u([C({type:A.Sequence,itemType:mt})],ey);var Ao=class{constructor(e={}){this.version=Qm.v1,this.privateKeyAlgorithm=new j,this.privateKey=new Wf,Object.assign(this,e)}};u([f({type:d.Integer})],Ao.prototype,"version",void 0);u([f({type:j})],Ao.prototype,"privateKeyAlgorithm",void 0);u([f({type:Wf})],Ao.prototype,"privateKey",void 0);u([f({type:ey,implicit:!0,context:0,optional:!0})],Ao.prototype,"attributes",void 0);var iv=class extends Ao{};iv=u([C({type:A.Sequence})],iv);var sv=class extends vo{};sv=u([C({type:A.Sequence})],sv);var qf=class{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],qf.prototype,"secretTypeId",void 0);u([f({type:d.Any,context:0})],qf.prototype,"secretValue",void 0);var So=class{constructor(e={}){this.mac=new Oi,this.macSalt=new oe,this.iterations=1,Object.assign(this,e)}};u([f({type:Oi})],So.prototype,"mac",void 0);u([f({type:oe})],So.prototype,"macSalt",void 0);u([f({type:d.Integer,defaultValue:1})],So.prototype,"iterations",void 0);var ji=class{constructor(e={}){this.version=3,this.authSafe=new hr,this.macData=new So,Object.assign(this,e)}};u([f({type:d.Integer})],ji.prototype,"version",void 0);u([f({type:hr})],ji.prototype,"authSafe",void 0);u([f({type:So,optional:!0})],ji.prototype,"macData",void 0);var ty,Gs=class{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:d.ObjectIdentifier})],Gs.prototype,"bagId",void 0);u([f({type:d.Any,context:0})],Gs.prototype,"bagValue",void 0);u([f({type:Di,repeated:"set",optional:!0})],Gs.prototype,"bagAttributes",void 0);var av=ty=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,ty.prototype)}};av=ty=u([C({type:A.Sequence,itemType:Gs})],av);var ry,ny,oy,Xe="1.2.840.113549.1.9",lq=`${Xe}.0`,vv=`${Xe}.24`,Yc=`${Xe}.25`,Av=`${Xe}.26`,Sv=`${Xe}.27`,fq=`${vv}.1`,pq=`${vv}.2`,hq=`${Xe}.1`,dq=`${Xe}.2`,mq=`${Xe}.3`,yq=`${Xe}.4`,gq=`${Xe}.5`,wq=`${Xe}.6`,py=`${Xe}.7`,xq=`${Xe}.8`,bq=`${Xe}.9`,vq=`${Xe}.13`,Zc=`${Xe}.14`,Aq=`${Xe}.15`,Sq=`${Xe}.20`,Eq=`${Xe}.21`;var _q=`${Yc}.1`,Cq=`${Yc}.2`,Iq=`${Yc}.3`,Tq=`${Yc}.4`,Bq=`${Yc}.5`,Jc="1.3.6.1.5.5.7.9",kq=`${Jc}.1`,Pq=`${Jc}.2`,Nq=`${Jc}.3`,Oq=`${Jc}.4`,Rq=`${Jc}.5`,Lq=`${Av}.1`,Dq=`${Av}.2`,Uq=`${Sv}.1`,jq=`${Sv}.2`,Mq=`${Xe}.16`,Kq=`${Xe}.22`,Hq=`${Xe}.23`,Vq=`${Em}.65`,Gf=class extends tt{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};u([f({type:d.IA5String})],Gf.prototype,"ia5String",void 0);Gf=u([C({type:A.Choice})],Gf);var cv=class extends hr{};cv=u([C({type:A.Sequence})],cv);var uv=class extends ji{};uv=u([C({type:A.Sequence})],uv);var lv=class extends vo{};lv=u([C({type:A.Sequence})],lv);var iy=class{constructor(e=""){this.value=e}toString(){return this.value}};u([f({type:d.IA5String})],iy.prototype,"value",void 0);iy=u([C({type:A.Choice})],iy);var fv=class extends Gf{};fv=u([C({type:A.Choice})],fv);var pv=class extends tt{};pv=u([C({type:A.Choice})],pv);var sy=class{constructor(e=new Date){this.value=e}};u([f({type:d.GeneralizedTime})],sy.prototype,"value",void 0);sy=u([C({type:A.Choice})],sy);var hv=class extends tt{};hv=u([C({type:A.Choice})],hv);var ay=class{constructor(e="M"){this.value=e}toString(){return this.value}};u([f({type:d.PrintableString})],ay.prototype,"value",void 0);ay=u([C({type:A.Choice})],ay);var zf=class{constructor(e=""){this.value=e}toString(){return this.value}};u([f({type:d.PrintableString})],zf.prototype,"value",void 0);zf=u([C({type:A.Choice})],zf);var dv=class extends zf{};dv=u([C({type:A.Choice})],dv);var mv=class extends tt{};mv=u([C({type:A.Choice})],mv);var cy=class{constructor(e=""){this.value=e}toString(){return this.value}};u([f({type:d.ObjectIdentifier})],cy.prototype,"value",void 0);cy=u([C({type:A.Choice})],cy);var yv=class extends ze{};yv=u([C({type:A.Choice})],yv);var uy=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};u([f({type:d.Integer})],uy.prototype,"value",void 0);uy=u([C({type:A.Choice})],uy);var gv=class extends Ht{};gv=u([C({type:A.Sequence})],gv);var Xc=class extends tt{};Xc=u([C({type:A.Choice})],Xc);var wv=ry=class extends Jt{constructor(e){super(e),Object.setPrototypeOf(this,ry.prototype)}};wv=ry=u([C({type:A.Sequence})],wv);var xv=ny=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,ny.prototype)}};xv=ny=u([C({type:A.Set,itemType:Dr})],xv);var ly=class{constructor(e=""){this.value=e}toString(){return this.value}};u([f({type:d.BmpString})],ly.prototype,"value",void 0);ly=u([C({type:A.Choice})],ly);var fy=class extends j{};fy=u([C({type:A.Sequence})],fy);var bv=oy=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,oy.prototype)}};bv=oy=u([C({type:A.Sequence,itemType:fy})],bv);var hy,Qc=hy=class extends re{constructor(e){super(e),Object.setPrototypeOf(this,hy.prototype)}};Qc=hy=u([C({type:A.Sequence,itemType:mt})],Qc);var en=class{constructor(e={}){this.version=0,this.subject=new Pe,this.subjectPKInfo=new yt,this.attributes=new Qc,Object.assign(this,e)}};u([f({type:d.Integer})],en.prototype,"version",void 0);u([f({type:Pe})],en.prototype,"subject",void 0);u([f({type:yt})],en.prototype,"subjectPKInfo",void 0);u([f({type:Qc,implicit:!0,context:0})],en.prototype,"attributes",void 0);var Eo=class{constructor(e={}){this.certificationRequestInfo=new en,this.signatureAlgorithm=new j,this.signature=new ArrayBuffer(0),Object.assign(this,e)}};u([f({type:en})],Eo.prototype,"certificationRequestInfo",void 0);u([f({type:j})],Eo.prototype,"signatureAlgorithm",void 0);u([f({type:d.BitString})],Eo.prototype,"signature",void 0);var iu="crypto.algorithm",Sy=class{getAlgorithms(){return $e.resolveAll(iu)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let t=new j({algorithm:e.name});if("parameters"in e){let n=e;t.parameters=n.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let n of this.getAlgorithms()){let o=n.toWebAlgorithm(e);if(o)return o}return{name:e.algorithm,parameters:e.parameters}}},Mi="crypto.algorithmProvider";$e.registerSingleton(Mi,Sy);var Jf,qt="1.3.36.3.3.2.8.1.1",Ev=`${qt}.1`,_v=`${qt}.2`,Cv=`${qt}.3`,Iv=`${qt}.4`,Tv=`${qt}.5`,Bv=`${qt}.6`,kv=`${qt}.7`,Pv=`${qt}.8`,Nv=`${qt}.9`,Ov=`${qt}.10`,Rv=`${qt}.11`,Lv=`${qt}.12`,Dv=`${qt}.13`,Uv=`${qt}.14`,jv="brainpoolP160r1",Mv="brainpoolP160t1",Kv="brainpoolP192r1",Hv="brainpoolP192t1",Vv="brainpoolP224r1",$v="brainpoolP224t1",Fv="brainpoolP256r1",Wv="brainpoolP256t1",qv="brainpoolP320r1",Gv="brainpoolP320t1",zv="brainpoolP384r1",Xv="brainpoolP384t1",Yv="brainpoolP512r1",Zv="brainpoolP512t1",Fe="ECDSA",tu=Jf=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Fe.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return hb;case"sha-256":return db;case"sha-384":return mb;case"sha-512":return yb}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Rm;break;case"K-256":t=Jf.SECP256K1;break;case"P-384":t=Lm;break;case"P-521":t=Dm;break;case jv:t=Ev;break;case Mv:t=_v;break;case Kv:t=Cv;break;case Hv:t=Iv;break;case Vv:t=Tv;break;case $v:t=Bv;break;case Fv:t=kv;break;case Wv:t=Pv;break;case qv:t=Nv;break;case Gv:t=Ov;break;case zv:t=Rv;break;case Xv:t=Lv;break;case Yv:t=Dv;break;case Zv:t=Uv;break}if(t)return new j({algorithm:Ii,parameters:$.serialize(new Zr({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case jc:return{name:Fe,hash:{name:"SHA-1"}};case Mc:return{name:Fe,hash:{name:"SHA-256"}};case Kc:return{name:Fe,hash:{name:"SHA-384"}};case Hc:return{name:Fe,hash:{name:"SHA-512"}};case Ii:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch($.parse(e.parameters,Zr).namedCurve){case Rm:return{name:Fe,namedCurve:"P-256"};case Jf.SECP256K1:return{name:Fe,namedCurve:"K-256"};case Lm:return{name:Fe,namedCurve:"P-384"};case Dm:return{name:Fe,namedCurve:"P-521"};case Ev:return{name:Fe,namedCurve:jv};case _v:return{name:Fe,namedCurve:Mv};case Cv:return{name:Fe,namedCurve:Kv};case Iv:return{name:Fe,namedCurve:Hv};case Tv:return{name:Fe,namedCurve:Vv};case Bv:return{name:Fe,namedCurve:$v};case kv:return{name:Fe,namedCurve:Fv};case Pv:return{name:Fe,namedCurve:Wv};case Nv:return{name:Fe,namedCurve:qv};case Ov:return{name:Fe,namedCurve:Gv};case Rv:return{name:Fe,namedCurve:zv};case Lv:return{name:Fe,namedCurve:Xv};case Dv:return{name:Fe,namedCurve:Yv};case Uv:return{name:Fe,namedCurve:Zv}}}}return null}};tu.SECP256K1="1.3.132.0.10";tu=Jf=u([bo()],tu);$e.registerSingleton(iu,tu);var c1=Symbol("name"),u1=Symbol("value"),Se=class{constructor(e,t={},n=""){this[c1]=e,this[u1]=n;for(let o in t)this[o]=t[o]}};Se.NAME=c1;Se.VALUE=u1;var Ey=class{static toTextObject(e){let t=new Se("Algorithm Identifier",{},rn.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Ii:{let n=new tu().toWebAlgorithm(e);n&&"namedCurve"in n?t["Named Curve"]=n.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}},rn=class{static toString(e){let t=this.items[e];return t||e}};rn.items={[Bi]:"sha1",[Rf]:"sha224",[ki]:"sha256",[Pi]:"sha384",[Ni]:"sha512",[Jr]:"rsaEncryption",[Us]:"sha1WithRSAEncryption",[vb]:"sha224WithRSAEncryption",[Of]:"sha256WithRSAEncryption",[js]:"sha384WithRSAEncryption",[Ms]:"sha512WithRSAEncryption",[Ii]:"ecPublicKey",[jc]:"ecdsaWithSHA1",[Nf]:"ecdsaWithSHA224",[Mc]:"ecdsaWithSHA256",[Kc]:"ecdsaWithSHA384",[Hc]:"ecdsaWithSHA512",[Gx]:"TLS WWW server authentication",[zx]:"TLS WWW client authentication",[Xx]:"Code Signing",[Yx]:"E-mail Protection",[Zx]:"Time Stamping",[Jx]:"OCSP Signing",[fb]:"Signed Data"};var Nn=class{static serialize(e){return this.serializeObj(e).join(`
9
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){let n=[],o=this.pad(t++),i="",s=e[Se.VALUE];s&&(i=` ${s}`),n.push(`${o}${e[Se.NAME]}:${i}`),o=this.pad(t);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],l=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${o}${l}${c}`);else if(c instanceof Date)n.push(`${o}${l}${c.toUTCString()}`);else if(Array.isArray(c))for(let p of c)p[Se.NAME]=a,n.push(...this.serializeObj(p,t));else if(c instanceof Se)c[Se.NAME]=a,n.push(...this.serializeObj(c,t));else if(H.BufferSourceConverter.isBufferSource(c))a?(n.push(`${o}${l}`),n.push(...this.serializeBufferSource(c,t+1))):n.push(...this.serializeBufferSource(c,t));else if("toTextObject"in c){let p=c.toTextObject();p[Se.NAME]=a,n.push(...this.serializeObj(p,t))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,t=0){let n=this.pad(t),o=H.BufferSourceConverter.toUint8Array(e),i=[];for(let s=0;s<o.length;){let a=[];for(let c=0;c<16&&s<o.length;c++){c===8&&a.push("");let l=o[s++].toString(16).padStart(2,"0");a.push(l)}i.push(`${n}${a.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};Nn.oidSerializer=rn;Nn.algorithmSerializer=Ey;var _o=class r{constructor(...e){if(e.length===1){let t=e[0];this.rawData=$.serialize(t),this.onInit(t)}else{let t=$.parse(e[0],e[1]);this.rawData=H.BufferSourceConverter.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof r?(0,H.isEqual)(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return $.toString(this.rawData);case"text":return Nn.serialize(this.toTextObject());case"hex":return H.Convert.ToHex(this.rawData);case"base64":return H.Convert.ToBase64(this.rawData);case"base64url":return H.Convert.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Se(this.getTextName(),{},e)}};_o.NAME="ASN";var yr=class r extends _o{constructor(...e){let t;H.BufferSourceConverter.isBufferSource(e[0])?t=H.BufferSourceConverter.toArrayBuffer(e[0]):t=$.serialize(new gt({extnID:e[0],critical:e[1],extnValue:new oe(H.BufferSourceConverter.toArrayBuffer(e[2]))})),super(t,gt)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Se.NAME]===r.NAME&&(e[Se.NAME]=rn.toString(this.type)),e}},l1,ru=class r{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[l1]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(r.DEFAULT,crypto):typeof globalThis<"u"&&globalThis.crypto&&globalThis.crypto.subtle&&this.set(r.DEFAULT,globalThis.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=r.DEFAULT){let t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if(typeof e=="string"){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(r.DEFAULT,e);return this}};l1=Symbol.toStringTag;ru.DEFAULT="default";var vt=new ru,vC=/^[0-2](?:\.[1-9][0-9]*)+$/;function AC(r){return new RegExp(vC).test(r)}var ep=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return AC(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}},Ft=new ep;Ft.register("CN","2.5.4.3");Ft.register("L","2.5.4.7");Ft.register("ST","2.5.4.8");Ft.register("O","2.5.4.10");Ft.register("OU","2.5.4.11");Ft.register("C","2.5.4.6");Ft.register("DC","0.9.2342.19200300.100.1.25");Ft.register("E","1.2.840.113549.1.9.1");Ft.register("G","2.5.4.42");Ft.register("I","2.5.4.43");Ft.register("SN","2.5.4.4");Ft.register("T","2.5.4.12");function SC(r,e){return`\\${H.Convert.ToHex(H.Convert.FromUtf8String(e)).toUpperCase()}`}function EC(r){return r.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,SC)}var mr=class r{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new ep,this.asn=new Pe;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let o=t[n];this.extraNames.register(n,o)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Pe?this.asn=e:H.BufferSourceConverter.isBufferSource(e)?this.asn=$.parse(e,Pe):this.asn=this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Ft.findId(e),n=[];for(let o of this.asn)for(let i of o)i.type===t&&n.push(i.value.toString());return n}getName(e){return this.extraNames.get(e)||Ft.get(e)}toString(){return this.asn.map(e=>e.map(t=>{let n=this.getName(t.type)||t.type,o=t.value.anyValue?`#${H.Convert.ToHex(t.value.anyValue)}`:EC(t.value.toString());return`${n}=${o}`}).join("+")).join(", ")}toJSON(){var e;let t=[];for(let n of this.asn){let o={};for(let i of n){let s=this.getName(i.type)||i.type;(e=o[s])!==null&&e!==void 0||(o[s]=[]),o[s].push(i.value.anyValue?`#${H.Convert.ToHex(i.value.anyValue)}`:i.value.toString())}t.push(o)}return t}fromString(e){let t=new Pe,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,o=null,i=",";for(;o=n.exec(`${e},`);){let[,s,a]=o,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),o[3]=c);let l=o[3];s=this.getTypeOid(s);let p=this.createAttribute(s,a);i==="+"?t[t.length-1].push(p):t.push(new io([p])),i=l}return t}fromJSON(e){let t=new Pe;for(let n of e){let o=new io;for(let i in n){let s=this.getTypeOid(i),a=n[i];for(let c of a){let l=this.createAttribute(s,c);o.push(l)}}t.push(o)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){let n=new ai({type:e});if(typeof t=="object")for(let o in t)switch(o){case"ia5String":n.value.ia5String=t[o];break;case"utf8String":n.value.utf8String=t[o];break;case"universalString":n.value.universalString=t[o];break;case"bmpString":n.value.bmpString=t[o];break;case"printableString":n.value.printableString=t[o];break}else if(t[0]==="#")n.value.anyValue=H.Convert.FromHex(t.slice(1));else{let o=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=o:r.isPrintableString(o)?n.value.printableString=o:n.value.utf8String=o}return n}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/ig,`
10
+ `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return $.serialize(this.asn)}async getThumbprint(...e){var t;let n,o="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(o=e[0]||o,n=e[1]||vt.get()):n=e[0]||vt.get(),await n.subtle.digest(o,this.toArrayBuffer())}},f1="Cannot initialize GeneralName from ASN.1 data.",Jv=`${f1} Unsupported string format in use.`,_C=`${f1} Value doesn't match to GUID regular expression.`,Qv=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,e1="1.3.6.1.4.1.311.25.1",t1="1.3.6.1.4.1.311.20.2.3",dy="dns",my="dn",yy="email",gy="ip",wy="url",xy="guid",by="upn",Xf="id",tn=class extends _o{constructor(...e){let t;if(e.length===2)switch(e[0]){case my:{let n=new mr(e[1]).toArrayBuffer(),o=$.parse(n,Pe);t=new ae({directoryName:o});break}case dy:t=new ae({dNSName:e[1]});break;case yy:t=new ae({rfc822Name:e[1]});break;case xy:{let n=new RegExp(Qv,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let o=n.slice(1).map((i,s)=>s<3?H.Convert.ToHex(new Uint8Array(H.Convert.FromHex(i)).reverse()):i).join("");t=new ae({otherName:new so({typeId:e1,value:$.serialize(new oe(H.Convert.FromHex(o)))})});break}case gy:t=new ae({iPAddress:e[1]});break;case Xf:t=new ae({registeredID:e[1]});break;case by:{t=new ae({otherName:new so({typeId:t1,value:$.serialize(Wd.toASN(e[1]))})});break}case wy:t=new ae({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else H.BufferSourceConverter.isBufferSource(e[0])?t=$.parse(e[0],ae):t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=dy,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=yy,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=gy,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=wy,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Xf,this.value=e.registeredID;else if(e.directoryName!=null)this.type=my,this.value=new mr(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===e1){this.type=xy;let t=$.parse(e.otherName.value,oe),n=new RegExp(Qv,"i").exec(H.Convert.ToHex(t));if(!n)throw new Error(_C);this.value=n.slice(1).map((o,i)=>i<3?H.Convert.ToHex(new Uint8Array(H.Convert.FromHex(o)).reverse()):o).join("-")}else if(e.otherName.typeId===t1)this.type=by,this.value=$.parse(e.otherName.value,tt).toString();else throw new Error(Jv);else throw new Error(Jv)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case my:case dy:case xy:case gy:case Xf:case by:case wy:e=this.type.toUpperCase();break;case yy:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===Xf&&(t=rn.toString(t)),new Se(e,void 0,t)}},Ki=class extends _o{constructor(e){let t;if(e instanceof Ve)t=e;else if(Array.isArray(e)){let n=[];for(let o of e)if(o instanceof ae)n.push(o);else{let i=$.parse(new tn(o.type,o.value).rawData,ae);n.push(i)}t=new Ve(n)}else if(H.BufferSourceConverter.isBufferSource(e))t=$.parse(e,Ve);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(t)}onInit(e){let t=[];for(let n of e){let o=null;try{o=new tn(n)}catch{continue}t.push(o)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let n=t.toTextObject(),o=e[n[Se.NAME]];Array.isArray(o)||(o=[],e[n[Se.NAME]]=o),o.push(n)}return e}};Ki.NAME="GeneralNames";var eu="-{5}",nu="\\n",CC=`[^${nu}]+`,IC=`${eu}BEGIN (${CC}(?=${eu}))${eu}`,TC=`${eu}END \\1${eu}`,zs="\\n",BC=`[^:${nu}]+`,kC=`(?:[^${nu}]+${zs}(?: +[^${nu}]+${zs})*)`,PC="[a-zA-Z0-9=+/]+",NC=`(?:${PC}${zs})+`,r1=`${IC}${zs}(?:((?:${BC}: ${kC})+))?${zs}?(${NC})${TC}`,Nt=class{static isPem(e){return typeof e=="string"&&new RegExp(r1,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(r1,"g"),n=[],o=null;for(;o=t.exec(e);){let i=o[3].replace(new RegExp(`[${nu}]+`,"g"),""),s={type:o[1],headers:[],rawData:H.Convert.FromBase64(i)},a=o[2];if(a){let c=a.split(new RegExp(zs,"g")),l=null;for(let p of c){let[h,m]=p.split(/:(.*)/);if(m===void 0){if(!l)throw new Error("Cannot parse PEM string. Incorrect header value");l.value+=h.trim()}else l&&s.headers.push(l),l={key:h,value:m.trim()}}l&&s.headers.push(l)}n.push(s)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){let n=new Array;return t?e.forEach(o=>{if(!H.BufferSourceConverter.isBufferSource(o))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:t,rawData:H.BufferSourceConverter.toArrayBuffer(o)}))}):e.forEach(o=>{if(!("type"in o))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(o))}),n.join(`
11
+ `)}else{if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:H.BufferSourceConverter.toArrayBuffer(e)})}}static encodeStruct(e){var t;let n=e.type.toLocaleUpperCase(),o=[];if(o.push(`-----BEGIN ${n}-----`),!((t=e.headers)===null||t===void 0)&&t.length){for(let l of e.headers)o.push(`${l.key}: ${l.value}`);o.push("")}let i=H.Convert.ToBase64(e.rawData),s,a=0,c=Array();for(;a<i.length&&(i.length-a<64?s=i.substring(a):(s=i.substring(a,a+64),a+=64),s.length!==0);)if(c.push(s),s.length<64)break;return o.push(...c),o.push(`-----END ${n}-----`),o.join(`
12
+ `)}};Nt.CertificateTag="CERTIFICATE";Nt.CrlTag="CRL";Nt.CertificateRequestTag="CERTIFICATE REQUEST";Nt.PublicKeyTag="PUBLIC KEY";Nt.PrivateKeyTag="PRIVATE KEY";var Co=class r extends _o{static isAsnEncoded(e){return H.BufferSourceConverter.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(Nt.isPem(e))return Nt.decode(e)[0];if(H.Convert.isHex(e))return H.Convert.FromHex(e);if(H.Convert.isBase64(e))return H.Convert.FromBase64(e);if(H.Convert.isBase64Url(e))return H.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let t=H.Convert.ToBinary(e);return Nt.isPem(t)?Nt.decode(t)[0]:H.Convert.isHex(t)?H.Convert.FromHex(t):H.Convert.isBase64(t)?H.Convert.FromBase64(t):H.Convert.isBase64Url(t)?H.Convert.FromBase64Url(t):H.BufferSourceConverter.toArrayBuffer(e)}}constructor(...e){r.isAsnEncoded(e[0])?super(r.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){switch(e){case"pem":return Nt.encode(this.rawData,this.tag);default:return super.toString(e)}}},Pn=class r extends Co{static async create(e,t=vt.get()){if(e instanceof r)return e;if(ru.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let n=await t.subtle.exportKey("spki",e);return new r(n)}else{if(e.publicKey)return e.publicKey;if(H.BufferSourceConverter.isBufferSource(e))return new r(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Co.isAsnEncoded(e)?super(e,yt):super(e),this.tag=Nt.PublicKeyTag}async export(...e){let t,n=["verify"],o={hash:"SHA-256",...this.algorithm};e.length>1?(o=e[0]||o,n=e[1]||n,t=e[2]||vt.get()):t=e[0]||vt.get();let i=this.rawData,s=$.parse(this.rawData,yt);return s.algorithm.algorithm===go&&(i=OC(s,i)),t.subtle.importKey("spki",i,o,!0,n)}onInit(e){let t=$e.resolve(Mi),n=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Jr:{let o=$.parse(e.subjectPublicKey,Vs),i=H.BufferSourceConverter.toUint8Array(o.modulus);n.publicExponent=H.BufferSourceConverter.toUint8Array(o.publicExponent),n.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let n,o="SHA-1";return e.length>=1&&!(!((t=e[0])===null||t===void 0)&&t.subtle)?(o=e[0]||o,n=e[1]||vt.get()):n=e[0]||vt.get(),await n.subtle.digest(o,this.rawData)}async getKeyIdentifier(...e){let t,n="SHA-1";e.length===1?typeof e[0]=="string"?(n=e[0],t=vt.get()):t=e[0]:e.length===2?(n=e[0],t=e[1]):t=vt.get();let o=$.parse(this.rawData,yt);return await t.subtle.digest(n,o.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=$.parse(this.rawData,yt);switch(e.Algorithm=Nn.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Ii:e["EC Point"]=t.subjectPublicKey;break;case Jr:default:e["Raw Data"]=t.subjectPublicKey}return e}};function OC(r,e){return r.algorithm=new j({algorithm:Jr,parameters:null}),e=$.serialize(r),e}var tp=class r extends yr{static async create(e,t=!1,n=vt.get()){if("name"in e&&"serialNumber"in e)return new r(e,t);let i=await(await Pn.create(e,n)).getKeyIdentifier(n);return new r(H.Convert.ToHex(i),t)}constructor(...e){if(H.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let t=new Gr({keyIdentifier:new li(H.Convert.FromHex(e[0]))});super(ff,e[1],$.serialize(t))}else{let t=e[0],n=t.name instanceof Ki?$.parse(t.name.rawData,Ve):t.name,o=new Gr({authorityCertIssuer:n,authorityCertSerialNumber:H.Convert.FromHex(t.serialNumber)});super(ff,e[1],$.serialize(o))}}onInit(e){super.onInit(e);let t=$.parse(e.extnValue,Gr);t.keyIdentifier&&(this.keyId=H.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?H.Convert.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=$.parse(this.value,Gr);return t.authorityCertIssuer&&(e["Authority Issuer"]=new Ki(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}};tp.NAME="Authority Key Identifier";var Xs=class extends yr{constructor(...e){if(H.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=$.parse(this.value,fi);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new fi({cA:e[0],pathLenConstraint:e[1]});super(pf,e[2],$.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};Xs.NAME="Basic Constraints";var n1;(function(r){r.serverAuth="1.3.6.1.5.5.7.3.1",r.clientAuth="1.3.6.1.5.5.7.3.2",r.codeSigning="1.3.6.1.5.5.7.3.3",r.emailProtection="1.3.6.1.5.5.7.3.4",r.timeStamping="1.3.6.1.5.5.7.3.8",r.ocspSigning="1.3.6.1.5.5.7.3.9"})(n1||(n1={}));var rp=class extends yr{constructor(...e){if(H.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=$.parse(this.value,xc);this.usages=t.map(n=>n)}else{let t=new xc(e[0]);super(yf,e[1],$.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(t=>rn.toString(t)).join(", "),e}};rp.NAME="Extended Key Usages";var o1;(function(r){r[r.digitalSignature=1]="digitalSignature",r[r.nonRepudiation=2]="nonRepudiation",r[r.keyEncipherment=4]="keyEncipherment",r[r.dataEncipherment=8]="dataEncipherment",r[r.keyAgreement=16]="keyAgreement",r[r.keyCertSign=32]="keyCertSign",r[r.cRLSign=64]="cRLSign",r[r.encipherOnly=128]="encipherOnly",r[r.decipherOnly=256]="decipherOnly"})(o1||(o1={}));var np=class extends yr{constructor(...e){if(H.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=$.parse(this.value,bs);this.usages=t.toNumber()}else{let t=new bs(e[0]);super(gf,e[1],$.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=$.parse(this.value,bs);return e[""]=t.toJSON().join(", "),e}};np.NAME="Key Usages";var op=class r extends yr{static async create(e,t=!1,n=vt.get()){let i=await(await Pn.create(e,n)).getKeyIdentifier(n);return new r(H.Convert.ToHex(i),t)}constructor(...e){if(H.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=$.parse(this.value,Mt);this.keyId=H.Convert.ToHex(t)}else{let t=typeof e[0]=="string"?H.Convert.FromHex(e[0]):e[0],n=new Mt(t);super(gm,e[1],$.serialize(n)),this.keyId=H.Convert.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=$.parse(this.value,Mt);return e[""]=t,e}};op.NAME="Subject Key Identifier";var ip=class extends yr{constructor(...e){H.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(mm,e[1],new Ki(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=$.parse(e.extnValue,vf);this.names=new Ki(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};ip.NAME="Subject Alternative Name";var Wt=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new yr(e),n=this.items.get(t.type);return n?new n(e):t}};Wt.items=new Map;var sp=class extends yr{constructor(...e){var t;if(H.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let n=$.parse(this.value,dc);this.policies=n.map(o=>o.policyIdentifier)}else{let n=e[0],o=(t=e[1])!==null&&t!==void 0?t:!1,i=new dc(n.map(s=>new pi({policyIdentifier:s})));super(df,o,$.serialize(i)),this.policies=n}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(t=>new Se("",{},rn.toString(t))),e}};sp.NAME="Certificate Policies";Wt.register(df,sp);var ap=class extends yr{constructor(...e){var t;if(H.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let o=e[0].map(s=>new zr({distributionPoint:new _n({fullName:[new ae({uniformResourceIdentifier:s})]})})),i=new uo(o);super(mf,e[1],$.serialize(i))}else{let n=new uo(e[0]);super(mf,e[1],$.serialize(n))}(t=this.distributionPoints)!==null&&t!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let t=$.parse(e.extnValue,uo);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(t=>{var n;let o={};return t.distributionPoint&&(o[""]=(n=t.distributionPoint.fullName)===null||n===void 0?void 0:n.map(i=>new tn(i).toString()).join(", ")),t.reasons&&(o.Reasons=t.reasons.toString()),t.cRLIssuer&&(o["CRL Issuer"]=t.cRLIssuer.map(i=>i.toString()).join(", ")),o}),e}};ap.NAME="CRL Distribution Points";var cp=class extends yr{constructor(...e){var t,n,o,i;if(H.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof ui){let s=new ui(e[0]);super(lf,e[1],$.serialize(s))}else{let s=e[0],a=new ui;Zf(a,s,Qd,"ocsp"),Zf(a,s,em,"caIssuers"),Zf(a,s,tm,"timeStamping"),Zf(a,s,rm,"caRepository"),super(lf,e[1],$.serialize(a))}(t=this.ocsp)!==null&&t!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(o=this.timeStamping)!==null&&o!==void 0||(this.timeStamping=[]),(i=this.caRepository)!==null&&i!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],$.parse(e.extnValue,ui).forEach(n=>{switch(n.accessMethod){case Qd:this.ocsp.push(new tn(n.accessLocation));break;case em:this.caIssuers.push(new tn(n.accessLocation));break;case tm:this.timeStamping.push(new tn(n.accessLocation));break;case rm:this.caRepository.push(new tn(n.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Yf(e,"OCSP",this.ocsp),this.caIssuers.length&&Yf(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Yf(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Yf(e,"CA Repository",this.caRepository),e}};cp.NAME="Authority Info Access";function Yf(r,e,t){if(t.length===1)r[e]=t[0].toTextObject();else{let n=new Se("");t.forEach((o,i)=>{let s=o.toTextObject(),a=`${s[Se.NAME]} ${i+1}`,c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(s)}),r[e]=n}}function Zf(r,e,t,n){let o=e[n];o&&(Array.isArray(o)?o:[o]).forEach(s=>{typeof s=="string"&&(s=new tn("url",s)),r.push(new Sn({accessMethod:t,accessLocation:$.parse(s.rawData,ae)}))})}var Ys=class r extends _o{constructor(...e){let t;if(H.BufferSourceConverter.isBufferSource(e[0]))t=H.BufferSourceConverter.toArrayBuffer(e[0]);else{let n=e[0],o=Array.isArray(e[1])?e[1].map(i=>H.BufferSourceConverter.toArrayBuffer(i)):[];t=$.serialize(new mt({type:n,values:o}))}super(t,mt)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(t=>new Se("",{"":t})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Se.NAME]===r.NAME&&(e[Se.NAME]=rn.toString(this.type)),e}};Ys.NAME="Attribute";var up=class extends Ys{constructor(...e){var t;if(H.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=new Xc({printableString:e[0]});super(py,[$.serialize(n)])}(t=this.password)!==null&&t!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let t=$.parse(this.values[0],Xc);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Se.VALUE]=this.password,e}};up.NAME="Challenge Password";var ou=class extends Ys{constructor(...e){var t;if(H.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=e[0],o=new Jt;for(let i of n)o.push($.parse(i.rawData,gt));super(Zc,[$.serialize(o)])}(t=this.items)!==null&&t!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let t=$.parse(this.values[0],Jt);this.items=t.map(n=>Wt.create($.serialize(n)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(n=>n.toTextObject());for(let n of t)e[n[Se.NAME]]=n;return e}};ou.NAME="Extensions";var Zs=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new Ys(e),n=this.items.get(t.type);return n?new n(e):t}};Zs.items=new Map;var su="crypto.signatureFormatter",_y=class{toAsnSignature(e,t){return H.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return H.BufferSourceConverter.toArrayBuffer(t)}},Qf,Cy=Qf=class{static createPssParams(e,t){let n=Qf.getHashAlgorithm(e);return n?new Qr({hashAlgorithm:n,maskGenAlgorithm:new j({algorithm:wo,parameters:$.serialize(n)}),saltLength:t}):null}static getHashAlgorithm(e){let t=$e.resolve(Mi);return typeof e=="string"?t.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let t;if(typeof e.hash=="string")t=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")t=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(t.toLowerCase()){case"sha-1":return new j({algorithm:Us,parameters:null});case"sha-256":return new j({algorithm:Of,parameters:null});case"sha-384":return new j({algorithm:js,parameters:null});case"sha-512":return new j({algorithm:Ms,parameters:null})}}else return new j({algorithm:Jr,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let t=Qf.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new j({algorithm:go,parameters:$.serialize(t)})}else return new j({algorithm:go,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case Jr:return{name:"RSASSA-PKCS1-v1_5"};case Us:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Of:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case js:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Ms:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case go:if(e.parameters){let t=$.parse(e.parameters,Qr);return{name:"RSA-PSS",hash:$e.resolve(Mi).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}else return{name:"RSA-PSS"}}return null}};Cy=Qf=u([bo()],Cy);$e.registerSingleton(iu,Cy);var Iy=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new j({algorithm:Bi});case"sha-256":return new j({algorithm:ki});case"sha-384":return new j({algorithm:Pi});case"sha-512":return new j({algorithm:Ni})}return null}toWebAlgorithm(e){switch(e.algorithm){case Bi:return{name:"SHA-1"};case ki:return{name:"SHA-256"};case Pi:return{name:"SHA-384"};case Ni:return{name:"SHA-512"}}return null}};Iy=u([bo()],Iy);$e.registerSingleton(iu,Iy);var On=class r{addPadding(e,t){let n=H.BufferSourceConverter.toUint8Array(t),o=new Uint8Array(e);return o.set(n,e-n.length),o}removePadding(e,t=!1){let n=H.BufferSourceConverter.toUint8Array(e);for(let o=0;o<n.length;o++)if(n[o]){n=n.slice(o);break}if(t&&n[0]>127){let o=new Uint8Array(n.length+1);return o.set(n,1),o.buffer}return n.buffer}toAsnSignature(e,t){if(e.name==="ECDSA"){let n=e.namedCurve,o=r.namedCurveSize.get(n)||r.defaultNamedCurveSize,i=new Ti,s=H.BufferSourceConverter.toUint8Array(t);return i.r=this.removePadding(s.slice(0,o),!0),i.s=this.removePadding(s.slice(o,o+o),!0),$.serialize(i)}return null}toWebSignature(e,t){if(e.name==="ECDSA"){let n=$.parse(t,Ti),o=e.namedCurve,i=r.namedCurveSize.get(o)||r.defaultNamedCurveSize,s=this.addPadding(i,this.removePadding(n.r)),a=this.addPadding(i,this.removePadding(n.s));return(0,H.combine)(s,a)}return null}};On.namedCurveSize=new Map;On.defaultNamedCurveSize=32;var vy="1.3.101.110",i1="1.3.101.111",Ay="1.3.101.112",s1="1.3.101.113",Ty=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=Ay;break;case"x25519":t=vy;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=Ay;break;case"ed448":t=s1;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=vy;break;case"x448":t=i1;break}}return t?new j({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case Ay:return{name:"Ed25519"};case s1:return{name:"EdDSA",namedCurve:"Ed448"};case vy:return{name:"X25519"};case i1:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Ty=u([bo()],Ty);$e.registerSingleton(iu,Ty);var By=class extends Co{constructor(e){Co.isAsnEncoded(e)?super(e,Eo):super(e),this.tag=Nt.CertificateRequestTag}onInit(e){this.tbs=$.serialize(e.certificationRequestInfo),this.publicKey=new Pn(e.certificationRequestInfo.subjectPKInfo);let t=$e.resolve(Mi);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(o=>Zs.create($.serialize(o)));let n=this.getAttribute(Zc);this.extensions=[],n instanceof ou&&(this.extensions=n.items),this.subjectName=new mr(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=vt.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,["verify"],e),o=$e.resolveAll(su).reverse(),i=null;for(let a of o)if(i=a.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=$.parse(this.rawData,Eo),n=t.certificationRequestInfo,o=new Se("",{Version:`${Xr[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let i=new Se("");for(let s of this.attributes){let a=s.toTextObject();i[a[Se.NAME]]=a}o.Attributes=i}return e.Data=o,e.Signature=new Se("",{Algorithm:Nn.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};By.NAME="PKCS#10 Certificate Request";var Js=class extends Co{constructor(e){Co.isAsnEncoded(e)?super(e,lr):super(e),this.tag=Nt.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=$.serialize(t),this.serialNumber=H.Convert.ToHex(t.serialNumber),this.subjectName=new mr(t.subject),this.subject=new mr(t.subject).toString(),this.issuerName=new mr(t.issuer),this.issuer=this.issuerName.toString();let n=$e.resolve(Mi);this.signatureAlgorithm=n.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;let o=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!o)throw new Error("Cannot get 'notBefore' value");this.notBefore=o;let i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(s=>Wt.create($.serialize(s)))),this.publicKey=new Pn(t.subjectPublicKeyInfo)}getExtension(e){for(let t of this.extensions)if(typeof e=="string"){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e=="string"?t.type===e:t instanceof e)}async verify(e={},t=vt.get()){let n,o,i=e.publicKey;try{if(!i)n={...this.publicKey.algorithm,...this.signatureAlgorithm},o=await this.publicKey.export(n,["verify"],t);else if("publicKey"in i)n={...i.publicKey.algorithm,...this.signatureAlgorithm},o=await i.publicKey.export(n,["verify"],t);else if(i instanceof Pn)n={...i.algorithm,...this.signatureAlgorithm},o=await i.export(n,["verify"],t);else if(H.BufferSourceConverter.isBufferSource(i)){let l=new Pn(i);n={...l.algorithm,...this.signatureAlgorithm},o=await l.export(n,["verify"],t)}else n={...i.algorithm,...this.signatureAlgorithm},o=i}catch{return!1}let s=$e.resolveAll(su).reverse(),a=null;for(let l of s)if(a=l.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await t.subtle.verify(this.signatureAlgorithm,o,a,this.tbs);if(e.signatureOnly)return c;{let p=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<p&&p<this.notAfter.getTime()}}async getThumbprint(...e){let t,n="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??(t=vt.get()),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=vt.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=$.parse(this.rawData,lr),n=t.tbsCertificate,o=new Se("",{Version:`${Xr[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":Nn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new Se("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(o["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(o["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){let i=new Se("");for(let s of this.extensions){let a=s.toTextObject();i[a[Se.NAME]]=a}o.Extensions=i}return e.Data=o,e.Signature=new Se("",{Algorithm:Nn.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};Js.NAME="Certificate";var lp=class{static async createSelfSigned(e,t=vt.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=vt.get()){var n;let o;e.publicKey instanceof Pn?o=e.publicKey.rawData:"publicKey"in e.publicKey?o=e.publicKey.publicKey.rawData:H.BufferSourceConverter.isBufferSource(e.publicKey)?o=e.publicKey:o=await t.subtle.exportKey("spki",e.publicKey);let i=e.serialNumber?H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));i[0]>127&&(i[0]&=127),i.length>1&&i[0]===0&&(i[1]|=128);let s=e.notBefore||new Date,a=e.notAfter||new Date(s.getTime()+31536e6),c=new lr({tbsCertificate:new wt({version:Xr.v3,serialNumber:i,validity:new Cn({notBefore:s,notAfter:a}),extensions:new Jt(((n=e.extensions)===null||n===void 0?void 0:n.map(y=>$.parse(y.rawData,gt)))||[]),subjectPublicKeyInfo:$.parse(o,yt)})});if(e.subject){let y=e.subject instanceof mr?e.subject:new mr(e.subject);c.tbsCertificate.subject=$.parse(y.toArrayBuffer(),Pe)}if(e.issuer){let y=e.issuer instanceof mr?e.issuer:new mr(e.issuer);c.tbsCertificate.issuer=$.parse(y.toArrayBuffer(),Pe)}let l={hash:"SHA-256"},p="signingKey"in e?{...l,...e.signingAlgorithm,...e.signingKey.algorithm}:{...l,...e.signingAlgorithm},h=$e.resolve(Mi);c.tbsCertificate.signature=c.signatureAlgorithm=h.toAsnAlgorithm(p);let m=$.serialize(c.tbsCertificate),g="signingKey"in e?await t.subtle.sign(p,e.signingKey,m):e.signature,x=$e.resolveAll(su).reverse(),w=null;for(let y of x)if(w=y.toAsnSignature(p,g),w)break;if(!w)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=w,new Js($.serialize(c))}},a1;(function(r){r[r.unspecified=0]="unspecified",r[r.keyCompromise=1]="keyCompromise",r[r.cACompromise=2]="cACompromise",r[r.affiliationChanged=3]="affiliationChanged",r[r.superseded=4]="superseded",r[r.cessationOfOperation=5]="cessationOfOperation",r[r.certificateHold=6]="certificateHold",r[r.removeFromCRL=8]="removeFromCRL",r[r.privilegeWithdrawn=9]="privilegeWithdrawn",r[r.aACompromise=10]="aACompromise"})(a1||(a1={}));Wt.register(pf,Xs);Wt.register(yf,rp);Wt.register(gf,np);Wt.register(gm,op);Wt.register(ff,tp);Wt.register(mm,ip);Wt.register(mf,ap);Wt.register(lf,cp);Zs.register(py,up);Zs.register(Zc,ou);$e.registerSingleton(su,_y);$e.registerSingleton(su,On);On.namedCurveSize.set("P-256",32);On.namedCurveSize.set("K-256",32);On.namedCurveSize.set("P-384",48);On.namedCurveSize.set("P-521",66);var Rn="/",p1=new TextEncoder().encode(Rn),fp=p1[0],au=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=de(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==fp)throw new Error("Invalid key")}toString(e="utf8"){return ue(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=p1),this._buf[0]!==fp){let e=new Uint8Array(this._buf.byteLength+1);e.fill(fp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===fp;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rn).slice(1)}type(){return RC(this.baseNamespace())}name(){return LC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rn)||(e+=Rn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rn):new r(e.slice(0,-1).join(Rn))}child(e){return this.toString()===Rn?e:e.toString()===Rn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...DC(e.map(t=>t.namespaces()))])}};function RC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function LC(r){let e=r.split(":");return e[e.length-1]}function DC(r){return[].concat(...r)}var pp=class extends Mn{async listen(){throw new Dl("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};var ky=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Ee(),this.haveNext=Ee()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ee(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ee(),await lt(this.readNext.promise,t?.signal,t)}};function h1(){return new ky}var hp=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Py=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ny=class extends Py{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function d1(r,e){let t=h1();r.sink(t).catch(async s=>{await t.end(s)}),r.sink=async s=>{for await(let a of s)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new pe;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((p,h)=>{c=()=>{h(new Ny("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:h,value:m}=await Promise.race([n.next(),l]);return h===!0?new pe:m}for(;o.byteLength<s;){let{value:h,done:m}=await Promise.race([n.next(),l]);if(m===!0)throw new hp("unexpected end of input");o.append(h)}let p=o.sublist(0,s);return o.consume(s),p}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await t.push(s,a):await t.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var dp=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},mp=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},yp=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Oy(r,e={}){let t=d1(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Re(e.maxDataLength));let n=e?.lengthDecoder??zt,o=e?.lengthEncoder??nr;return{read:async s=>{let a=-1,c=new pe;for(;;){c.append(await t.read(1,s));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new dp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new yp("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new mp("message length too long");return t.read(a,s)},write:async(s,a)=>{await t.write(new pe(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new pe(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function Ry(){let r=Ee(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function m1(){let r=Ry(),e=Ry();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}var Ly=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ee(),this.haveNext=Ee()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ee(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ee(),await lt(this.readNext.promise,t?.signal,t)}};function y1(){return new Ly}function UC(r){return r[Symbol.asyncIterator]!=null}async function jC(r,e){try{await Promise.all(r.map(async t=>{for await(let n of t)await e.push(n)})),await e.end()}catch(t){await e.end(t).catch(()=>{})}}async function*MC(r){let e=y1();jC(r,e).catch(()=>{}),yield*e}function*KC(r){for(let e of r)yield*e}function HC(...r){let e=[];for(let t of r)UC(t)||e.push(t);return e.length===r.length?KC(e):MC(r)}var g1=HC;function w1(r,...e){if(r==null)throw new Error("Empty pipeline");if(Dy(r)){let n=r;r=()=>n.source}else if(b1(r)||x1(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Dy(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Dy(t[n])&&(t[n]=$C(t[n]));return VC(...t)}var VC=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},x1=r=>r?.[Symbol.asyncIterator]!=null,b1=r=>r?.[Symbol.iterator]!=null,Dy=r=>r==null?!1:r.sink!=null&&r.source!=null,$C=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=ls({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(x1(i))o=async function*(){yield*i,n.end()};else if(b1(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return g1(n,o())}return r.source};var Qs=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function gp(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Uy(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Tt(r,...e){if(!Uy(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function jy(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function v1(r,e){Tt(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function My(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var Ln=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),A1=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),FC=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!FC)throw new Error("Non little-endian hardware is not supported");function WC(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function wp(r){if(typeof r=="string")r=WC(r);else if(Uy(r))r=xp(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function S1(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function E1(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var Ky=(r,e)=>{function t(n,...o){if(Tt(n),r.nonceLength!==void 0){let p=o[0];if(!p)throw new Error("nonce / iv required");r.varSizeNonce?Tt(p):Tt(p,r.nonceLength)}let i=r.tagLength;i&&o[1]!==void 0&&Tt(o[1]);let s=e(n,...o),a=(p,h)=>{if(h!==void 0){if(p!==2)throw new Error("cipher output not supported");Tt(h)}},c=!1;return{encrypt(p,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Tt(p),a(s.encrypt.length,h),s.encrypt(p,h)},decrypt(p,h){if(Tt(p),i&&p.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(s.decrypt.length,h),s.decrypt(p,h)}}}return Object.assign(t,r),t};function Hy(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!qC(e))throw new Error("invalid output, must be aligned");return e}function Vy(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(t>>o&i),a=Number(t&i),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}function qC(r){return r.byteOffset%4===0}function xp(r){return Uint8Array.from(r)}function Dn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}var C1=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),GC=C1("expand 16-byte k"),zC=C1("expand 32-byte k"),XC=Ln(GC),YC=Ln(zC);function Z(r,e){return r<<e|r>>>32-e}function $y(r){return r.byteOffset%4===0}var bp=64,ZC=16,I1=2**32-1,_1=new Uint32Array;function JC(r,e,t,n,o,i,s,a){let c=o.length,l=new Uint8Array(bp),p=Ln(l),h=$y(o)&&$y(i),m=h?Ln(o):_1,g=h?Ln(i):_1;for(let x=0;x<c;s++){if(r(e,t,n,p,s,a),s>=I1)throw new Error("arx: counter overflow");let w=Math.min(bp,c-x);if(h&&w===bp){let y=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let S=0,T;S<ZC;S++)T=y+S,g[T]=m[T]^p[S];x+=bp;continue}for(let y=0,S;y<w;y++)S=x+y,i[S]=o[S]^l[y];x+=w}}function Fy(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:i,rounds:s}=S1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return gp(o),gp(s),My(i),My(t),(a,c,l,p,h=0)=>{Tt(a),Tt(c),Tt(l);let m=l.length;if(p===void 0&&(p=new Uint8Array(m)),Tt(p),gp(h),h<0||h>=I1)throw new Error("arx: counter overflow");if(p.length<m)throw new Error(`arx: output (${p.length}) is shorter than data (${m})`);let g=[],x=a.length,w,y;if(x===32)g.push(w=xp(a)),y=YC;else if(x===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),y=XC,g.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);$y(c)||g.push(c=xp(c));let S=Ln(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(y,S,Ln(c.subarray(0,16)),S),c=c.subarray(16)}let T=16-o;if(T!==c.length)throw new Error(`arx: nonce must be ${T} or 16 bytes`);if(T!==12){let L=new Uint8Array(12);L.set(c,i?0:12-c.length),c=L,g.push(c)}let v=Ln(c);return JC(r,y,S,v,l,p,h,s),Dn(...g),p}}var At=(r,e)=>r[e++]&255|(r[e++]&255)<<8,Wy=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=wp(e),Tt(e,32);let t=At(e,0),n=At(e,2),o=At(e,4),i=At(e,6),s=At(e,8),a=At(e,10),c=At(e,12),l=At(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let p=0;p<8;p++)this.pad[p]=At(e,16+2*p)}process(e,t,n=!1){let o=n?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],p=s[3],h=s[4],m=s[5],g=s[6],x=s[7],w=s[8],y=s[9],S=At(e,t+0),T=At(e,t+2),v=At(e,t+4),L=At(e,t+6),F=At(e,t+8),K=At(e,t+10),O=At(e,t+12),M=At(e,t+14),D=i[0]+(S&8191),ne=i[1]+((S>>>13|T<<3)&8191),G=i[2]+((T>>>10|v<<6)&8191),J=i[3]+((v>>>7|L<<9)&8191),le=i[4]+((L>>>4|F<<12)&8191),R=i[5]+(F>>>1&8191),U=i[6]+((F>>>14|K<<2)&8191),I=i[7]+((K>>>11|O<<5)&8191),E=i[8]+((O>>>8|M<<8)&8191),P=i[9]+(M>>>5|o),B=0,W=B+D*a+ne*(5*y)+G*(5*w)+J*(5*x)+le*(5*g);B=W>>>13,W&=8191,W+=R*(5*m)+U*(5*h)+I*(5*p)+E*(5*l)+P*(5*c),B+=W>>>13,W&=8191;let q=B+D*c+ne*a+G*(5*y)+J*(5*w)+le*(5*x);B=q>>>13,q&=8191,q+=R*(5*g)+U*(5*m)+I*(5*h)+E*(5*p)+P*(5*l),B+=q>>>13,q&=8191;let N=B+D*l+ne*c+G*a+J*(5*y)+le*(5*w);B=N>>>13,N&=8191,N+=R*(5*x)+U*(5*g)+I*(5*m)+E*(5*h)+P*(5*p),B+=N>>>13,N&=8191;let ie=B+D*p+ne*l+G*c+J*a+le*(5*y);B=ie>>>13,ie&=8191,ie+=R*(5*w)+U*(5*x)+I*(5*g)+E*(5*m)+P*(5*h),B+=ie>>>13,ie&=8191;let ce=B+D*h+ne*p+G*l+J*c+le*a;B=ce>>>13,ce&=8191,ce+=R*(5*y)+U*(5*w)+I*(5*x)+E*(5*g)+P*(5*m),B+=ce>>>13,ce&=8191;let ee=B+D*m+ne*h+G*p+J*l+le*c;B=ee>>>13,ee&=8191,ee+=R*a+U*(5*y)+I*(5*w)+E*(5*x)+P*(5*g),B+=ee>>>13,ee&=8191;let be=B+D*g+ne*m+G*h+J*p+le*l;B=be>>>13,be&=8191,be+=R*c+U*a+I*(5*y)+E*(5*w)+P*(5*x),B+=be>>>13,be&=8191;let Ne=B+D*x+ne*g+G*m+J*h+le*p;B=Ne>>>13,Ne&=8191,Ne+=R*l+U*c+I*a+E*(5*y)+P*(5*w),B+=Ne>>>13,Ne&=8191;let Be=B+D*w+ne*x+G*g+J*m+le*h;B=Be>>>13,Be&=8191,Be+=R*p+U*l+I*c+E*a+P*(5*y),B+=Be>>>13,Be&=8191;let De=B+D*y+ne*w+G*x+J*g+le*m;B=De>>>13,De&=8191,De+=R*h+U*p+I*l+E*c+P*a,B+=De>>>13,De&=8191,B=(B<<2)+B|0,B=B+W|0,W=B&8191,B=B>>>13,q+=B,i[0]=W,i[1]=q,i[2]=N,i[3]=ie,i[4]=ce,i[5]=ee,i[6]=be,i[7]=Ne,i[8]=Be,i[9]=De}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+t[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+t[a]|0)+(s>>>16)|0,e[a]=s&65535;Dn(n)}update(e){jy(this);let{buffer:t,blockLen:n}=this;e=wp(e);let o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){for(;n<=o-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Dn(this.h,this.r,this.buffer,this.pad)}digestInto(e){jy(this),v1(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=n[s]>>>0,e[i++]=n[s]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function QC(r){let e=(n,o)=>r(o).update(wp(n)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var T1=QC(r=>new Wy(r));function P1(r,e,t,n,o,i=20){let s=r[0],a=r[1],c=r[2],l=r[3],p=e[0],h=e[1],m=e[2],g=e[3],x=e[4],w=e[5],y=e[6],S=e[7],T=o,v=t[0],L=t[1],F=t[2],K=s,O=a,M=c,D=l,ne=p,G=h,J=m,le=g,R=x,U=w,I=y,E=S,P=T,B=v,W=L,q=F;for(let ie=0;ie<i;ie+=2)K=K+ne|0,P=Z(P^K,16),R=R+P|0,ne=Z(ne^R,12),K=K+ne|0,P=Z(P^K,8),R=R+P|0,ne=Z(ne^R,7),O=O+G|0,B=Z(B^O,16),U=U+B|0,G=Z(G^U,12),O=O+G|0,B=Z(B^O,8),U=U+B|0,G=Z(G^U,7),M=M+J|0,W=Z(W^M,16),I=I+W|0,J=Z(J^I,12),M=M+J|0,W=Z(W^M,8),I=I+W|0,J=Z(J^I,7),D=D+le|0,q=Z(q^D,16),E=E+q|0,le=Z(le^E,12),D=D+le|0,q=Z(q^D,8),E=E+q|0,le=Z(le^E,7),K=K+G|0,q=Z(q^K,16),I=I+q|0,G=Z(G^I,12),K=K+G|0,q=Z(q^K,8),I=I+q|0,G=Z(G^I,7),O=O+J|0,P=Z(P^O,16),E=E+P|0,J=Z(J^E,12),O=O+J|0,P=Z(P^O,8),E=E+P|0,J=Z(J^E,7),M=M+le|0,B=Z(B^M,16),R=R+B|0,le=Z(le^R,12),M=M+le|0,B=Z(B^M,8),R=R+B|0,le=Z(le^R,7),D=D+ne|0,W=Z(W^D,16),U=U+W|0,ne=Z(ne^U,12),D=D+ne|0,W=Z(W^D,8),U=U+W|0,ne=Z(ne^U,7);let N=0;n[N++]=s+K|0,n[N++]=a+O|0,n[N++]=c+M|0,n[N++]=l+D|0,n[N++]=p+ne|0,n[N++]=h+G|0,n[N++]=m+J|0,n[N++]=g+le|0,n[N++]=x+R|0,n[N++]=w+U|0,n[N++]=y+I|0,n[N++]=S+E|0,n[N++]=T+P|0,n[N++]=v+B|0,n[N++]=L+W|0,n[N++]=F+q|0}function eI(r,e,t,n){let o=r[0],i=r[1],s=r[2],a=r[3],c=e[0],l=e[1],p=e[2],h=e[3],m=e[4],g=e[5],x=e[6],w=e[7],y=t[0],S=t[1],T=t[2],v=t[3];for(let F=0;F<20;F+=2)o=o+c|0,y=Z(y^o,16),m=m+y|0,c=Z(c^m,12),o=o+c|0,y=Z(y^o,8),m=m+y|0,c=Z(c^m,7),i=i+l|0,S=Z(S^i,16),g=g+S|0,l=Z(l^g,12),i=i+l|0,S=Z(S^i,8),g=g+S|0,l=Z(l^g,7),s=s+p|0,T=Z(T^s,16),x=x+T|0,p=Z(p^x,12),s=s+p|0,T=Z(T^s,8),x=x+T|0,p=Z(p^x,7),a=a+h|0,v=Z(v^a,16),w=w+v|0,h=Z(h^w,12),a=a+h|0,v=Z(v^a,8),w=w+v|0,h=Z(h^w,7),o=o+l|0,v=Z(v^o,16),x=x+v|0,l=Z(l^x,12),o=o+l|0,v=Z(v^o,8),x=x+v|0,l=Z(l^x,7),i=i+p|0,y=Z(y^i,16),w=w+y|0,p=Z(p^w,12),i=i+p|0,y=Z(y^i,8),w=w+y|0,p=Z(p^w,7),s=s+h|0,S=Z(S^s,16),m=m+S|0,h=Z(h^m,12),s=s+h|0,S=Z(S^s,8),m=m+S|0,h=Z(h^m,7),a=a+c|0,T=Z(T^a,16),g=g+T|0,c=Z(c^g,12),a=a+c|0,T=Z(T^a,8),g=g+T|0,c=Z(c^g,7);let L=0;n[L++]=o,n[L++]=i,n[L++]=s,n[L++]=a,n[L++]=y,n[L++]=S,n[L++]=T,n[L++]=v}var tI=Fy(P1,{counterRight:!1,counterLength:4,allowShortKeys:!1}),rI=Fy(P1,{counterRight:!1,counterLength:8,extendNonceFn:eI,allowShortKeys:!1});var nI=new Uint8Array(16),B1=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(nI.subarray(t))},oI=new Uint8Array(32);function k1(r,e,t,n,o){let i=r(e,t,oI),s=T1.create(i);o&&B1(s,o),B1(s,n);let a=new Uint8Array(16),c=A1(a);Vy(c,0,BigInt(o?o.length:0),!0),Vy(c,8,BigInt(n.length),!0),s.update(a);let l=s.digest();return Dn(i,a),l}var N1=r=>(e,t,n)=>({encrypt(i,s){let a=i.length;s=Hy(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);r(e,t,c,c,1);let l=k1(r,e,t,c,n);return s.set(l,a),Dn(l),s},decrypt(i,s){s=Hy(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=k1(r,e,t,a,n);if(!E1(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),r(e,t,s,s,1),Dn(l),s}}),qy=Ky({blockSize:64,nonceLength:12,tagLength:16},N1(tI)),Mz=Ky({blockSize:64,nonceLength:24,tagLength:16},N1(rI));function R1(r,e,t){return da(r),t===void 0&&(t=new Uint8Array(r.outputLen)),ns(r,$n(t),$n(e))}var Gy=new Uint8Array([0]),O1=new Uint8Array;function L1(r,e,t,n=32){if(da(r),Du(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);t===void 0&&(t=O1);let i=new Uint8Array(o*r.outputLen),s=ns.create(r,e),a=s._cloneInto(),c=new Uint8Array(s.outputLen);for(let l=0;l<o;l++)Gy[0]=l+1,a.update(l===0?O1:c).update(t).update(Gy).digestInto(c),i.set(c,r.outputLen*l),s._cloneInto(a);return s.destroy(),a.destroy(),c.fill(0),Gy.fill(0),i.slice(0,n)}var zy={hashSHA256(r){return Kr(r.subarray())},getHKDF(r,e){let t=R1(Kr,e,r),o=L1(Kr,t,void 0,96),i=o.subarray(0,32),s=o.subarray(32,64),a=o.subarray(64,96);return[i,s,a]},generateX25519KeyPair(){let r=va.utils.randomPrivateKey();return{publicKey:va.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:va.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return va.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return qy(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return qy(n,e,t).decrypt(r.subarray(),o)}};var D1=zy;function U1(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var ea=r=>{let e=ot(2);return e[0]=r>>8,e[1]=r,e};ea.bytes=2;var cu=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};cu.bytes=2;function j1(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Xy(r,e){!e.enabled||!Qs||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${ue(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${ue(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Yy(r,e){!e.enabled||!Qs||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ue(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ue(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function M1(r,e){!e.enabled||!Qs||e(r?`REMOTE_STATIC_PUBLIC_KEY ${ue(r.subarray(),"hex")}`:"Missing remote static public key.")}function Zy(r,e){!e.enabled||!Qs||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ue(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Jy(r,e,t){!t.enabled||!Qs||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&ue(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&ue(e.k,"hex")}`))}var ta=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var iI=0,sI=4294967295,aI="Cipherstate has reached maximum n, a new handshake must be performed",vp=class{n;bytes;view;constructor(e=iI){this.n=e,this.bytes=nt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>sI)throw new Error(aI)}};var Hi=nt(0),ra=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new vp(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Qy=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=de(t,"utf-8");this.h=cI(e,n),this.ck=this.h,this.cs=new ra(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new ra(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new pe(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,Hi);return[new ra(this.crypto,e),new ra(this.crypto,t)]}},eg=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:i,s,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Qy(t,n),this.ss.mixHash(o),this.initiator=i,this.s=s,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},uu=class extends eg{writeMessageA(e){return new pe(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new pe(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new pe(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new ta(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new ta(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new ta(`handshake stage 2 validation fail: ${t.message}`)}}};function cI(r,e){if(e.length<=32){let t=nt(32);return t.set(e),t}else return r.hash(e)}var Ap;(function(r){let e;r.codec=()=>(e==null&&(e=Tr((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let i of t.webtransportCerthashes)n.uint32(10),n.bytes(i);if(t.streamMuxers!=null)for(let i of t.streamMuxers)n.uint32(18),n.string(i);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={webtransportCerthashes:[],streamMuxers:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new _a('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&i.streamMuxers.length===o.limits.streamMuxers)throw new _a('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Ir(t,r.codec()),r.decode=(t,n)=>Cr(t,r.codec(),n)})(Ap||(Ap={}));var lu;(function(r){let e;r.codec=()=>(e==null&&(e=Tr((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),Ap.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={identityKey:nt(0),identitySig:nt(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.identityKey=t.bytes();break}case 2:{i.identitySig=t.bytes();break}case 4:{i.extensions=Ap.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Ir(t,r.codec()),r.decode=(t,n)=>Cr(t,r.codec(),n)})(lu||(lu={}));async function tg(r,e,t){let n=await r.sign(K1(e));return lu.encode({identityKey:Vn(r.publicKey),identitySig:n,extensions:t})}async function rg(r,e,t){try{let n=lu.decode(r),o=Pa(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let i=K1(e);if(!await o.verify(i,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Au(n.message)}}function K1(r){let e=de("noise-libp2p-static-key:");return r instanceof Uint8Array?it([e,r],e.length+r.length):(r.prepend(e),r)}async function H1(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,p=await tg(i,a.publicKey,l),h=new uu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:a});Xy(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Hi),e),t.trace("Stage 0 - Initiator finished sending first message."),Yy(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let m=h.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Zy(h.re,t),M1(h.rs,t),t.trace("Initiator going to check remote's signature...");let g=await rg(m,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(p),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[x,w]=h.ss.split();return Jy(x,w,t),{payload:g,encrypt:y=>x.encryptWithAd(Hi,y),decrypt:(y,S)=>w.decryptWithAd(Hi,y,S)}}async function V1(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,p=await tg(i,a.publicKey,l),h=new uu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:a});Xy(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Zy(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(p),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Yy(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let m=h.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let g=await rg(m,h.rs,c),[x,w]=h.ss.split();return Jy(x,w,t),{payload:g,encrypt:y=>w.encryptWithAd(Hi,y),decrypt:(y,S)=>x.decryptWithAd(Hi,y,S)}}var F1=16;function W1(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65519){let i=o+65519;i>n.length&&(i=n.length);let s;n instanceof Uint8Array?s=r.encrypt(n.subarray(o,i)):s=r.encrypt(n.sublist(o,i)),e?.encryptedPackets.increment(),yield new pe(ea(s.byteLength),s)}}}function q1(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65535){let i=o+65535;if(i>n.length&&(i=n.length),i-F1<o)throw new Error("Invalid chunk");let s=n.sublist(o,i),a=n.subarray(o,i-F1);try{let c=r.decrypt(s,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var Sp=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:i,prologueBytes:s}=t,{metrics:a}=e;this.components=e;let c=i??D1;this.crypto=U1(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?j1(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=s??nt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Fi]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=Oy(e,{lengthEncoder:ea,lengthDecoder:cu,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,t?.remotePeer?.publicKey,t),i=await this.createSecureConnection(n,o);e.source=i.source,e.sink=i.sink;let s=Pa(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:nd(s),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new Su("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=Oy(e,{lengthEncoder:ea,lengthDecoder:cu,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,t?.remotePeer?.publicKey,t),i=await this.createSecureConnection(n,o);e.source=i.source,e.sink=i.sink;let s=Pa(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:nd(s),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o){let i;try{i=await H1({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return i}async performHandshakeResponder(e,t,n,o){let i;try{i=await V1({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return i}async createSecureConnection(e,t){let[n,o]=m1(),i=e.unwrap();return await w1(n,W1(t,this.metrics),i,s=>Fo(s,{lengthDecoder:cu}),q1(t,this.metrics),n),o}};function G1(r={}){return e=>new Sp(e,r)}var ng=Object.values(Po).map(r=>r.decoder).reduce((r,e)=>r.or(e)),uI=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function z1(r){return r?.match(uI)?.groups?.fingerprint}function og(r){let t=r.stringTuples().filter(n=>n[0]===xw).map(n=>n[1])[0];if(t===void 0||t==="")throw new ve(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function lI(r){return er.decode(ng.decode(r))}function fI(r){let e=lI(og(r)),t=pI(e.code),n=e.digest.reduce((i,s)=>i+s.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Ll(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function X1(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=St(tr.code,t);return Hr(`/certhash/${ko.encode(n.bytes)}`)}function pI(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Ul(r)}}function Y1(r,e){let{host:t,port:n,family:o}=r.toOptions(),i=fI(r);return{type:"answer",sdp:`v=0
13
+ o=- 0 0 IN IP${o} ${t}
4
14
  s=-
5
15
  t=0 0
6
16
  a=ice-lite
7
17
  m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
8
- c=IN IP${o} ${e}
18
+ c=IN IP${o} ${t}
9
19
  a=mid:0
10
20
  a=ice-options:ice2
11
- a=ice-ufrag:${t}
12
- a=ice-pwd:${t}
13
- a=fingerprint:${s}
21
+ a=ice-ufrag:${e}
22
+ a=ice-pwd:${e}
23
+ a=fingerprint:${i}
14
24
  a=setup:passive
15
25
  a=sctp-port:5000
16
- a=max-message-size:${xr}
17
- a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
26
+ a=max-message-size:${cs}
27
+ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host
18
28
  a=end-of-candidates
19
- `}}function Zu(r,t){let{host:e,port:n,family:o}=r.toOptions();return{type:"offer",sdp:`v=0
20
- o=- 0 0 IN IP${o} ${e}
29
+ `}}function Z1(r,e){let{host:t,port:n,family:o}=r.toOptions();return{type:"offer",sdp:`v=0
30
+ o=- 0 0 IN IP${o} ${t}
21
31
  s=-
22
- c=IN IP${o} ${e}
32
+ c=IN IP${o} ${t}
23
33
  t=0 0
24
34
  a=ice-options:ice2,trickle
25
35
  m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
26
36
  a=mid:0
27
37
  a=setup:active
28
- a=ice-ufrag:${t}
29
- a=ice-pwd:${t}
38
+ a=ice-ufrag:${e}
39
+ a=ice-pwd:${e}
30
40
  a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
31
41
  a=sctp-port:5000
32
- a=max-message-size:${xr}
33
- a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
42
+ a=max-message-size:${cs}
43
+ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host
34
44
  a=end-of-candidates
35
- `}}function La(r,t){if(r.sdp===void 0)throw new Q("Can't munge a missing SDP");let e=r.sdp.includes(`\r
45
+ `}}function ig(r,e){if(r.sdp===void 0)throw new ve("Can't munge a missing SDP");let t=r.sdp.includes(`\r
36
46
  `)?`\r
37
47
  `:`
38
48
  `;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
- a=ice-ufrag:`+t+e).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+t+e),r}var Ba=X("libp2p-webrtc-noise:");function Ju(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=X(n,"hex"),s=Ct(ie.code,o),i=Ta.decode(_a(t)),a=Ba.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?yt([Ba,i,s.bytes],a):yt([Ba,s.bytes,i],a)}var Fm=an?"iceconnectionstatechange":"connectionstatechange";async function Qu(r,t,e){let n=r.createDataChannel("",{negotiated:!0,id:0});if(e.role==="client"){e.log.trace("client creating local offer");let d=await r.createOffer();e.log.trace("client created local offer %s",d.sdp);let g=La(d,t);e.log.trace("client setting local offer %s",g.sdp),await r.setLocalDescription(g);let x=Xu(e.remoteAddr,t);e.log.trace("client setting server description %s",x.sdp),await r.setRemoteDescription(x)}else{let d=Zu(e.remoteAddr,t);e.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),e.log.trace("server creating local answer");let g=await r.createAnswer();e.log.trace("server created local answer");let x=La(g,t);e.log.trace("server setting local description %s",g.sdp),await r.setLocalDescription(x)}if(e.log.trace("%s wait for handshake channel to open",e.role),await un(n,"open",e.signal),e.log.trace("%s handshake channel opened",e.role),e.role==="server"){let d=r.remoteFingerprint()?.value??"";e.remoteAddr=e.remoteAddr.encapsulate(ju(d))}let o=$u(r.localDescription?.sdp);if(o==null)throw new De("Could not get fingerprint from local description sdp");e.log.trace("%s performing noise handshake",e.role);let s=Ju(o,e.remoteAddr,e.role),i=zu({prologueBytes:s})(e),a=Ar({channel:n,direction:"inbound",logger:e.logger,...e.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let g of d)yield g}()},l=new je(e,{peerConnection:r,remoteAddr:e.remoteAddr,timeline:{open:Date.now()},metrics:e.events});r.addEventListener(Fm,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{e.log.error("error closing connection",d),l.abort(d)});break;default:break}}),e.events?.increment({peer_connection:!0});let u=new Re(e,{peerConnection:r,metrics:e.events,dataChannelOptions:e.dataChannel});if(e.role==="client")return e.log.trace("%s secure inbound",e.role),await i.secureInbound(c,{remotePeer:e.remotePeerId,signal:e.signal}),e.log.trace("%s upgrade outbound",e.role),e.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal});e.log.trace("%s secure outbound",e.role);let f=await i.secureOutbound(c,{remotePeer:e.remotePeerId,signal:e.signal});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),e.log.trace("%s upgrade inbound",e.role),await e.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal})}async function tf(r,t,e,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e=="function"?await e():e;return new RTCPeerConnection({...o??{},certificates:[n]})}var Wo=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[tr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){return new Ro(this.components,{...this.init,...t})}listenFilter(t){return t.filter(Pl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){e.signal.throwIfAborted();let n,o=t.getPeerId();o!=null&&(n=mr(o));let s=Ql(),i=await tf("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await bt(Qu(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:e.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),e.signal)}catch(a){throw i.close(),a}}};function Hm(r){return t=>new Wo(t,r)}function qm(r){return t=>new Po(t,r)}return pf(Vm);})();
49
+ a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
50
+ a=ice-pwd:`+e+t),r}var sg=de("libp2p-webrtc-noise:");function Q1(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=de(n,"hex"),i=St(tr.code,o),s=ng.decode(og(e)),a=sg.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?it([sg,s,i.bytes],a):it([sg,i.bytes,s],a)}var hI=Va?"iceconnectionstatechange":"connectionstatechange";async function eA(r,e,t){let n=r.createDataChannel("",{negotiated:!0,id:0});if(t.role==="client"){t.log.trace("client creating local offer");let m=await r.createOffer();t.log.trace("client created local offer %s",m.sdp);let g=ig(m,e);t.log.trace("client setting local offer %s",g.sdp),await r.setLocalDescription(g);let x=Y1(t.remoteAddr,e);t.log.trace("client setting server description %s",x.sdp),await r.setRemoteDescription(x)}else{let m=Z1(t.remoteAddr,e);t.log.trace("server setting client %s %s",m.type,m.sdp),await r.setRemoteDescription(m),t.log.trace("server creating local answer");let g=await r.createAnswer();t.log.trace("server created local answer");let x=ig(g,e);t.log.trace("server setting local description %s",g.sdp),await r.setLocalDescription(x)}if(t.log.trace("%s wait for handshake channel to open",t.role),await Wa(n,"open",t.signal),t.log.trace("%s handshake channel opened",t.role),t.role==="server"){let m=r.remoteFingerprint()?.value??"";t.remoteAddr=t.remoteAddr.encapsulate(X1(m))}let o=z1(r.localDescription?.sdp);if(o==null)throw new eo("Could not get fingerprint from local description sdp");t.log.trace("%s performing noise handshake",t.role);let i=Q1(o,t.remoteAddr,t.role),s=G1({prologueBytes:i})(t),a=ps({channel:n,direction:"inbound",logger:t.logger,...t.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let m of a.source)for(let g of m)yield g}()},l=new Vo(t,{peerConnection:r,remoteAddr:t.remoteAddr,timeline:{open:Date.now()},metrics:t.events});r.addEventListener(hI,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(m=>{t.log.error("error closing connection",m),l.abort(m)});break;default:break}}),t.events?.increment({peer_connection:!0});let p=new Qn(t,{peerConnection:r,metrics:t.events,dataChannelOptions:t.dataChannel});if(t.role==="client")return t.log.trace("%s secure inbound",t.role),await s.secureInbound(c,{remotePeer:t.remotePeerId,signal:t.signal}),t.log.trace("%s upgrade outbound",t.role),t.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:p,signal:t.signal});t.log.trace("%s secure outbound",t.role);let h=await s.secureOutbound(c,{remotePeer:t.remotePeerId,signal:t.signal});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${h.remotePeer}`),t.log.trace("%s upgrade inbound",t.role),await t.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:p,signal:t.signal})}async function tA(r,e,t,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t=="function"?await t():t;return new RTCPeerConnection({...o??{},certificates:[n]})}async function rA(r){let e=await ol(r),t=await crypto.subtle.exportKey("pkcs8",e.privateKey);return["-----BEGIN PRIVATE KEY-----",...ue(new Uint8Array(t),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join(`
51
+ `)}var Ep=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new Mn,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new ve("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[vu]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Fi]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){if(this.certificate==null)throw new ku;return new pp(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(hw.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){t.signal.throwIfAborted();let n,o=e.getPeerId();o!=null&&(n=os(o));let i=jw(),s=await tA("client",i,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await lt(eA(s,i,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),t.signal)}catch(a){throw s.close(),a}}async getCertificate(e){if(dI(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:o}=await this.loadOrCreateCertificate(t,e);return{privateKey:await rA(t),pem:n,certhash:o}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??Iw,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new To;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await W0("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,o=new au(this.init.certificateDatastoreKey??Cw),i=await ol(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new To;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(o,i)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(o,i)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??_d)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:ko.encode((await tr.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),o=new Js(n),i=o.notAfter.getTime()-(this.init.certificateRenewalThreshold??_d);if(Date.now()>i)throw this.log("stored TLS certificate has expired"),new To;this.log("loaded certificate, expires in %d ms",i);let s=await o.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!Ge(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new To;return this.log("loaded certificate, expiry time is %o",i),o}async createCertificate(e,t){let n=new Date,o=new Date(Date.now()+(this.init.certificateLifespan??Tw));n.setMilliseconds(0),o.setMilliseconds(0);let i=await lp.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:o,keys:t,extensions:[new Xs(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,de(i.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),i}getKeychain(){try{return this.components.keychain}catch{}}};function dI(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function mI(r){return e=>new Ep(e,r)}function yI(r){return e=>new Hl(e,r)}return lA(gI);})();
41
52
  /*! Bundled license information:
42
53
 
54
+ reflect-metadata/Reflect.js:
55
+ (*! *****************************************************************************
56
+ Copyright (C) Microsoft. All rights reserved.
57
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
58
+ this file except in compliance with the License. You may obtain a copy of the
59
+ License at http://www.apache.org/licenses/LICENSE-2.0
60
+
61
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
62
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
63
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
64
+ MERCHANTABLITY OR NON-INFRINGEMENT.
65
+
66
+ See the Apache Version 2.0 License for specific language governing permissions
67
+ and limitations under the License.
68
+ ***************************************************************************** *)
69
+
70
+ pvtsutils/build/index.js:
71
+ (*!
72
+ * MIT License
73
+ *
74
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
75
+ *
76
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
77
+ * of this software and associated documentation files (the "Software"), to deal
78
+ * in the Software without restriction, including without limitation the rights
79
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
80
+ * copies of the Software, and to permit persons to whom the Software is
81
+ * furnished to do so, subject to the following conditions:
82
+ *
83
+ * The above copyright notice and this permission notice shall be included in all
84
+ * copies or substantial portions of the Software.
85
+ *
86
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
87
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
88
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
89
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
90
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
91
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
92
+ * SOFTWARE.
93
+ *
94
+ *)
95
+
96
+ tslib/tslib.js:
97
+ (*! *****************************************************************************
98
+ Copyright (c) Microsoft Corporation.
99
+
100
+ Permission to use, copy, modify, and/or distribute this software for any
101
+ purpose with or without fee is hereby granted.
102
+
103
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
104
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
105
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
106
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
107
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
108
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
109
+ PERFORMANCE OF THIS SOFTWARE.
110
+ ***************************************************************************** *)
111
+
43
112
  @noble/hashes/esm/utils.js:
44
113
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
45
114
 
@@ -70,6 +139,72 @@ a=ice-pwd:`+t+e),r}var Ba=X("libp2p-webrtc-noise:");function Ju(r,t,e){let n=r.t
70
139
  @noble/curves/esm/secp256k1.js:
71
140
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
72
141
 
142
+ pvutils/build/utils.es.js:
143
+ (*!
144
+ Copyright (c) Peculiar Ventures, LLC
145
+ *)
146
+
147
+ asn1js/build/index.es.js:
148
+ (*!
149
+ * Copyright (c) 2014, GMO GlobalSign
150
+ * Copyright (c) 2015-2022, Peculiar Ventures
151
+ * All rights reserved.
152
+ *
153
+ * Author 2014-2019, Yury Strozhevsky
154
+ *
155
+ * Redistribution and use in source and binary forms, with or without modification,
156
+ * are permitted provided that the following conditions are met:
157
+ *
158
+ * * Redistributions of source code must retain the above copyright notice, this
159
+ * list of conditions and the following disclaimer.
160
+ *
161
+ * * Redistributions in binary form must reproduce the above copyright notice, this
162
+ * list of conditions and the following disclaimer in the documentation and/or
163
+ * other materials provided with the distribution.
164
+ *
165
+ * * Neither the name of the copyright holder nor the names of its
166
+ * contributors may be used to endorse or promote products derived from
167
+ * this software without specific prior written permission.
168
+ *
169
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
170
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
171
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
172
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
173
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
174
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
175
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
176
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
177
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
178
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
179
+ *
180
+ *)
181
+
182
+ @peculiar/x509/build/x509.es.js:
183
+ (*!
184
+ * MIT License
185
+ *
186
+ * Copyright (c) Peculiar Ventures. All rights reserved.
187
+ *
188
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
189
+ * of this software and associated documentation files (the "Software"), to deal
190
+ * in the Software without restriction, including without limitation the rights
191
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
192
+ * copies of the Software, and to permit persons to whom the Software is
193
+ * furnished to do so, subject to the following conditions:
194
+ *
195
+ * The above copyright notice and this permission notice shall be included in all
196
+ * copies or substantial portions of the Software.
197
+ *
198
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
199
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
200
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
201
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
202
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
203
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
204
+ * SOFTWARE.
205
+ *
206
+ *)
207
+
73
208
  @noble/ciphers/esm/utils.js:
74
209
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
75
210
  */