UNPKG

nostr-web-components

Version:

collection of web components that provide quick access to basic nostr things

1 lines 92.8 kB
var nostr_note=(function(){"use strict";var Vi=Object.defineProperty;var Di=(ue,Z,L)=>Z in ue?Vi(ue,Z,{enumerable:!0,configurable:!0,writable:!0,value:L}):ue[Z]=L;var h=(ue,Z,L)=>Di(ue,typeof Z!="symbol"?Z+"":Z,L);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ue(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Z(t,e=""){if(!Number.isSafeInteger(t)||t<0){const n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function L(t,e,n=""){const r=ue(t),i=t==null?void 0:t.length,s=e!==void 0;if(!r||s&&i!==e){const a=n&&`"${n}" `,c=s?` of length ${e}`:"",o=r?`length=${i}`:`type=${typeof t}`;throw new Error(a+"expected Uint8Array"+c+", got "+o)}return t}function At(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Wn(t,e){L(t,void 0,"digestInto() output");const n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ge(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Je(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Y(t,e){return t<<32-e|t>>>e}const Ot=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vn=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function C(t){if(L(t),Ot)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Vn[t[n]];return e}const ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function _t(t){if(t>=ne._0&&t<=ne._9)return t-ne._0;if(t>=ne.A&&t<=ne.F)return t-(ne.A-10);if(t>=ne.a&&t<=ne.f)return t-(ne.a-10)}function N(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ot)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const a=_t(t.charCodeAt(s)),c=_t(t.charCodeAt(s+1));if(a===void 0||c===void 0){const o=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+o+'" at index '+s)}r[i]=a*16+c}return r}function xe(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];L(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}function Dn(t,e={}){const n=(i,s)=>t(s).update(i).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=i=>t(i),Object.assign(n,e),Object.freeze(n)}function Pt(t=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(t))}const Fn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Zn(t,e,n){return t&e^~t&n}function jn(t,e,n){return t&e^t&n^e&n}class Kn{constructor(e,n,r,i){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=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Je(this.buffer)}update(e){At(this),L(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let a=0;a<s;){const c=Math.min(i-this.pos,s-a);if(c===i){const o=Je(e);for(;i<=s-a;a+=i)this.process(o,a);continue}r.set(e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){At(this),Wn(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:a}=this;n[a++]=128,Ge(this.buffer.subarray(a)),this.padOffset>i-a&&(this.process(r,0),a=0);for(let l=a;l<i;l++)n[l]=0;r.setBigUint64(i-8,BigInt(this.length*8),s),this.process(r,0);const c=Je(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=o/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:a,pos:c}=this;return e.destroyed=a,e.finished=s,e.length=i,e.pos=c,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const ie=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zn=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 Yn extends Kn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:n,C:r,D:i,E:s,F:a,G:c,H:o}=this;return[e,n,r,i,s,a,c,o]}set(e,n,r,i,s,a,c,o){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=a|0,this.G=c|0,this.H=o|0}process(e,n){for(let l=0;l<16;l++,n+=4)se[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const y=se[l-15],d=se[l-2],b=Y(y,7)^Y(y,18)^y>>>3,w=Y(d,17)^Y(d,19)^d>>>10;se[l]=w+se[l-7]+b+se[l-16]|0}let{A:r,B:i,C:s,D:a,E:c,F:o,G:u,H:f}=this;for(let l=0;l<64;l++){const y=Y(c,6)^Y(c,11)^Y(c,25),d=f+y+Zn(c,o,u)+zn[l]+se[l]|0,w=(Y(r,2)^Y(r,13)^Y(r,22))+jn(r,i,s)|0;f=u,u=o,o=c,c=a+d|0,a=s,s=i,i=r,r=d+w|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,a=a+this.D|0,c=c+this.E|0,o=o+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,s,a,c,o,u,f)}roundClean(){Ge(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}}class Gn extends Yn{constructor(){super(32);h(this,"A",ie[0]|0);h(this,"B",ie[1]|0);h(this,"C",ie[2]|0);h(this,"D",ie[3]|0);h(this,"E",ie[4]|0);h(this,"F",ie[5]|0);h(this,"G",ie[6]|0);h(this,"H",ie[7]|0)}}const Be=Dn(()=>new Gn,Fn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xe=BigInt(0),Qe=BigInt(1);function Ct(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Jn(t){if(typeof t=="bigint"){if(!er(t))throw new Error("positive bigint expected, got "+t)}else Z(t);return t}function Bt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Xe:BigInt("0x"+t)}function et(t){return Bt(C(t))}function It(t){return Bt(C(Xn(L(t)).reverse()))}function tt(t,e){Z(e),t=Jn(t);const n=N(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function $t(t,e){return tt(t,e).reverse()}function Xn(t){return Uint8Array.from(t)}function Qn(t){return Uint8Array.from(t,(e,n)=>{const r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}const er=t=>typeof t=="bigint"&&Xe<=t;function tr(t){let e;for(e=0;t>Xe;t>>=Qe,e+=1);return e}const Lt=t=>(Qe<<BigInt(t))-Qe;function Ht(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,a,c){const o=t[s];if(c&&o===void 0)return;const u=typeof o;if(u!==a||o===null)throw new Error(`param "${s}" is invalid: expected ${a}, got ${u}`)}const i=(s,a)=>Object.entries(s).forEach(([c,o])=>r(c,o,a));i(e,!1),i(n,!0)}function Nt(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const M=BigInt(0),q=BigInt(1),he=BigInt(2),qt=BigInt(3),Ut=BigInt(4),Mt=BigInt(5),nr=BigInt(7),Wt=BigInt(8),rr=BigInt(9),Vt=BigInt(16);function j(t,e){const n=t%e;return n>=M?n:e+n}function V(t,e,n){let r=t;for(;e-- >M;)r*=r,r%=n;return r}function Dt(t,e){if(t===M)throw new Error("invert: expected non-zero number");if(e<=M)throw new Error("invert: expected positive modulus, got "+e);let n=j(t,e),r=e,i=M,s=q;for(;n!==M;){const c=r/n,o=r%n,u=i-s*c;r=n,n=o,i=s,s=u}if(r!==q)throw new Error("invert: does not exist");return j(i,e)}function nt(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ft(t,e){const n=(t.ORDER+q)/Ut,r=t.pow(e,n);return nt(t,r,e),r}function ir(t,e){const n=(t.ORDER-Mt)/Wt,r=t.mul(e,he),i=t.pow(r,n),s=t.mul(e,i),a=t.mul(t.mul(s,he),i),c=t.mul(s,t.sub(a,t.ONE));return nt(t,c,e),c}function sr(t){const e=Ie(t),n=Zt(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),a=(t+nr)/Vt;return(c,o)=>{let u=c.pow(o,a),f=c.mul(u,r);const l=c.mul(u,i),y=c.mul(u,s),d=c.eql(c.sqr(f),o),b=c.eql(c.sqr(l),o);u=c.cmov(u,f,d),f=c.cmov(y,l,b);const w=c.eql(c.sqr(f),o),p=c.cmov(u,f,w);return nt(c,p,o),p}}function Zt(t){if(t<qt)throw new Error("sqrt is not defined for small field");let e=t-q,n=0;for(;e%he===M;)e/=he,n++;let r=he;const i=Ie(t);for(;Kt(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ft;let s=i.pow(r,e);const a=(e+q)/he;return function(o,u){if(o.is0(u))return u;if(Kt(o,u)!==1)throw new Error("Cannot find square root");let f=n,l=o.mul(o.ONE,s),y=o.pow(u,e),d=o.pow(u,a);for(;!o.eql(y,o.ONE);){if(o.is0(y))return o.ZERO;let b=1,w=o.sqr(y);for(;!o.eql(w,o.ONE);)if(b++,w=o.sqr(w),b===f)throw new Error("Cannot find square root");const p=q<<BigInt(f-b-1),T=o.pow(l,p);f=b,l=o.sqr(T),y=o.mul(y,l),d=o.mul(d,T)}return d}}function or(t){return t%Ut===qt?Ft:t%Wt===Mt?ir:t%Vt===rr?sr(t):Zt(t)}const ar=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cr(t){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=ar.reduce((r,i)=>(r[i]="function",r),e);return Ht(t,n),t}function lr(t,e,n){if(n<M)throw new Error("invalid exponent, negatives unsupported");if(n===M)return t.ONE;if(n===q)return e;let r=t.ONE,i=e;for(;n>M;)n&q&&(r=t.mul(r,i)),i=t.sqr(i),n>>=q;return r}function jt(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((a,c,o)=>t.is0(c)?a:(r[o]=a,t.mul(a,c)),t.ONE),s=t.inv(i);return e.reduceRight((a,c,o)=>t.is0(c)?a:(r[o]=t.mul(a,r[o]),t.mul(a,c)),s),r}function Kt(t,e){const n=(t.ORDER-q)/he,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),a=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function ur(t,e){e!==void 0&&Z(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}class hr{constructor(e,n={}){h(this,"ORDER");h(this,"BITS");h(this,"BYTES");h(this,"isLE");h(this,"ZERO",M);h(this,"ONE",q);h(this,"_lengths");h(this,"_sqrt");h(this,"_mod");var a;if(e<=M)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=(a=n.allowedLengths)==null?void 0:a.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:i,nByteLength:s}=ur(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return j(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&q)===q}neg(e){return j(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return j(e*e,this.ORDER)}add(e,n){return j(e+n,this.ORDER)}sub(e,n){return j(e-n,this.ORDER)}mul(e,n){return j(e*n,this.ORDER)}pow(e,n){return lr(this,e,n)}div(e,n){return j(e*Dt(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Dt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=or(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?$t(e,this.BYTES):tt(e,this.BYTES)}fromBytes(e,n=!1){L(e);const{_lengths:r,BYTES:i,isLE:s,ORDER:a,_mod:c}=this;if(r){if(!r.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const u=new Uint8Array(i);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let o=s?It(e):et(e);if(c&&(o=j(o,a)),!n&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(e){return jt(this,e)}cmov(e,n,r){return r?n:e}}function Ie(t,e={}){return new hr(t,e)}function zt(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function fr(t){const e=zt(t);return e+Math.ceil(e/2)}function dr(t,e,n=!1){L(t);const r=t.length,i=zt(e),s=fr(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=n?It(t):et(t),c=j(a,e-q)+q;return n?$t(c,i):tt(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ge=BigInt(0),fe=BigInt(1);function $e(t,e){const n=e.negate();return t?n:e}function Yt(t,e){const n=jt(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Gt(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function rt(t,e){Gt(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Lt(t),a=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:a}}function Jt(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:a}=n;let c=Number(t&i),o=t>>a;c>r&&(c-=s,o+=fe);const u=e*r,f=u+Math.abs(c)-1,l=c===0,y=c<0,d=e%2!==0;return{nextN:o,offset:f,isZero:l,isNeg:y,isNegF:d,offsetF:u}}const it=new WeakMap,Xt=new WeakMap;function st(t){return Xt.get(t)||1}function Qt(t){if(t!==ge)throw new Error("invalid wNAF")}class yr{constructor(e,n){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=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>ge;)n&fe&&(r=r.add(i)),i=i.double(),n>>=fe;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=rt(n,this.bits),s=[];let a=e,c=a;for(let o=0;o<r;o++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const a=rt(e,this.bits);for(let c=0;c<a.windows;c++){const{nextN:o,offset:u,isZero:f,isNeg:l,isNegF:y,offsetF:d}=Jt(r,c,a);r=o,f?s=s.add($e(y,n[d])):i=i.add($e(l,n[u]))}return Qt(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=rt(e,this.bits);for(let a=0;a<s.windows&&r!==ge;a++){const{nextN:c,offset:o,isZero:u,isNeg:f}=Jt(r,a,s);if(r=c,!u){const l=n[o];i=i.add(f?l.negate():l)}}return Qt(r),i}getPrecomputes(e,n,r){let i=it.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),it.set(n,i))),i}cached(e,n,r){const i=st(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=st(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Gt(n,this.bits),Xt.set(e,n),it.delete(e)}hasCache(e){return st(e)!==1}}function br(t,e,n,r){let i=e,s=t.ZERO,a=t.ZERO;for(;n>ge||r>ge;)n&fe&&(s=s.add(i)),r&fe&&(a=a.add(i)),i=i.double(),n>>=fe,r>>=fe;return{p1:s,p2:a}}function en(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return cr(e),e}else return Ie(t,{isLE:n})}function wr(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const o of["p","n","h"]){const u=e[o];if(!(typeof u=="bigint"&&u>ge))throw new Error(`CURVE.${o} must be positive bigint`)}const i=en(e.p,n.Fp,r),s=en(e.n,n.Fn,r),c=["Gx","Gy","a","b"];for(const o of c)if(!i.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}function gr(t,e){return function(r){const i=t(r);return{secretKey:i,publicKey:e(i)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const tn=(t,e)=>(t+(t>=0?e:-e)/mr)/e;function pr(t,e,n){const[[r,i],[s,a]]=e,c=tn(a*t,n),o=tn(-i*t,n);let u=t-c*r-o*s,f=-c*i-o*a;const l=u<Se,y=f<Se;l&&(u=-u),y&&(f=-f);const d=Lt(Math.ceil(tr(n)/2))+Le;if(u<Se||u>=d||f<Se||f>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:u,k2neg:y,k2:f}}const Se=BigInt(0),Le=BigInt(1),mr=BigInt(2),He=BigInt(3),Er=BigInt(4);function vr(t,e={}){const n=wr("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a,n:c}=s;Ht(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:o}=e;if(o&&(!r.is0(s.a)||typeof o.beta!="bigint"||!Array.isArray(o.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Sr(r,i);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(O,g,m){const{x:v,y:x}=g.toAffine(),_=r.toBytes(v);if(Ct(m,"isCompressed"),m){f();const k=!r.isOdd(x);return xe(xr(k),_)}else return xe(Uint8Array.of(4),_,r.toBytes(x))}function y(O){L(O,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=u,v=O.length,x=O[0],_=O.subarray(1);if(v===g&&(x===2||x===3)){const k=r.fromBytes(_);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");const S=w(k);let E;try{E=r.sqrt(S)}catch(F){const H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}f();const R=r.isOdd(E);return(x&1)===1!==R&&(E=r.neg(E)),{x:k,y:E}}else if(v===m&&x===4){const k=r.BYTES,S=r.fromBytes(_.subarray(0,k)),E=r.fromBytes(_.subarray(k,k*2));if(!p(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=${m}`)}const d=e.toBytes||l,b=e.fromBytes||y;function w(O){const g=r.sqr(O),m=r.mul(g,O);return r.add(r.add(m,r.mul(O,s.a)),s.b)}function p(O,g){const m=r.sqr(g),v=w(O);return r.eql(m,v)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const T=r.mul(r.pow(s.a,He),Er),I=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(T,I)))throw new Error("bad curve params: a or b");function W(O,g,m=!1){if(!r.isValid(g)||m&&r.is0(g))throw new Error(`bad point coordinate ${O}`);return g}function ee(O){if(!(O instanceof we))throw new Error("Weierstrass Point expected")}function $(O){if(!o||!o.basises)throw new Error("no endo");return pr(O,o.basises,i.ORDER)}const D=Nt((O,g)=>{const{X:m,Y:v,Z:x}=O;if(r.eql(x,r.ONE))return{x:m,y:v};const _=O.is0();g==null&&(g=_?r.ONE:r.inv(x));const k=r.mul(m,g),S=r.mul(v,g),E=r.mul(x,g);if(_)return{x:r.ZERO,y:r.ZERO};if(!r.eql(E,r.ONE))throw new Error("invZ was invalid");return{x:k,y:S}}),Wi=Nt(O=>{if(O.is0()){if(e.allowInfinityPoint&&!r.is0(O.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=O.toAffine();if(!r.isValid(g)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!p(g,m))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function qn(O,g,m,v,x){return m=new we(r.mul(m.X,O),m.Y,m.Z),g=$e(v,g),m=$e(x,m),g.add(m)}const B=class B{constructor(g,m,v){h(this,"X");h(this,"Y");h(this,"Z");this.X=W("x",g),this.Y=W("y",m,!0),this.Z=W("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){const{x:m,y:v}=g||{};if(!g||!r.isValid(m)||!r.isValid(v))throw new Error("invalid affine point");if(g instanceof B)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(v)?B.ZERO:new B(m,v,r.ONE)}static fromBytes(g){const m=B.fromAffine(b(L(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return B.fromBytes(N(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return Ce.createCache(this,g),m||this.multiply(He),this}assertValidity(){Wi(this)}hasEvenY(){const{y:g}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(g)}equals(g){ee(g);const{X:m,Y:v,Z:x}=this,{X:_,Y:k,Z:S}=g,E=r.eql(r.mul(m,S),r.mul(_,x)),R=r.eql(r.mul(v,S),r.mul(k,x));return E&&R}negate(){return new B(this.X,r.neg(this.Y),this.Z)}double(){const{a:g,b:m}=s,v=r.mul(m,He),{X:x,Y:_,Z:k}=this;let S=r.ZERO,E=r.ZERO,R=r.ZERO,A=r.mul(x,x),F=r.mul(_,_),H=r.mul(k,k),P=r.mul(x,_);return P=r.add(P,P),R=r.mul(x,k),R=r.add(R,R),S=r.mul(g,R),E=r.mul(v,H),E=r.add(S,E),S=r.sub(F,E),E=r.add(F,E),E=r.mul(S,E),S=r.mul(P,S),R=r.mul(v,R),H=r.mul(g,H),P=r.sub(A,H),P=r.mul(g,P),P=r.add(P,R),R=r.add(A,A),A=r.add(R,A),A=r.add(A,H),A=r.mul(A,P),E=r.add(E,A),H=r.mul(_,k),H=r.add(H,H),A=r.mul(H,P),S=r.sub(S,A),R=r.mul(H,F),R=r.add(R,R),R=r.add(R,R),new B(S,E,R)}add(g){ee(g);const{X:m,Y:v,Z:x}=this,{X:_,Y:k,Z:S}=g;let E=r.ZERO,R=r.ZERO,A=r.ZERO;const F=s.a,H=r.mul(s.b,He);let P=r.mul(m,_),K=r.mul(v,k),z=r.mul(x,S),ve=r.add(m,v),U=r.add(_,k);ve=r.mul(ve,U),U=r.add(P,K),ve=r.sub(ve,U),U=r.add(m,x);let te=r.add(_,S);return U=r.mul(U,te),te=r.add(P,z),U=r.sub(U,te),te=r.add(v,x),E=r.add(k,S),te=r.mul(te,E),E=r.add(K,z),te=r.sub(te,E),A=r.mul(F,U),E=r.mul(H,z),A=r.add(E,A),E=r.sub(K,A),A=r.add(K,A),R=r.mul(E,A),K=r.add(P,P),K=r.add(K,P),z=r.mul(F,z),U=r.mul(H,U),K=r.add(K,z),z=r.sub(P,z),z=r.mul(F,z),U=r.add(U,z),P=r.mul(K,U),R=r.add(R,P),P=r.mul(te,U),E=r.mul(ve,E),E=r.sub(E,P),P=r.mul(ve,K),A=r.mul(te,A),A=r.add(A,P),new B(E,R,A)}subtract(g){return this.add(g.negate())}is0(){return this.equals(B.ZERO)}multiply(g){const{endo:m}=e;if(!i.isValidNot0(g))throw new Error("invalid scalar: out of range");let v,x;const _=k=>Ce.cached(this,k,S=>Yt(B,S));if(m){const{k1neg:k,k1:S,k2neg:E,k2:R}=$(g),{p:A,f:F}=_(S),{p:H,f:P}=_(R);x=F.add(P),v=qn(m.beta,A,H,k,E)}else{const{p:k,f:S}=_(g);v=k,x=S}return Yt(B,[v,x])[0]}multiplyUnsafe(g){const{endo:m}=e,v=this;if(!i.isValid(g))throw new Error("invalid scalar: out of range");if(g===Se||v.is0())return B.ZERO;if(g===Le)return v;if(Ce.hasCache(this))return this.multiply(g);if(m){const{k1neg:x,k1:_,k2neg:k,k2:S}=$(g),{p1:E,p2:R}=br(B,v,_,S);return qn(m.beta,E,R,x,k)}else return Ce.unsafe(v,g)}toAffine(g){return D(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return a===Le?!0:g?g(B,this):Ce.unsafe(this,c).is0()}clearCofactor(){const{clearCofactor:g}=e;return a===Le?this:g?g(B,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(g=!0){return Ct(g,"isCompressed"),this.assertValidity(),d(B,this,g)}toHex(g=!0){return C(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};h(B,"BASE",new B(s.Gx,s.Gy,r.ONE)),h(B,"ZERO",new B(r.ZERO,r.ONE,r.ZERO)),h(B,"Fp",r),h(B,"Fn",i);let we=B;const Un=i.BITS,Ce=new yr(we,e.endo?Math.ceil(Un/2):Un);return we.BASE.precompute(8),we}function xr(t){return Uint8Array.of(t?2:3)}function Sr(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ne={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Rr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tr=BigInt(0),ot=BigInt(2);function kr(t){const e=Ne.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),c=BigInt(44),o=BigInt(88),u=t*t*t%e,f=u*u*t%e,l=V(f,n,e)*f%e,y=V(l,n,e)*f%e,d=V(y,ot,e)*u%e,b=V(d,i,e)*d%e,w=V(b,s,e)*b%e,p=V(w,c,e)*w%e,T=V(p,o,e)*p%e,I=V(T,c,e)*w%e,W=V(I,n,e)*f%e,ee=V(W,a,e)*b%e,$=V(ee,r,e)*u%e,D=V($,ot,e);if(!qe.eql(qe.sqr(D),t))throw new Error("Cannot find square root");return D}const qe=Ie(Ne.p,{sqrt:kr}),pe=vr(Ne,{Fp:qe,endo:Rr}),nn={};function Ue(t,...e){let n=nn[t];if(n===void 0){const r=Be(Qn(t));n=xe(r,r),nn[t]=n}return Be(xe(n,...e))}const at=t=>t.toBytes(!0).slice(1),ct=t=>t%ot===Tr;function lt(t){const{Fn:e,BASE:n}=pe,r=e.fromBytes(t),i=n.multiply(r);return{scalar:ct(i.y)?r:e.neg(r),bytes:at(i)}}function rn(t){const e=qe;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x ≥ p");const n=e.create(t*t),r=e.create(n*t+BigInt(7));let i=e.sqrt(r);ct(i)||(i=e.neg(i));const s=pe.fromAffine({x:t,y:i});return s.assertValidity(),s}const Re=et;function sn(...t){return pe.Fn.create(Re(Ue("BIP0340/challenge",...t)))}function on(t){return lt(t).bytes}function Ar(t,e,n=Pt(32)){const{Fn:r}=pe,i=L(t,void 0,"message"),{bytes:s,scalar:a}=lt(e),c=L(n,32,"auxRand"),o=r.toBytes(a^Re(Ue("BIP0340/aux",c))),u=Ue("BIP0340/nonce",o,s,i),{bytes:f,scalar:l}=lt(u),y=sn(f,s,i),d=new Uint8Array(64);if(d.set(f,0),d.set(r.toBytes(r.create(l+y*a)),32),!an(d,i,s))throw new Error("sign: Invalid signature produced");return d}function an(t,e,n){const{Fp:r,Fn:i,BASE:s}=pe,a=L(t,64,"signature"),c=L(e,void 0,"message"),o=L(n,32,"publicKey");try{const u=rn(Re(o)),f=Re(a.subarray(0,32));if(!r.isValidNot0(f))return!1;const l=Re(a.subarray(32,64));if(!i.isValidNot0(l))return!1;const y=sn(i.toBytes(f),at(u),c),d=s.multiplyUnsafe(l).add(u.multiplyUnsafe(i.neg(y))),{x:b,y:w}=d.toAffine();return!(d.is0()||!ct(w)||b!==f)}catch{return!1}}const G=(()=>{const n=(r=Pt(48))=>dr(r,Ne.n);return{keygen:gr(n,on),getPublicKey:on,sign:Ar,verify:an,Point:pe,utils:{randomSecretKey:n,taggedHash:Ue,lift_x:rn,pointToBytes:at},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),de=Symbol("verified"),Or=t=>t instanceof Object;function _r(t){if(!Or(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}const Me=new TextDecoder("utf-8"),Te=new TextEncoder;function me(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);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: ${t}`)}}let Pr=class{generateSecretKey(){return G.utils.randomSecretKey()}getPublicKey(e){return C(G.getPublicKey(e))}finalizeEvent(e,n){const r=e;return r.pubkey=C(G.getPublicKey(n)),r.id=ut(r),r.sig=C(G.sign(N(ut(r)),n)),r[de]=!0,r}verifyEvent(e){if(typeof e[de]=="boolean")return e[de];const n=ut(e);if(n!==e.id)return e[de]=!1,!1;try{const r=G.verify(N(e.sig),N(n),N(e.pubkey));return e[de]=r,r}catch{return e[de]=!1,!1}}};function Cr(t){if(!_r(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function ut(t){let e=Be(Te.encode(Cr(t)));return C(e)}const We=new Pr;We.generateSecretKey,We.getPublicKey,We.finalizeEvent;const cn=We.verifyEvent;/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ln(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function un(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Br(t){if(typeof t!="function")throw new Error("function expected");return!0}function ke(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function hn(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function ht(t){if(!Array.isArray(t))throw new Error("array expected")}function fn(t,e){if(!un(!0,e))throw new Error(`${t}: array of strings expected`)}function dn(t,e){if(!un(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ir(...t){const e=s=>s,n=(s,a)=>c=>s(a(c)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function $r(t){const e=typeof t=="string"?t.split(""):t,n=e.length;fn("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(ht(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(ht(i),i.map(s=>{ke("alphabet.decode",s);const a=r.get(s);if(a===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return a}))}}function Lr(t=""){return ke("join",t),{encode:e=>(fn("join.decode",e),e.join(t)),decode:e=>(ke("join.decode",e),e.split(t))}}const yn=(t,e)=>e===0?t:yn(e,t%e),Ve=(t,e)=>t+(e-yn(t,e)),De=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function ft(t,e,n,r){if(ht(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Ve(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ve(e,n)}`);let i=0,s=0;const a=De[e],c=De[n]-1,o=[];for(const u of t){if(hn(u),u>=a)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)o.push((i>>s-n&c)>>>0);const f=De[s];if(f===void 0)throw new Error("invalid carry");i&=f-1}if(i=i<<n-s&c,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&o.push(i>>>0),o}function Hr(t,e=!1){if(hn(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ve(8,t)>32||Ve(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!ln(n))throw new Error("radix2.encode input should be Uint8Array");return ft(Array.from(n),8,t,!e)},decode:n=>(dn("radix2.decode",n),Uint8Array.from(ft(n,t,8,e)))}}function bn(t){return Br(t),function(...e){try{return t.apply(null,e)}catch{}}}const dt=Ir($r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Lr("")),wn=[996825010,642813549,513874426,1027748829,705979059];function Ae(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<wn.length;r++)(e>>r&1)===1&&(n^=wn[r]);return n}function gn(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const a=t.charCodeAt(s);if(a<33||a>126)throw new Error(`Invalid prefix (${t})`);i=Ae(i)^a>>5}i=Ae(i);for(let s=0;s<r;s++)i=Ae(i)^t.charCodeAt(s)&31;for(let s of e)i=Ae(i)^s;for(let s=0;s<6;s++)i=Ae(i);return i^=n,dt.encode(ft([i%De[30]],30,5,!1))}function Nr(t){const e=t==="bech32"?1:734539939,n=Hr(5),r=n.decode,i=n.encode,s=bn(r);function a(l,y,d=90){ke("bech32.encode prefix",l),ln(y)&&(y=Array.from(y)),dn("bech32.encode",y);const b=l.length;if(b===0)throw new TypeError(`Invalid prefix length ${b}`);const w=b+7+y.length;if(d!==!1&&w>d)throw new TypeError(`Length ${w} exceeds limit ${d}`);const p=l.toLowerCase(),T=gn(p,y,e);return`${p}1${dt.encode(y)}${T}`}function c(l,y=90){ke("bech32.decode input",l);const d=l.length;if(d<8||y!==!1&&d>y)throw new TypeError(`invalid string length: ${d} (${l}). Expected (8..${y})`);const b=l.toLowerCase();if(l!==b&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=b.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const p=b.slice(0,w),T=b.slice(w+1);if(T.length<6)throw new Error("Data must be at least 6 characters long");const I=dt.decode(T).slice(0,-6),W=gn(p,I,e);if(!T.endsWith(W))throw new Error(`Invalid checksum in ${l}: expected "${W}"`);return{prefix:p,words:I}}const o=bn(c);function u(l){const{prefix:y,words:d}=c(l,!1);return{prefix:y,words:d,bytes:r(d)}}function f(l,y){return a(l,i(y))}return{encode:a,decode:c,encodeFromBytes:f,decodeToBytes:u,decodeUnsafe:o,fromWords:r,fromWordsUnsafe:s,toWords:i}}const oe=Nr("bech32"),pn=5e3;function qr(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function Ur(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),mn(t)}catch{return{type:"invalid",data:null}}}function mn(t){var i,s,a,c,o,u,f;let{prefix:e,words:n}=oe.decode(t,pn),r=new Uint8Array(oe.fromWords(n));switch(e){case"nprofile":{let l=yt(r);if(!((i=l[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:C(l[0][0]),relays:l[1]?l[1].map(y=>Me.decode(y)):[]}}}case"nevent":{let l=yt(r);if(!((s=l[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(l[2]&&l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(l[3]&&l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:C(l[0][0]),relays:l[1]?l[1].map(y=>Me.decode(y)):[],author:(a=l[2])!=null&&a[0]?C(l[2][0]):void 0,kind:(c=l[3])!=null&&c[0]?parseInt(C(l[3][0]),16):void 0}}}case"naddr":{let l=yt(r);if(!((o=l[0])!=null&&o[0]))throw new Error("missing TLV 0 for naddr");if(!((u=l[2])!=null&&u[0]))throw new Error("missing TLV 2 for naddr");if(l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((f=l[3])!=null&&f[0]))throw new Error("missing TLV 3 for naddr");if(l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Me.decode(l[0][0]),pubkey:C(l[2][0]),kind:parseInt(C(l[3][0]),16),relays:l[1]?l[1].map(y=>Me.decode(y)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:C(r)};default:throw new Error(`unknown prefix ${e}`)}}function yt(t){let e={},n=t;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(s)}return e}function En(t){return Mr("npub",N(t))}function Fe(t,e){let n=oe.toWords(e);return oe.encode(t,n,pn)}function Mr(t,e){return Fe(t,e)}function Wr(t){let e=bt({0:[N(t.pubkey)],1:(t.relays||[]).map(n=>Te.encode(n))});return Fe("nprofile",e)}function Ze(t){let e;t.kind!==void 0&&(e=qr(t.kind));let n=bt({0:[N(t.id)],1:(t.relays||[]).map(r=>Te.encode(r)),2:t.author?[N(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return Fe("nevent",n)}function Vr(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let n=bt({0:[Te.encode(t.identifier)],1:(t.relays||[]).map(r=>Te.encode(r)),2:[N(t.pubkey)],3:[new Uint8Array(e)]});return Fe("naddr",n)}function bt(t){let e=[];return Object.entries(t).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),e.push(s)})}),xe(...e)}function vn(t){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=t.tags.length-1;i>=0;i--){const s=t.tags[i];if(s[0]==="e"&&s[1]){const[a,c,o,u,f]=s,l={id:c,relays:o?[o]:[],author:f};if(u==="root"){e.root=l;continue}if(u==="reply"){e.reply=l;continue}if(u==="mention"){e.mentions.push(l);continue}n?r=l:n=l,e.mentions.push(l);continue}if(s[0]==="q"&&s[1]){const[a,c,o]=s;e.quotes.push({id:c,relays:o?[o]:[]})}if(s[0]==="p"&&s[1]){e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return e.root||(e.root=r||n||e.reply),e.reply||(e.reply=n||e.root),[e.reply,e.root].forEach(i=>{if(!i)return;let s=e.mentions.indexOf(i);if(s!==-1&&e.mentions.splice(s,1),i.author){let a=e.profiles.find(c=>c.pubkey===i.author);a&&a.relays&&(i.relays||(i.relays=[]),a.relays.forEach(c=>{var o;((o=i.relays)==null?void 0:o.indexOf(c))===-1&&i.relays.push(c)}),a.relays=i.relays)}}),e.mentions.forEach(i=>{if(i.author){let s=e.profiles.find(a=>a.pubkey===i.author);s&&s.relays&&(i.relays||(i.relays=[]),s.relays.forEach(a=>{i.relays.indexOf(a)===-1&&i.relays.push(a)}),s.relays=i.relays)}}),e}const Dr=22242;function Fr(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),i=t[`#${r}`];if(i&&!e.tags.find(([s,a])=>s===n.slice(1)&&i.indexOf(a)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function Zr(t,e){for(let n=0;n<t.length;n++)if(Fr(t[n],e))return!0;return!1}function jr(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,i=t.slice(r).indexOf('"')+r+1;return t.slice(i,i+64)}function Kr(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,i=t.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return t.slice(r+1,s)}function zr(t,e){return{kind:Dr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}let xn=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},Yr=class Mn{constructor(e,n){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=me(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const r=new Mn(e,n);return await r.connect(n),r}closeAllSubscriptions(e){for(let[n,r]of this.openSubs)r.close(e);this.openSubs.clear();for(let[n,r]of this.openEventPublishes)r.reject(new Error(e));this.openEventPublishes.clear();for(let[n,r]of this.openCountRequests)r.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 n;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():((n=this.onclose)==null||n.call(this),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((r,i)=>{e!=null&&e.timeout&&(n=setTimeout(()=>{var s;i("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=i);try{this.ws=new this._WebSocket(this.url)}catch(s){clearTimeout(n),i(s);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const s=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const a of this.openSubs.values()){if(a.eosed=!1,s)for(let c=0;c<a.filters.length;c++)a.lastEmitted&&(a.filters[c].since=a.lastEmitted+1);a.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),r()},this.ws.onerror=()=>{var s;clearTimeout(n),i("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(n),i(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,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const r=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),r.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(r){n(r)}})}async pingpong(){var e,n,r;((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))])||((n=this.ws)==null?void 0:n.readyState)===this._WebSocket.OPEN&&((r=this.ws)==null||r.close()))}async send(e){if(!this.connectionPromise)throw new xn(e,this.url);this.connectionPromise.then(()=>{var n;(n=this.ws)==null||n.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(r,i)=>{try{let s=await e(zr(this.url,n)),a=setTimeout(()=>{let c=this.openEventPublishes.get(s.id);c&&(c.reject(new Error("auth timed out")),this.openEventPublishes.delete(s.id))},this.publishTimeout);this.openEventPublishes.set(s.id,{resolve:r,reject:i,timeout:a}),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 n=new Promise((r,i)=>{const s=setTimeout(()=>{const a=this.openEventPublishes.get(e.id);a&&(a.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:r,reject:i,timeout:s})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const r=(n==null?void 0:n.id)||"count:"+this.serial,i=new Promise((s,a)=>{this.openCountRequests.set(r,{resolve:s,reject:a})});return this.send('["COUNT","'+r+'",'+JSON.stringify(e).substring(1)),i}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const r=this.prepareSubscription(e,n);return r.fire(),n.abort&&(n.abort.onabort=()=>r.close(String(n.abort.reason||"<aborted>"))),r}prepareSubscription(e,n){this.serial++;const r=n.id||(n.label?n.label+":":"sub:")+this.serial,i=new Gr(this,r,e,n);return this.openSubs.set(r,i),i}close(){var e,n,r;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),((n=this.ws)==null?void 0:n.readyState)===this._WebSocket.OPEN&&((r=this.ws)==null||r.close())}_onmessage(e){var i,s,a;const n=e.data;if(!n)return;const r=Kr(n);if(r){const c=this.openSubs.get(r);if(!c)return;const o=jr(n,"id"),u=(i=c.alreadyHaveEvent)==null?void 0:i.call(c,o);if((s=c.receivedEvent)==null||s.call(c,this,o),u)return}try{let c=JSON.parse(n);switch(c[0]){case"EVENT":{const o=this.openSubs.get(c[1]),u=c[2];this.verifyEvent(u)&&Zr(o.filters,u)&&o.onevent(u),(!o.lastEmitted||o.lastEmitted<u.created_at)&&(o.lastEmitted=u.created_at);return}case"COUNT":{const o=c[1],u=c[2],f=this.openCountRequests.get(o);f&&(f.resolve(u.count),this.openCountRequests.delete(o));return}case"EOSE":{const o=this.openSubs.get(c[1]);if(!o)return;o.receivedEose();return}case"OK":{const o=c[1],u=c[2],f=c[3],l=this.openEventPublishes.get(o);l&&(clearTimeout(l.timeout),u?l.resolve(f):l.reject(new Error(f)),this.openEventPublishes.delete(o));return}case"CLOSED":{const o=c[1],u=this.openSubs.get(o);if(!u)return;u.closed=!0,u.close(c[2]);return}case"NOTICE":{this.onnotice(c[1]);return}case"AUTH":{this.challenge=c[1],this.onauth&&this.auth(this.onauth);return}default:{const o=this.openSubs.get(c[1]);(a=o==null?void 0:o.oncustom)==null||a.call(o,c);return}}}catch(c){const[o,u,f]=JSON.parse(n);window.printer.maybe(f.pubkey,":: caught err",f,this.url,c);return}}},Gr=class{constructor(e,n,r,i){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(r.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=r,this.id=n,this.alreadyHaveEvent=i.alreadyHaveEvent,this.receivedEvent=i.receivedEvent,this.eoseTimeout=i.eoseTimeout||e.baseEoseTimeout,this.oneose=i.oneose,this.onclose=i.onclose,this.onevent=i.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 n;if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(r){if(!(r instanceof xn))throw r}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),(n=this.onclose)==null||n.call(this,e)}};const Jr=t=>(t[de]=!0,!0);let Xr=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,n){e=me(e);let r=this.relays.get(e);if(r||(r=new Yr(e,{verifyEvent:this.trustedRelayURLs.has(e)?Jr:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),r.onclose=()=>{this.relays.delete(e)},this.relays.set(e,r)),this.automaticallyAuth){const i=this.automaticallyAuth(e);i&&(r.onauth=i)}try{await r.connect({timeout:n==null?void 0:n.connectionTimeout,abort:n==null?void 0:n.abort})}catch(i){throw this.relays.delete(e),i}return r}close(e){e.map(me).forEach(n=>{var r;(r=this.relays.get(n))==null||r.close(),this.relays.delete(n)})}subscribe(e,n,r){const i=[],s=[];for(let a=0;a<e.length;a++){const c=me(e[a]);i.find(o=>o.url===c)||s.indexOf(c)===-1&&(s.push(c),i.push({url:c,filter:n}))}return this.subscribeMap(i,r)}subscribeMany(e,n,r){return this.subscribe(e,n,r)}subscribeMap(e,n){const r=new Map;for(const d of e){const{url:b,filter:w}=d;r.has(b)||r.set(b,[]),r.get(b).push(w)}const i=Array.from(r.entries()).map(([d,b])=>({url:d,filters:b}));this.trackRelays&&(n.receivedEvent=(d,b)=>{let w=this.seenOn.get(b);w||(w=new Set,this.seenOn.set(b,w)),w.add(d)});const s=new Set,a=[],c=[];let o=d=>{var b;c[d]||(c[d]=!0,c.filter(w=>w).length===i.length&&((b=n.oneose)==null||b.call(n),o=()=>{}))};const u=[];let f=(d,b)=>{var w;u[d]||(o(d),u[d]=b,u.filter(p=>p).length===i.length&&((w=n.onclose)==null||w.call(n,u),f=()=>{}))};const l=d=>{var w;if((w=n.alreadyHaveEvent)!=null&&w.call(n,d))return!0;const b=s.has(d);return s.add(d),b},y=Promise.all(i.map(async({url:d,filters:b},w)=>{var I,W,ee;if(((I=this.allowConnectingToRelay)==null?void 0:I.call(this,d,["read",b]))===!1){f(w,"connection skipped by allowConnectingToRelay");return}let p;try{p=await this.ensureRelay(d,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch($){(W=this.onRelayConnectionFailure)==null||W.call(this,d),f(w,($==null?void 0:$.message)||String($));return}(ee=this.onRelayConnectionSuccess)==null||ee.call(this,d);let T=p.subscribe(b,{...n,oneose:()=>o(w),onclose:$=>{$.startsWith("auth-required: ")&&n.onauth?p.auth(n.onauth).then(()=>{p.subscribe(b,{...n,oneose:()=>o(w),onclose:D=>{f(w,D)},alreadyHaveEvent:l,eoseTimeout:n.maxWait,abort:n.abort})}).catch(D=>{f(w,`auth was required and attempted, but failed with: ${D}`)}):f(w,$)},alreadyHaveEvent:l,eoseTimeout:n.maxWait,abort:n.abort});a.push(T)}));return{async close(d){await y,a.forEach(b=>{b.close(d)})}}}subscribeEose(e,n