nostr-web-components
Version:
collection of web components that provide quick access to basic nostr things
7 lines (5 loc) • 84.6 kB
JavaScript
var nostr_picture=(function(){"use strict";var Ar=Object.defineProperty;var Or=(le,F,be)=>F in le?Ar(le,F,{enumerable:!0,configurable:!0,writable:!0,value:be}):le[F]=be;var h=(le,F,be)=>Or(le,typeof F!="symbol"?F+"":F,be);function le(i,e=100){let t,n,r;function s(){const c=Date.now()-n;c<e&&c>=0?t=setTimeout(s,e-c):(t=void 0,i(...r))}return function(...c){n=Date.now(),r=c,t||(t=setTimeout(s,e))}}const F="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";function be(i){const e=i.target;console.warn("error loading image",i),e.src!==F&&(e.src=F)}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kn(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ze(i,e=""){if(!Number.isSafeInteger(i)||i<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${i}`)}}function q(i,e,t=""){const n=kn(i),r=i==null?void 0:i.length,s=e!==void 0;if(!n||s&&r!==e){const c=t&&`"${t}" `,o=s?` of length ${e}`:"",a=n?`length=${r}`:`type=${typeof i}`;throw new Error(c+"expected Uint8Array"+o+", got "+a)}return i}function vt(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function _n(i,e){q(i,void 0,"digestInto() output");const t=e.outputLen;if(i.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Ke(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}function je(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Y(i,e){return i<<32-e|i>>>e}const xt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pn=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function B(i){if(q(i),xt)return i.toHex();let e="";for(let t=0;t<i.length;t++)e+=Pn[i[t]];return e}const ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function St(i){if(i>=ne._0&&i<=ne._9)return i-ne._0;if(i>=ne.A&&i<=ne.F)return i-(ne.A-10);if(i>=ne.a&&i<=ne.f)return i-(ne.a-10)}function Z(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);if(xt)return Uint8Array.fromHex(i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(t);for(let r=0,s=0;r<t;r++,s+=2){const c=St(i.charCodeAt(s)),o=St(i.charCodeAt(s+1));if(c===void 0||o===void 0){const a=i[s]+i[s+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+s)}n[r]=c*16+o}return n}function _e(...i){let e=0;for(let n=0;n<i.length;n++){const r=i[n];q(r),e+=r.length}const t=new Uint8Array(e);for(let n=0,r=0;n<i.length;n++){const s=i[n];t.set(s,r),r+=s.length}return t}function Bn(i,e={}){const t=(r,s)=>i(s).update(r).digest(),n=i(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>i(r),Object.assign(t,e),Object.freeze(t)}function Rt(i=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(i))}const Cn=i=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,i])});function In(i,e,t){return i&e^~i&t}function $n(i,e,t){return i&e^i&t^e&t}class Hn{constructor(e,t,n,r){h(this,"blockLen");h(this,"outputLen");h(this,"padOffset");h(this,"isLE");h(this,"buffer");h(this,"view");h(this,"finished",!1);h(this,"length",0);h(this,"pos",0);h(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=je(this.buffer)}update(e){vt(this),q(e);const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let c=0;c<s;){const o=Math.min(r-this.pos,s-c);if(o===r){const a=je(e);for(;r<=s-c;c+=r)this.process(a,c);continue}n.set(e.subarray(c,c+o),this.pos),this.pos+=o,c+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){vt(this),_n(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:c}=this;t[c++]=128,Ke(this.buffer.subarray(c)),this.padOffset>r-c&&(this.process(n,0),c=0);for(let l=c;l<r;l++)t[l]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);const o=je(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)o.setUint32(4*l,f[l],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:s,destroyed:c,pos:o}=this;return e.destroyed=c,e.finished=s,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const re=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ln=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),se=new Uint32Array(64);class Nn extends Hn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:s,F:c,G:o,H:a}=this;return[e,t,n,r,s,c,o,a]}set(e,t,n,r,s,c,o,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=c|0,this.G=o|0,this.H=a|0}process(e,t){for(let l=0;l<16;l++,t+=4)se[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){const b=se[l-15],d=se[l-2],y=Y(b,7)^Y(b,18)^b>>>3,w=Y(d,17)^Y(d,19)^d>>>10;se[l]=w+se[l-7]+y+se[l-16]|0}let{A:n,B:r,C:s,D:c,E:o,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const b=Y(o,6)^Y(o,11)^Y(o,25),d=f+b+In(o,a,u)+Ln[l]+se[l]|0,w=(Y(n,2)^Y(n,13)^Y(n,22))+$n(n,r,s)|0;f=u,u=a,a=o,o=c+d|0,c=s,s=r,r=n,n=d+w|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,c=c+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,r,s,c,o,a,u,f)}roundClean(){Ke(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Ke(this.buffer)}}class qn extends Nn{constructor(){super(32);h(this,"A",re[0]|0);h(this,"B",re[1]|0);h(this,"C",re[2]|0);h(this,"D",re[3]|0);h(this,"E",re[4]|0);h(this,"F",re[5]|0);h(this,"G",re[6]|0);h(this,"H",re[7]|0)}}const Pe=Bn(()=>new qn,Cn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ze=BigInt(0),Ye=BigInt(1);function Tt(i,e=""){if(typeof i!="boolean"){const t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof i)}return i}function Mn(i){if(typeof i=="bigint"){if(!Vn(i))throw new Error("positive bigint expected, got "+i)}else Ze(i);return i}function At(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?ze:BigInt("0x"+i)}function Ge(i){return At(B(i))}function Ot(i){return At(B(Un(q(i)).reverse()))}function Je(i,e){Ze(e),i=Mn(i);const t=Z(i.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function kt(i,e){return Je(i,e).reverse()}function Un(i){return Uint8Array.from(i)}function Wn(i){return Uint8Array.from(i,(e,t)=>{const n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${i[t]}" with code ${n} at position ${t}`);return n})}const Vn=i=>typeof i=="bigint"&&ze<=i;function Dn(i){let e;for(e=0;i>ze;i>>=Ye,e+=1);return e}const _t=i=>(Ye<<BigInt(i))-Ye;function Pt(i,e={},t={}){if(!i||typeof i!="object")throw new Error("expected valid options object");function n(s,c,o){const a=i[s];if(o&&a===void 0)return;const u=typeof a;if(u!==c||a===null)throw new Error(`param "${s}" is invalid: expected ${c}, got ${u}`)}const r=(s,c)=>Object.entries(s).forEach(([o,a])=>n(o,a,c));r(e,!1),r(t,!0)}function Bt(i){const e=new WeakMap;return(t,...n)=>{const r=e.get(t);if(r!==void 0)return r;const s=i(t,...n);return e.set(t,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const M=BigInt(0),L=BigInt(1),ue=BigInt(2),Ct=BigInt(3),It=BigInt(4),$t=BigInt(5),Fn=BigInt(7),Ht=BigInt(8),Zn=BigInt(9),Lt=BigInt(16);function K(i,e){const t=i%e;return t>=M?t:e+t}function W(i,e,t){let n=i;for(;e-- >M;)n*=n,n%=t;return n}function Nt(i,e){if(i===M)throw new Error("invert: expected non-zero number");if(e<=M)throw new Error("invert: expected positive modulus, got "+e);let t=K(i,e),n=e,r=M,s=L;for(;t!==M;){const o=n/t,a=n%t,u=r-s*o;n=t,t=a,r=s,s=u}if(n!==L)throw new Error("invert: does not exist");return K(r,e)}function Xe(i,e,t){if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function qt(i,e){const t=(i.ORDER+L)/It,n=i.pow(e,t);return Xe(i,n,e),n}function Kn(i,e){const t=(i.ORDER-$t)/Ht,n=i.mul(e,ue),r=i.pow(n,t),s=i.mul(e,r),c=i.mul(i.mul(s,ue),r),o=i.mul(s,i.sub(c,i.ONE));return Xe(i,o,e),o}function jn(i){const e=Be(i),t=Mt(i),n=t(e,e.neg(e.ONE)),r=t(e,n),s=t(e,e.neg(n)),c=(i+Fn)/Lt;return(o,a)=>{let u=o.pow(a,c),f=o.mul(u,n);const l=o.mul(u,r),b=o.mul(u,s),d=o.eql(o.sqr(f),a),y=o.eql(o.sqr(l),a);u=o.cmov(u,f,d),f=o.cmov(b,l,y);const w=o.eql(o.sqr(f),a),m=o.cmov(u,f,w);return Xe(o,m,a),m}}function Mt(i){if(i<Ct)throw new Error("sqrt is not defined for small field");let e=i-L,t=0;for(;e%ue===M;)e/=ue,t++;let n=ue;const r=Be(i);for(;Wt(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return qt;let s=r.pow(n,e);const c=(e+L)/ue;return function(a,u){if(a.is0(u))return u;if(Wt(a,u)!==1)throw new Error("Cannot find square root");let f=t,l=a.mul(a.ONE,s),b=a.pow(u,e),d=a.pow(u,c);for(;!a.eql(b,a.ONE);){if(a.is0(b))return a.ZERO;let y=1,w=a.sqr(b);for(;!a.eql(w,a.ONE);)if(y++,w=a.sqr(w),y===f)throw new Error("Cannot find square root");const m=L<<BigInt(f-y-1),T=a.pow(l,m);f=y,l=a.sqr(T),b=a.mul(b,l),d=a.mul(d,T)}return d}}function zn(i){return i%It===Ct?qt:i%Ht===$t?Kn:i%Lt===Zn?jn(i):Mt(i)}const Yn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gn(i){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Yn.reduce((n,r)=>(n[r]="function",n),e);return Pt(i,t),i}function Jn(i,e,t){if(t<M)throw new Error("invalid exponent, negatives unsupported");if(t===M)return i.ONE;if(t===L)return e;let n=i.ONE,r=e;for(;t>M;)t&L&&(n=i.mul(n,r)),r=i.sqr(r),t>>=L;return n}function Ut(i,e,t=!1){const n=new Array(e.length).fill(t?i.ZERO:void 0),r=e.reduce((c,o,a)=>i.is0(o)?c:(n[a]=c,i.mul(c,o)),i.ONE),s=i.inv(r);return e.reduceRight((c,o,a)=>i.is0(o)?c:(n[a]=i.mul(c,n[a]),i.mul(c,o)),s),n}function Wt(i,e){const t=(i.ORDER-L)/ue,n=i.pow(e,t),r=i.eql(n,i.ONE),s=i.eql(n,i.ZERO),c=i.eql(n,i.neg(i.ONE));if(!r&&!s&&!c)throw new Error("invalid Legendre symbol result");return r?1:s?0:-1}function Xn(i,e){e!==void 0&&Ze(e);const t=e!==void 0?e:i.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}class Qn{constructor(e,t={}){h(this,"ORDER");h(this,"BITS");h(this,"BYTES");h(this,"isLE");h(this,"ZERO",M);h(this,"ONE",L);h(this,"_lengths");h(this,"_sqrt");h(this,"_mod");var c;if(e<=M)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=(c=t.allowedLengths)==null?void 0:c.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:s}=Xn(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return K(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return M<=e&&e<this.ORDER}is0(e){return e===M}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&L)===L}neg(e){return K(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return K(e*e,this.ORDER)}add(e,t){return K(e+t,this.ORDER)}sub(e,t){return K(e-t,this.ORDER)}mul(e,t){return K(e*t,this.ORDER)}pow(e,t){return Jn(this,e,t)}div(e,t){return K(e*Nt(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Nt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=zn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?kt(e,this.BYTES):Je(e,this.BYTES)}fromBytes(e,t=!1){q(e);const{_lengths:n,BYTES:r,isLE:s,ORDER:c,_mod:o}=this;if(n){if(!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const u=new Uint8Array(r);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=s?Ot(e):Ge(e);if(o&&(a=K(a,c)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Ut(this,e)}cmov(e,t,n){return n?t:e}}function Be(i,e={}){return new Qn(i,e)}function Vt(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function ei(i){const e=Vt(i);return e+Math.ceil(e/2)}function ti(i,e,t=!1){q(i);const n=i.length,r=Vt(e),s=ei(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const c=t?Ot(i):Ge(i),o=K(c,e-L)+L;return t?kt(o,r):Je(o,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const we=BigInt(0),he=BigInt(1);function Ce(i,e){const t=e.negate();return i?t:e}function Dt(i,e){const t=Ut(i.Fp,e.map(n=>n.Z));return e.map((n,r)=>i.fromAffine(n.toAffine(t[r])))}function Ft(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Qe(i,e){Ft(i,e);const t=Math.ceil(e/i)+1,n=2**(i-1),r=2**i,s=_t(i),c=BigInt(i);return{windows:t,windowSize:n,mask:s,maxNumber:r,shiftBy:c}}function Zt(i,e,t){const{windowSize:n,mask:r,maxNumber:s,shiftBy:c}=t;let o=Number(i&r),a=i>>c;o>n&&(o-=s,a+=he);const u=e*n,f=u+Math.abs(o)-1,l=o===0,b=o<0,d=e%2!==0;return{nextN:a,offset:f,isZero:l,isNeg:b,isNegF:d,offsetF:u}}const et=new WeakMap,Kt=new WeakMap;function tt(i){return Kt.get(i)||1}function jt(i){if(i!==we)throw new Error("invalid wNAF")}class ni{constructor(e,t){h(this,"BASE");h(this,"ZERO");h(this,"Fn");h(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>we;)t&he&&(n=n.add(r)),r=r.double(),t>>=he;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Qe(t,this.bits),s=[];let c=e,o=c;for(let a=0;a<n;a++){o=c,s.push(o);for(let u=1;u<r;u++)o=o.add(c),s.push(o);c=o.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const c=Qe(e,this.bits);for(let o=0;o<c.windows;o++){const{nextN:a,offset:u,isZero:f,isNeg:l,isNegF:b,offsetF:d}=Zt(n,o,c);n=a,f?s=s.add(Ce(b,t[d])):r=r.add(Ce(l,t[u]))}return jt(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=Qe(e,this.bits);for(let c=0;c<s.windows&&n!==we;c++){const{nextN:o,offset:a,isZero:u,isNeg:f}=Zt(n,c,s);if(n=o,!u){const l=t[a];r=r.add(f?l.negate():l)}}return jt(n),r}getPrecomputes(e,t,n){let r=et.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(r=n(r)),et.set(t,r))),r}cached(e,t,n){const r=tt(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=tt(e);return s===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Ft(t,this.bits),Kt.set(e,t),et.delete(e)}hasCache(e){return tt(e)!==1}}function ii(i,e,t,n){let r=e,s=i.ZERO,c=i.ZERO;for(;t>we||n>we;)t&he&&(s=s.add(r)),n&he&&(c=c.add(r)),r=r.double(),t>>=he,n>>=he;return{p1:s,p2:c}}function zt(i,e,t){if(e){if(e.ORDER!==i)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Gn(e),e}else return Be(i,{isLE:t})}function ri(i,e,t={},n){if(n===void 0&&(n=i==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${i} CURVE object`);for(const a of["p","n","h"]){const u=e[a];if(!(typeof u=="bigint"&&u>we))throw new Error(`CURVE.${a} must be positive bigint`)}const r=zt(e.p,t.Fp,n),s=zt(e.n,t.Fn,n),o=["Gx","Gy","a","b"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function si(i,e){return function(n){const r=i(n);return{secretKey:r,publicKey:e(r)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yt=(i,e)=>(i+(i>=0?e:-e)/ci)/e;function oi(i,e,t){const[[n,r],[s,c]]=e,o=Yt(c*i,t),a=Yt(-r*i,t);let u=i-o*n-a*s,f=-o*r-a*c;const l=u<ve,b=f<ve;l&&(u=-u),b&&(f=-f);const d=_t(Math.ceil(Dn(t)/2))+Ie;if(u<ve||u>=d||f<ve||f>=d)throw new Error("splitScalar (endomorphism): failed, k="+i);return{k1neg:l,k1:u,k2neg:b,k2:f}}const ve=BigInt(0),Ie=BigInt(1),ci=BigInt(2),$e=BigInt(3),ai=BigInt(4);function li(i,e={}){const t=ri("weierstrass",i,e),{Fp:n,Fn:r}=t;let s=t.CURVE;const{h:c,n:o}=s;Pt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:a}=e;if(a&&(!n.is0(s.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=hi(n,r);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(k,g,p){const{x:v,y:x}=g.toAffine(),_=n.toBytes(v);if(Tt(p,"isCompressed"),p){f();const A=!n.isOdd(x);return _e(ui(A),_)}else return _e(Uint8Array.of(4),_,n.toBytes(x))}function b(k){q(k,void 0,"Point");const{publicKey:g,publicKeyUncompressed:p}=u,v=k.length,x=k[0],_=k.subarray(1);if(v===g&&(x===2||x===3)){const A=n.fromBytes(_);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");const S=w(A);let E;try{E=n.sqrt(S)}catch(D){const H=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}f();const R=n.isOdd(E);return(x&1)===1!==R&&(E=n.neg(E)),{x:A,y:E}}else if(v===p&&x===4){const A=n.BYTES,S=n.fromBytes(_.subarray(0,A)),E=n.fromBytes(_.subarray(A,A*2));if(!m(S,E))throw new Error("bad point: is not on curve");return{x:S,y:E}}else throw new Error(`bad point: got length ${v}, expected compressed=${g} or uncompressed=${p}`)}const d=e.toBytes||l,y=e.fromBytes||b;function w(k){const g=n.sqr(k),p=n.mul(g,k);return n.add(n.add(p,n.mul(k,s.a)),s.b)}function m(k,g){const p=n.sqr(g),v=w(k);return n.eql(p,v)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const T=n.mul(n.pow(s.a,$e),ai),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(T,I)))throw new Error("bad curve params: a or b");function U(k,g,p=!1){if(!n.isValid(g)||p&&n.is0(g))throw new Error(`bad point coordinate ${k}`);return g}function ee(k){if(!(k instanceof ye))throw new Error("Weierstrass Point expected")}function $(k){if(!a||!a.basises)throw new Error("no endo");return oi(k,a.basises,r.ORDER)}const V=Bt((k,g)=>{const{X:p,Y:v,Z:x}=k;if(n.eql(x,n.ONE))return{x:p,y:v};const _=k.is0();g==null&&(g=_?n.ONE:n.inv(x));const A=n.mul(p,g),S=n.mul(v,g),E=n.mul(x,g);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:A,y:S}}),Tr=Bt(k=>{if(k.is0()){if(e.allowInfinityPoint&&!n.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:p}=k.toAffine();if(!n.isValid(g)||!n.isValid(p))throw new Error("bad point: x or y not field elements");if(!m(g,p))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(k,g,p,v,x){return p=new ye(n.mul(p.X,k),p.Y,p.Z),g=Ce(v,g),p=Ce(x,p),g.add(p)}const C=class C{constructor(g,p,v){h(this,"X");h(this,"Y");h(this,"Z");this.X=U("x",g),this.Y=U("y",p,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){const{x:p,y:v}=g||{};if(!g||!n.isValid(p)||!n.isValid(v))throw new Error("invalid affine point");if(g instanceof C)throw new Error("projective point not allowed");return n.is0(p)&&n.is0(v)?C.ZERO:new C(p,v,n.ONE)}static fromBytes(g){const p=C.fromAffine(y(q(g,void 0,"point")));return p.assertValidity(),p}static fromHex(g){return C.fromBytes(Z(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,p=!0){return ke.createCache(this,g),p||this.multiply($e),this}assertValidity(){Tr(this)}hasEvenY(){const{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){ee(g);const{X:p,Y:v,Z:x}=this,{X:_,Y:A,Z:S}=g,E=n.eql(n.mul(p,S),n.mul(_,x)),R=n.eql(n.mul(v,S),n.mul(A,x));return E&&R}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){const{a:g,b:p}=s,v=n.mul(p,$e),{X:x,Y:_,Z:A}=this;let S=n.ZERO,E=n.ZERO,R=n.ZERO,O=n.mul(x,x),D=n.mul(_,_),H=n.mul(A,A),P=n.mul(x,_);return P=n.add(P,P),R=n.mul(x,A),R=n.add(R,R),S=n.mul(g,R),E=n.mul(v,H),E=n.add(S,E),S=n.sub(D,E),E=n.add(D,E),E=n.mul(S,E),S=n.mul(P,S),R=n.mul(v,R),H=n.mul(g,H),P=n.sub(O,H),P=n.mul(g,P),P=n.add(P,R),R=n.add(O,O),O=n.add(R,O),O=n.add(O,H),O=n.mul(O,P),E=n.add(E,O),H=n.mul(_,A),H=n.add(H,H),O=n.mul(H,P),S=n.sub(S,O),R=n.mul(H,D),R=n.add(R,R),R=n.add(R,R),new C(S,E,R)}add(g){ee(g);const{X:p,Y:v,Z:x}=this,{X:_,Y:A,Z:S}=g;let E=n.ZERO,R=n.ZERO,O=n.ZERO;const D=s.a,H=n.mul(s.b,$e);let P=n.mul(p,_),j=n.mul(v,A),z=n.mul(x,S),Ee=n.add(p,v),N=n.add(_,A);Ee=n.mul(Ee,N),N=n.add(P,j),Ee=n.sub(Ee,N),N=n.add(p,x);let te=n.add(_,S);return N=n.mul(N,te),te=n.add(P,z),N=n.sub(N,te),te=n.add(v,x),E=n.add(A,S),te=n.mul(te,E),E=n.add(j,z),te=n.sub(te,E),O=n.mul(D,N),E=n.mul(H,z),O=n.add(E,O),E=n.sub(j,O),O=n.add(j,O),R=n.mul(E,O),j=n.add(P,P),j=n.add(j,P),z=n.mul(D,z),N=n.mul(H,N),j=n.add(j,z),z=n.sub(P,z),z=n.mul(D,z),N=n.add(N,z),P=n.mul(j,N),R=n.add(R,P),P=n.mul(te,N),E=n.mul(Ee,E),E=n.sub(E,P),P=n.mul(Ee,j),O=n.mul(te,O),O=n.add(O,P),new C(E,R,O)}subtract(g){return this.add(g.negate())}is0(){return this.equals(C.ZERO)}multiply(g){const{endo:p}=e;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let v,x;const _=A=>ke.cached(this,A,S=>Dt(C,S));if(p){const{k1neg:A,k1:S,k2neg:E,k2:R}=$(g),{p:O,f:D}=_(S),{p:H,f:P}=_(R);x=D.add(P),v=Tn(p.beta,O,H,A,E)}else{const{p:A,f:S}=_(g);v=A,x=S}return Dt(C,[v,x])[0]}multiplyUnsafe(g){const{endo:p}=e,v=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===ve||v.is0())return C.ZERO;if(g===Ie)return v;if(ke.hasCache(this))return this.multiply(g);if(p){const{k1neg:x,k1:_,k2neg:A,k2:S}=$(g),{p1:E,p2:R}=ii(C,v,_,S);return Tn(p.beta,E,R,x,A)}else return ke.unsafe(v,g)}toAffine(g){return V(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return c===Ie?!0:g?g(C,this):ke.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:g}=e;return c===Ie?this:g?g(C,this):this.multiplyUnsafe(c)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}toBytes(g=!0){return Tt(g,"isCompressed"),this.assertValidity(),d(C,this,g)}toHex(g=!0){return B(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};h(C,"BASE",new C(s.Gx,s.Gy,n.ONE)),h(C,"ZERO",new C(n.ZERO,n.ONE,n.ZERO)),h(C,"Fp",n),h(C,"Fn",r);let ye=C;const An=r.BITS,ke=new ni(ye,e.endo?Math.ceil(An/2):An);return ye.BASE.precompute(8),ye}function ui(i){return Uint8Array.of(i?2:3)}function hi(i,e){return{secretKey:e.BYTES,publicKey:1+i.BYTES,publicKeyUncompressed:1+2*i.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const He={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},fi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},di=BigInt(0),nt=BigInt(2);function yi(i){const e=He.p,t=BigInt(3),n=BigInt(6),r=BigInt(11),s=BigInt(22),c=BigInt(23),o=BigInt(44),a=BigInt(88),u=i*i*i%e,f=u*u*i%e,l=W(f,t,e)*f%e,b=W(l,t,e)*f%e,d=W(b,nt,e)*u%e,y=W(d,r,e)*d%e,w=W(y,s,e)*y%e,m=W(w,o,e)*w%e,T=W(m,a,e)*m%e,I=W(T,o,e)*w%e,U=W(I,t,e)*f%e,ee=W(U,c,e)*y%e,$=W(ee,n,e)*u%e,V=W($,nt,e);if(!Le.eql(Le.sqr(V),i))throw new Error("Cannot find square root");return V}const Le=Be(He.p,{sqrt:yi}),ge=li(He,{Fp:Le,endo:fi}),Gt={};function Ne(i,...e){let t=Gt[i];if(t===void 0){const n=Pe(Wn(i));t=_e(n,n),Gt[i]=t}return Pe(_e(t,...e))}const it=i=>i.toBytes(!0).slice(1),rt=i=>i%nt===di;function st(i){const{Fn:e,BASE:t}=ge,n=e.fromBytes(i),r=t.multiply(n);return{scalar:rt(r.y)?n:e.neg(n),bytes:it(r)}}function Jt(i){const e=Le;if(!e.isValidNot0(i))throw new Error("invalid x: Fail if x ≥ p");const t=e.create(i*i),n=e.create(t*i+BigInt(7));let r=e.sqrt(n);rt(r)||(r=e.neg(r));const s=ge.fromAffine({x:i,y:r});return s.assertValidity(),s}const xe=Ge;function Xt(...i){return ge.Fn.create(xe(Ne("BIP0340/challenge",...i)))}function Qt(i){return st(i).bytes}function bi(i,e,t=Rt(32)){const{Fn:n}=ge,r=q(i,void 0,"message"),{bytes:s,scalar:c}=st(e),o=q(t,32,"auxRand"),a=n.toBytes(c^xe(Ne("BIP0340/aux",o))),u=Ne("BIP0340/nonce",a,s,r),{bytes:f,scalar:l}=st(u),b=Xt(f,s,r),d=new Uint8Array(64);if(d.set(f,0),d.set(n.toBytes(n.create(l+b*c)),32),!en(d,r,s))throw new Error("sign: Invalid signature produced");return d}function en(i,e,t){const{Fp:n,Fn:r,BASE:s}=ge,c=q(i,64,"signature"),o=q(e,void 0,"message"),a=q(t,32,"publicKey");try{const u=Jt(xe(a)),f=xe(c.subarray(0,32));if(!n.isValidNot0(f))return!1;const l=xe(c.subarray(32,64));if(!r.isValidNot0(l))return!1;const b=Xt(r.toBytes(f),it(u),o),d=s.multiplyUnsafe(l).add(u.multiplyUnsafe(r.neg(b))),{x:y,y:w}=d.toAffine();return!(d.is0()||!rt(w)||y!==f)}catch{return!1}}const G=(()=>{const t=(n=Rt(48))=>ti(n,He.n);return{keygen:si(t,Qt),getPublicKey:Qt,sign:bi,verify:en,Point:ge,utils:{randomSecretKey:t,taggedHash:Ne,lift_x:Jt,pointToBytes:it},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),fe=Symbol("verified"),wi=i=>i instanceof Object;function gi(i){if(!wi(i)||typeof i.kind!="number"||typeof i.content!="string"||typeof i.created_at!="number"||typeof i.pubkey!="string"||!i.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(i.tags))return!1;for(let e=0;e<i.tags.length;e++){let t=i.tags[e];if(!Array.isArray(t))return!1;for(let n=0;n<t.length;n++)if(typeof t[n]!="string")return!1}return!0}const qe=new TextDecoder("utf-8"),mi=new TextEncoder;function Se(i){try{i.indexOf("://")===-1&&(i="wss://"+i);let e=new URL(i);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${i}`)}}let pi=class{generateSecretKey(){return G.utils.randomSecretKey()}getPublicKey(e){return B(G.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=B(G.getPublicKey(t)),n.id=ot(n),n.sig=B(G.sign(Z(ot(n)),t)),n[fe]=!0,n}verifyEvent(e){if(typeof e[fe]=="boolean")return e[fe];const t=ot(e);if(t!==e.id)return e[fe]=!1,!1;try{const n=G.verify(Z(e.sig),Z(t),Z(e.pubkey));return e[fe]=n,n}catch{return e[fe]=!1,!1}}};function Ei(i){if(!gi(i))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,i.pubkey,i.created_at,i.kind,i.tags,i.content])}function ot(i){let e=Pe(mi.encode(Ei(i)));return B(e)}const Me=new pi;Me.generateSecretKey,Me.getPublicKey,Me.finalizeEvent;const vi=Me.verifyEvent,xi=22242;function Si(i,e){if(i.ids&&i.ids.indexOf(e.id)===-1||i.kinds&&i.kinds.indexOf(e.kind)===-1||i.authors&&i.authors.indexOf(e.pubkey)===-1)return!1;for(let t in i)if(t[0]==="#"){let n=t.slice(1),r=i[`#${n}`];if(r&&!e.tags.find(([s,c])=>s===t.slice(1)&&r.indexOf(c)!==-1))return!1}return!(i.since&&e.created_at<i.since||i.until&&e.created_at>i.until)}function Ri(i,e){for(let t=0;t<i.length;t++)if(Si(i[t],e))return!0;return!1}function Ti(i,e){let t=e.length+3,n=i.indexOf(`"${e}":`)+t,r=i.slice(n).indexOf('"')+n+1;return i.slice(r,r+64)}function Ai(i){let e=i.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let t=i.slice(e+7+1).indexOf('"');if(t===-1)return null;let n=e+7+1+t,r=i.slice(n+1,80).indexOf('"');if(r===-1)return null;let s=n+1+r;return i.slice(n+1,s)}function Oi(i,e){return{kind:xi,created_at:Math.floor(Date.now()/1e3),tags:[["relay",i],["challenge",e]],content:""}}let tn=class extends Error{constructor(e,t){super(`Tried to send message '${e} on a closed connection to ${t}.`),this.name="SendingOnClosedConnection"}},ki=class On{constructor(e,t){h(this,"url");h(this,"_connected",!1);h(this,"onclose",null);h(this,"onnotice",e=>console.debug(`NOTICE from ${this.url}: ${e}`));h(this,"onauth");h(this,"baseEoseTimeout",4400);h(this,"publishTimeout",4400);h(this,"pingFrequency",29e3);h(this,"pingTimeout",2e4);h(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);h(this,"openSubs",new Map);h(this,"enablePing");h(this,"enableReconnect");h(this,"idleSince",Date.now());h(this,"ongoingOperations",0);h(this,"reconnectTimeoutHandle");h(this,"pingIntervalHandle");h(this,"reconnectAttempts",0);h(this,"skipReconnection",!1);h(this,"connectionPromise");h(this,"openCountRequests",new Map);h(this,"openEventPublishes",new Map);h(this,"ws");h(this,"challenge");h(this,"authPromise");h(this,"serial",0);h(this,"verifyEvent");h(this,"_WebSocket");this.url=Se(e),this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation||WebSocket,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1}static async connect(e,t){const n=new On(e,t);return await n.connect(t),n}closeAllSubscriptions(e){for(let[t,n]of this.openSubs)n.close(e);this.openSubs.clear();for(let[t,n]of this.openEventPublishes)n.reject(new Error(e));this.openEventPublishes.clear();for(let[t,n]of this.openCountRequests)n.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){var t;this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():((t=this.onclose)==null||t.call(this),this.closeAllSubscriptions(e))}async connect(e){let t;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{e!=null&&e.timeout&&(t=setTimeout(()=>{var s;r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,(s=this.onclose)==null||s.call(this),this.handleHardClose("relay connection timed out")},e.timeout)),e!=null&&e.abort&&(e.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(s){clearTimeout(t),r(s);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(t),this._connected=!0;const s=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const c of this.openSubs.values()){if(c.eosed=!1,s)for(let o=0;o<c.filters.length;o++)c.lastEmitted&&(c.filters[o].since=c.lastEmitted+1);c.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{var s;clearTimeout(t),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,(s=this.onclose)==null||s.call(this),this.handleHardClose("relay connection failed")},this.ws.onclose=s=>{clearTimeout(t),r(s.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,t)=>{if(!this.connectionPromise)return t(new Error(`no connection to ${this.url}, can't ping`));try{const n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),n.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){t(n)}})}async pingpong(){var e,t,n;((e=this.ws)==null?void 0:e.readyState)===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(s=>setTimeout(()=>s(!1),this.pingTimeout))])||((t=this.ws)==null?void 0:t.readyState)===this._WebSocket.OPEN&&((n=this.ws)==null||n.close()))}async send(e){if(!this.connectionPromise)throw new tn(e,this.url);this.connectionPromise.then(()=>{var t;(t=this.ws)==null||t.send(e)})}async auth(e){const t=this.challenge;if(!t)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let s=await e(Oi(this.url,t)),c=setTimeout(()=>{let o=this.openEventPublishes.get(s.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(s.id))},this.publishTimeout);this.openEventPublishes.set(s.id,{resolve:n,reject:r,timeout:c}),this.send('["AUTH",'+JSON.stringify(s)+"]")}catch(s){console.warn("subscribe auth function failed:",s)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const t=new Promise((n,r)=>{const s=setTimeout(()=>{const c=this.openEventPublishes.get(e.id);c&&(c.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:n,reject:r,timeout:s})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),t}async count(e,t){this.serial++;const n=(t==null?void 0:t.id)||"count:"+this.serial,r=new Promise((s,c)=>{this.openCountRequests.set(n,{resolve:s,reject:c})});return this.send('["COUNT","'+n+'",'+JSON.stringify(e).substring(1)),r}subscribe(e,t){t.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const n=this.prepareSubscription(e,t);return n.fire(),t.abort&&(t.abort.onabort=()=>n.close(String(t.abort.reason||"<aborted>"))),n}prepareSubscription(e,t){this.serial++;const n=t.id||(t.label?t.label+":":"sub:")+this.serial,r=new _i(this,n,e,t);return this.openSubs.set(n,r),r}close(){var e,t,n;this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,(e=this.onclose)==null||e.call(this),((t=this.ws)==null?void 0:t.readyState)===this._WebSocket.OPEN&&((n=this.ws)==null||n.close())}_onmessage(e){var r,s,c;const t=e.data;if(!t)return;const n=Ai(t);if(n){const o=this.openSubs.get(n);if(!o)return;const a=Ti(t,"id"),u=(r=o.alreadyHaveEvent)==null?void 0:r.call(o,a);if((s=o.receivedEvent)==null||s.call(o,this,a),u)return}try{let o=JSON.parse(t);switch(o[0]){case"EVENT":{const a=this.openSubs.get(o[1]),u=o[2];this.verifyEvent(u)&&Ri(a.filters,u)&&a.onevent(u),(!a.lastEmitted||a.lastEmitted<u.created_at)&&(a.lastEmitted=u.created_at);return}case"COUNT":{const a=o[1],u=o[2],f=this.openCountRequests.get(a);f&&(f.resolve(u.count),this.openCountRequests.delete(a));return}case"EOSE":{const a=this.openSubs.get(o[1]);if(!a)return;a.receivedEose();return}case"OK":{const a=o[1],u=o[2],f=o[3],l=this.openEventPublishes.get(a);l&&(clearTimeout(l.timeout),u?l.resolve(f):l.reject(new Error(f)),this.openEventPublishes.delete(a));return}case"CLOSED":{const a=o[1],u=this.openSubs.get(a);if(!u)return;u.closed=!0,u.close(o[2]);return}case"NOTICE":{this.onnotice(o[1]);return}case"AUTH":{this.challenge=o[1],this.onauth&&this.auth(this.onauth);return}default:{const a=this.openSubs.get(o[1]);(c=a==null?void 0:a.oncustom)==null||c.call(a,o);return}}}catch(o){const[a,u,f]=JSON.parse(t);window.printer.maybe(f.pubkey,":: caught err",f,this.url,o);return}}},_i=class{constructor(e,t,n,r){h(this,"relay");h(this,"id");h(this,"lastEmitted");h(this,"closed",!1);h(this,"eosed",!1);h(this,"filters");h(this,"alreadyHaveEvent");h(this,"receivedEvent");h(this,"onevent");h(this,"oneose");h(this,"onclose");h(this,"oncustom");h(this,"eoseTimeout");h(this,"eoseTimeoutHandle");if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=n,this.id=t,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||e.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var e;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(e=this.oneose)==null||e.call(this))}close(e="closed by caller"){var t;if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(n){if(!(n instanceof tn))throw n}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),(t=this.onclose)==null||t.call(this,e)}};const Pi=i=>(i[fe]=!0,!0);let Bi=class{constructor(e){h(this,"relays",new Map);h(this,"seenOn",new Map);h(this,"trackRelays",!1);h(this,"verifyEvent");h(this,"enablePing");h(this,"enableReconnect");h(this,"automaticallyAuth");h(this,"trustedRelayURLs",new Set);h(this,"onRelayConnectionFailure");h(this,"onRelayConnectionSuccess");h(this,"allowConnectingToRelay");h(this,"maxWaitForConnection");h(this,"_WebSocket");this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,t){e=Se(e);let n=this.relays.get(e);if(n||(n=new ki(e,{verifyEvent:this.trustedRelayURLs.has(e)?Pi:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),n.onclose=()=>{this.relays.delete(e)},this.relays.set(e,n)),this.automaticallyAuth){const r=this.automaticallyAuth(e);r&&(n.onauth=r)}try{await n.connect({timeout:t==null?void 0:t.connectionTimeout,abort:t==null?void 0:t.abort})}catch(r){throw this.relays.delete(e),r}return n}close(e){e.map(Se).forEach(t=>{var n;(n=this.relays.get(t))==null||n.close(),this.relays.delete(t)})}subscribe(e,t,n){const r=[],s=[];for(let c=0;c<e.length;c++){const o=Se(e[c]);r.find(a=>a.url===o)||s.indexOf(o)===-1&&(s.push(o),r.push({url:o,filter:t}))}return this.subscribeMap(r,n)}subscribeMany(e,t,n){return this.subscribe(e,t,n)}subscribeMap(e,t){const n=new Map;for(const d of e){const{url:y,filter:w}=d;n.has(y)||n.set(y,[]),n.get(y).push(w)}const r=Array.from(n.entries()).map(([d,y])=>({url:d,filters:y}));this.trackRelays&&(t.receivedEvent=(d,y)=>{let w=this.seenOn.get(y);w||(w=new Set,this.seenOn.set(y,w)),w.add(d)});const s=new Set,c=[],o=[];let a=d=>{var y;o[d]||(o[d]=!0,o.filter(w=>w).length===r.length&&((y=t.oneose)==null||y.call(t),a=()=>{}))};const u=[];let f=(d,y)=>{var w;u[d]||(a(d),u[d]=y,u.filter(m=>m).length===r.length&&((w=t.onclose)==null||w.call(t,u),f=()=>{}))};const l=d=>{var w;if((w=t.alreadyHaveEvent)!=null&&w.call(t,d))return!0;const y=s.has(d);return s.add(d),y},b=Promise.all(r.map(async({url:d,filters:y},w)=>{var I,U,ee;if(((I=this.allowConnectingToRelay)==null?void 0:I.call(this,d,["read",y]))===!1){f(w,"connection skipped by allowConnectingToRelay");return}let m;try{m=await this.ensureRelay(d,{connectionTimeout:this.maxWaitForConnection<(t.maxWait||0)?Math.max(t.maxWait*.8,t.maxWait-1e3):this.maxWaitForConnection,abort:t.abort})}catch($){(U=this.onRelayConnectionFailure)==null||U.call(this,d),f(w,($==null?void 0:$.message)||String($));return}(ee=this.onRelayConnectionSuccess)==null||ee.call(this,d);let T=m.subscribe(y,{...t,oneose:()=>a(w),onclose:$=>{$.startsWith("auth-required: ")&&t.onauth?m.auth(t.onauth).then(()=>{m.subscribe(y,{...t,oneose:()=>a(w),onclose:V=>{f(w,V)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort})}).catch(V=>{f(w,`auth was required and attempted, but failed with: ${V}`)}):f(w,$)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort});c.push(T)}));return{async close(d){await b,c.forEach(y=>{y.close(d)})}}}subscribeEose(e,t,n){const r=this.subscribe(e,t,{...n,oneose(){r.close("closed automatically on eose")}});return r}subscribeManyEose(e,t,n){return this.subscribeEose(e,t,n)}async querySync(e,t,n){return new Promise(async r=>{const s=[];this.subscribeEose(e,t,{...n,onevent(c){s.push(c)},onclose(c){r(s)}})})}async get(e,t,n){t.limit=1;const r=await this.querySync(e,t,n);return r.sort((s,c)=>c.created_at-s.created_at),r[0]||null}publish(e,t,n){return e.map(Se).map(async(r,s,c)=>{var a,u;if(c.indexOf(r)!==s)return Promise.reject("duplicate url");if(((a=this.allowConnectingToRelay)==null?void 0:a.call(this,r,["write",t]))===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<((n==null?void 0:n.maxWait)||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n==null?void 0:n.abort})}catch(f){return(u=this.onRelayConnectionFailure)==null||u.call(this,r),"connection failure: "+String(f)}return o.publish(t).catch(async f=>{if(f instanceof Error&&f.message.startsWith("auth-required: ")&&(n!=null&&n.onauth))return await o.auth(n.onauth),o.publish(t);throw f}).then(f=>{if(this.trackRelays){let l=this.seenOn.get(t.id);l||(l=new Set,this.seenOn.set(t.id,l)),l.add(o)}return f})})}listConnectionStatus(){const e=new Map;return this.relays.forEach((t,n)=>e.set(n,t.connected)),e}destroy(){this.relays.forEach(e=>e.close()),this.relays=new Map}pruneIdleRelays(e=1e4){const t=[];for(const[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=e&&(this.relays.delete(n),t.push(n),r.close());return t}};var nn;try{nn=WebSocket}catch{}let Ci=class extends Bi{constructor(e){super({verifyEvent:vi,websocketImplementation:nn,maxWaitForConnection:3e3,...e})}};var Ii=Math.pow(2,8)-1,$i=Math.pow(2,16)-1,Hi=Math.pow(2,32)-1;const Li=function(i){var e=i-1;if(e<=Ii)return Uint8Array;if(e<=$i)return Uint16Array;if(e<=Hi)return Uint32Array;throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};function oe(i){if(this.capacity=i,typeof this.capacity!="number"||this.capacity<=0)throw new Error("mnemonist/lru-cache: capacity should be positive number.");if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw new Error("mnemonist/lru-cache: capacity should be a finite positive integer.");var e=Li(i);this.forward=new e(i),this.backward=new e(i),this.K=new Array(i),this.V=new Array(i),this.size=0,this.head=0,this.tail=0,this.items={}}oe.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},oe.prototype.splayOnTop=function(i){var e=this.head;if(this.head===i)return this;var t=this.backward[i],n=this.forward[i];return this.tail===i?this.tail=t:this.backward[n]=t,this.forward[t]=n,this.backward[e]=i,this.head=i,this.forward[i]=e,this},oe.prototype.set=function(i,e){var t=this.items[i];if(typeof t<"u"){this.splayOnTop(t),this.V[t]=e;return}this.size<this.capacity?t=this.size++:(t=this.tail,this.tail=this.backward[t],delete this.items[this.K[t]]),this.items[i]=t,this.K[t]=i,this.V[t]=e,this.forward[t]=this.head,this.backward[this.head]=t,this.head=t},oe.prototype.setpop=function(i,e){var t=null,n=null,r=this.items[i];return typeof r<"u"?(this.splayOnTop(r),t=this.V[r],this.V[r]=e,{evicted:!1,key:i,value:t}):(this.size<this.capacity?r=this.size++:(r=this.tail,this.tail=this.backward[r],t=this.V[r],n=this.K[r],delete this.items[n]),this.items[i]=r,this.K[r]=i,this.V[r]=e,this.forward[r]=this.head,this.backward[this.head]=r,this.head=r,n?{evicted:!0,key:n,value:t}:null)},oe.prototype.has=function(i){return i in this.items},oe.prototype.get=function(i){var e=this.items[i];if(!(typeof e>"u"))return this.splayOnTop(e),this.V[e]},oe.prototype.peek=function(i){var e=this.items[i];if(!(typeof e>"u"))return this.V[e]};class rn{constructor(e,t){h(this,"_batchLoadFn");h(this,"_maxBatchSize");h(this,"_cacheKeyFn");h(this,"_cacheMap");h(this,"_batch");if(typeof e!="function")throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${e}.`);this._batchLoadFn=e,this._maxBatchSize=(t==null?void 0:t.maxBatchSize)||1/0,this._cacheKeyFn=t==null?void 0:t.cacheKeyFn;const n=new oe(2e3);this._cacheMap={get:t.transformCacheHit?r=>{var s;return(s=n.get(r))==null?void 0:s.then(t.transformCacheHit)}:r=>n.get(r),set(r,s){return n.set(r,s)},delete(r){n.set(r,void 0)},clear(){n.clear()}},this._batch=null}load(e){if(e==null)throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(e)}.`);const t=Ni(this),n=this._cacheKeyFn(e),r=this._cacheMap.get(n);if(r){const c=t.cacheHits||(t.cacheHits=[]);return new Promise(o=>{c.push(()=>{o(r)})})}t.keys.push(e);const s=new Promise((c,o)=>{t.callbacks.push({resolve:c,reject:o})});return this._cacheMap.set(n,s),s}clear(e){const t=this._cacheMap;if(t){const n=this._cacheKeyFn(e);t.delete(n)}return this}}function Ni(i){const e=i._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<i._maxBatchSize)return e;const t={hasDispatched:!1,keys:[],callbacks:[]};return i._batch=t,setTimeout(()=>{qi(i,t)}),t}function qi(i,e){if(e.hasDispatched=!0,e.keys.length===0){at(e);return}let t;try{t=i._batchLoadFn(e.keys)}catch(n){return ct(i,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(n)}.`))}if(!t||typeof t.then!="function")return ct(i,e,new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(t)}.`));t.then(n=>{if(n.length!==e.keys.length)throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.
Keys:
${String(e.keys)}
Values:
${String(n)}`);at(e);for(let r=0;r<e.callbacks.length;r++){const s=n[r];s instanceof Error?e.callbacks[r].reject(s):e.callbacks[r].resolve(s)}}).catch(n=>{ct(i,e,n)})}function ct(i,e,t){at(e);for(let n=0;n<e.keys.length;n++)i.clear(e.keys[n]),e.callbacks[n].reject(t)}function at(i){if(i.cacheHits)for(let e=0;e<i.cacheHits.length;e++)i.cacheHits[e]()}const Ue=new TextDecoder("utf-8"),Mi=new TextEncoder;function J(i){try{i.indexOf("://")===-1&&(i="wss://"+i);let e=new URL(i);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${i}`)}}const de=Symbol("verified"),Ui=i=>i instanceof Object;function Wi(i){if(!Ui(i)||typeof i.kind!="number"||typeof i.content!="string"||typeof i.created_at!="number"||typeof i.pubkey!="string"||!i.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(i.tags))return!1;for(let e=0;e<i.tags.length;e++){let t=i.tags[e];if(!Array.isArray(t))return!1;for(let n=0;n<t.length;n++)if(typeof t[n]!="string")return!1}return!0}class Vi{generateSecretKey(){return G.utils.randomSecretKey()}getPublicKey(e){return B(G.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=B(G.getPublicKey(t)),n.id=lt(n),n.sig=B(G.sign(Z(lt(n)),t)),n[de]=!0,n}verifyEvent(e){if(typeof e[de]=="boolean")return e[de];const t=lt(e);if(t!==e.id)return e[de]=!1,!1;try{const n=G.verify(Z(e.sig),Z(t),Z(e.pubkey));return e[de]=n,n}catch{return e[de]=!1,!1}}}function Di(i){if(!Wi(i))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,i.pubkey,i.created_at,i.kind,i.tags,i.content])}function lt(i){let e=Pe(Mi.encode(Di(i)));return B(e)}const We=new Vi;We.generateSecretKey,We.getPublicKey,We.finalizeEvent;const Fi=We.verifyEvent,Zi=22242;function Ki(i,e){if(i.ids&&i.ids.indexOf(e.id)===-1||i.kinds&&i.kinds.indexOf(e.kind)===-1||i.authors&&i.authors.indexOf(e.pubkey)===-1)return!1;for(let t in i)if(t[0]==="#"){let n=t.slice(1),r=i[`#${n}`];if(r&&!e.tags.find(([s,c])=>s===t.sli