UNPKG

nostr-web-components

Version:

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

1 lines 86.7 kB
var nostr_rsvp=(function(){"use strict";var Rr=Object.defineProperty;var Tr=(le,Z,L)=>Z in le?Rr(le,Z,{enumerable:!0,configurable:!0,writable:!0,value:L}):le[Z]=L;var h=(le,Z,L)=>Tr(le,typeof Z!="symbol"?Z+"":Z,L);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function le(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Z(i,e=""){if(!Number.isSafeInteger(i)||i<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${i}`)}}function L(i,e,t=""){const n=le(i),r=i==null?void 0:i.length,s=e!==void 0;if(!n||s&&r!==e){const a=t&&`"${t}" `,o=s?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof i}`;throw new Error(a+"expected Uint8Array"+o+", got "+c)}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 Tn(i,e){L(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 Ze(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}function Ke(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function G(i,e){return i<<32-e|i>>>e}const St=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kn=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function I(i){if(L(i),St)return i.toHex();let e="";for(let t=0;t<i.length;t++)e+=kn[i[t]];return e}const ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function xt(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 K(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);if(St)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 a=xt(i.charCodeAt(s)),o=xt(i.charCodeAt(s+1));if(a===void 0||o===void 0){const c=i[s]+i[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[r]=a*16+o}return n}function Oe(...i){let e=0;for(let n=0;n<i.length;n++){const r=i[n];L(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 An(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 On=i=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,i])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Tt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function kt(i,e){return Array.isArray(e)?e.length===0?!0:i?e.every(t=>typeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Pn(i){if(typeof i!="function")throw new Error("function expected");return!0}function ve(i,e){if(typeof e!="string")throw new Error(`${i}: string expected`);return!0}function At(i){if(!Number.isSafeInteger(i))throw new Error(`invalid integer: ${i}`)}function je(i){if(!Array.isArray(i))throw new Error("array expected")}function Ot(i,e){if(!kt(!0,e))throw new Error(`${i}: array of strings expected`)}function Pt(i,e){if(!kt(!1,e))throw new Error(`${i}: array of numbers expected`)}function _n(...i){const e=s=>s,t=(s,a)=>o=>s(a(o)),n=i.map(s=>s.encode).reduceRight(t,e),r=i.map(s=>s.decode).reduce(t,e);return{encode:n,decode:r}}function Bn(i){const e=typeof i=="string"?i.split(""):i,t=e.length;Ot("alphabet",e);const n=new Map(e.map((r,s)=>[r,s]));return{encode:r=>(je(r),r.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${i}`);return e[s]})),decode:r=>(je(r),r.map(s=>{ve("alphabet.decode",s);const a=n.get(s);if(a===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${i}`);return a}))}}function Cn(i=""){return ve("join",i),{encode:e=>(Ot("join.decode",e),e.join(i)),decode:e=>(ve("join.decode",e),e.split(i))}}const _t=(i,e)=>e===0?i:_t(e,i%e),Pe=(i,e)=>i+(e-_t(i,e)),_e=(()=>{let i=[];for(let e=0;e<40;e++)i.push(2**e);return i})();function ze(i,e,t,n){if(je(i),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(Pe(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Pe(e,t)}`);let r=0,s=0;const a=_e[e],o=_e[t]-1,c=[];for(const u of i){if(At(u),u>=a)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(r=r<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=t;s-=t)c.push((r>>s-t&o)>>>0);const f=_e[s];if(f===void 0)throw new Error("invalid carry");r&=f-1}if(r=r<<t-s&o,!n&&s>=e)throw new Error("Excess padding");if(!n&&r>0)throw new Error(`Non-zero padding: ${r}`);return n&&s>0&&c.push(r>>>0),c}function In(i,e=!1){if(At(i),i<=0||i>32)throw new Error("radix2: bits should be in (0..32]");if(Pe(8,i)>32||Pe(i,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!Tt(t))throw new Error("radix2.encode input should be Uint8Array");return ze(Array.from(t),8,i,!e)},decode:t=>(Pt("radix2.decode",t),Uint8Array.from(ze(t,i,8,e)))}}function Bt(i){return Pn(i),function(...e){try{return i.apply(null,e)}catch{}}}const Ye=_n(Bn("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Cn("")),Ct=[996825010,642813549,513874426,1027748829,705979059];function Se(i){const e=i>>25;let t=(i&33554431)<<5;for(let n=0;n<Ct.length;n++)(e>>n&1)===1&&(t^=Ct[n]);return t}function It(i,e,t=1){const n=i.length;let r=1;for(let s=0;s<n;s++){const a=i.charCodeAt(s);if(a<33||a>126)throw new Error(`Invalid prefix (${i})`);r=Se(r)^a>>5}r=Se(r);for(let s=0;s<n;s++)r=Se(r)^i.charCodeAt(s)&31;for(let s of e)r=Se(r)^s;for(let s=0;s<6;s++)r=Se(r);return r^=t,Ye.encode(ze([r%_e[30]],30,5,!1))}function $n(i){const e=i==="bech32"?1:734539939,t=In(5),n=t.decode,r=t.encode,s=Bt(n);function a(l,y,d=90){ve("bech32.encode prefix",l),Tt(y)&&(y=Array.from(y)),Pt("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(),x=It(p,y,e);return`${p}1${Ye.encode(y)}${x}`}function o(l,y=90){ve("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),x=b.slice(w+1);if(x.length<6)throw new Error("Data must be at least 6 characters long");const H=Ye.decode(x).slice(0,-6),v=It(p,H,e);if(!x.endsWith(v))throw new Error(`Invalid checksum in ${l}: expected "${v}"`);return{prefix:p,words:H}}const c=Bt(o);function u(l){const{prefix:y,words:d}=o(l,!1);return{prefix:y,words:d,bytes:n(d)}}function f(l,y){return a(l,r(y))}return{encode:a,decode:o,encodeFromBytes:f,decodeToBytes:u,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:r}}const ye=$n("bech32"),Be=new TextDecoder("utf-8"),Hn=new TextEncoder;function we(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 Ln=5e3;function Nn(i){try{return i.startsWith("nostr:")&&(i=i.substring(6)),qn(i)}catch{return{type:"invalid",data:null}}}function qn(i){var r,s,a,o,c,u,f;let{prefix:e,words:t}=ye.decode(i,Ln),n=new Uint8Array(ye.fromWords(t));switch(e){case"nprofile":{let l=Ge(n);if(!((r=l[0])!=null&&r[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:I(l[0][0]),relays:l[1]?l[1].map(y=>Be.decode(y)):[]}}}case"nevent":{let l=Ge(n);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:I(l[0][0]),relays:l[1]?l[1].map(y=>Be.decode(y)):[],author:(a=l[2])!=null&&a[0]?I(l[2][0]):void 0,kind:(o=l[3])!=null&&o[0]?parseInt(I(l[3][0]),16):void 0}}}case"naddr":{let l=Ge(n);if(!((c=l[0])!=null&&c[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:Be.decode(l[0][0]),pubkey:I(l[2][0]),kind:parseInt(I(l[3][0]),16),relays:l[1]?l[1].map(y=>Be.decode(y)):[]}}}case"nsec":return{type:e,data:n};case"npub":case"note":return{type:e,data:I(n)};default:throw new Error(`unknown prefix ${e}`)}}function Ge(i){let e={},t=i;for(;t.length>0;){let n=t[0],r=t[1],s=t.slice(2,2+r);if(t=t.slice(2+r),s.length<r)throw new Error(`not enough data to read on TLV ${n}`);e[n]=e[n]||[],e[n].push(s)}return e}function Mn(i,e,t){return i&e^~i&t}function Dn(i,e,t){return i&e^i&t^e&t}class Vn{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=Ke(this.buffer)}update(e){vt(this),L(e);const{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let a=0;a<s;){const o=Math.min(r-this.pos,s-a);if(o===r){const c=Ke(e);for(;r<=s-a;a+=r)this.process(c,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){vt(this),Tn(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:a}=this;t[a++]=128,Ze(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let l=a;l<r;l++)t[l]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);const o=Ke(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=c/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:a,pos:o}=this;return e.destroyed=a,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]),Un=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 Wn extends Vn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:s,F:a,G:o,H:c}=this;return[e,t,n,r,s,a,o,c]}set(e,t,n,r,s,a,o,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=c|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 y=se[l-15],d=se[l-2],b=G(y,7)^G(y,18)^y>>>3,w=G(d,17)^G(d,19)^d>>>10;se[l]=w+se[l-7]+b+se[l-16]|0}let{A:n,B:r,C:s,D:a,E:o,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const y=G(o,6)^G(o,11)^G(o,25),d=f+y+Mn(o,c,u)+Un[l]+se[l]|0,w=(G(n,2)^G(n,13)^G(n,22))+Dn(n,r,s)|0;f=u,u=c,c=o,o=a+d|0,a=s,s=r,r=n,n=d+w|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,r,s,a,o,c,u,f)}roundClean(){Ze(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Ze(this.buffer)}}class Fn extends Wn{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 Ce=An(()=>new Fn,On(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Je=BigInt(0),Xe=BigInt(1);function $t(i,e=""){if(typeof i!="boolean"){const t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof i)}return i}function Zn(i){if(typeof i=="bigint"){if(!zn(i))throw new Error("positive bigint expected, got "+i)}else Z(i);return i}function Ht(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Je:BigInt("0x"+i)}function Qe(i){return Ht(I(i))}function Lt(i){return Ht(I(Kn(L(i)).reverse()))}function et(i,e){Z(e),i=Zn(i);const t=K(i.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Nt(i,e){return et(i,e).reverse()}function Kn(i){return Uint8Array.from(i)}function jn(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 zn=i=>typeof i=="bigint"&&Je<=i;function Yn(i){let e;for(e=0;i>Je;i>>=Xe,e+=1);return e}const qt=i=>(Xe<<BigInt(i))-Xe;function Mt(i,e={},t={}){if(!i||typeof i!="object")throw new Error("expected valid options object");function n(s,a,o){const c=i[s];if(o&&c===void 0)return;const u=typeof c;if(u!==a||c===null)throw new Error(`param "${s}" is invalid: expected ${a}, got ${u}`)}const r=(s,a)=>Object.entries(s).forEach(([o,c])=>n(o,c,a));r(e,!1),r(t,!0)}function Dt(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 V=BigInt(0),M=BigInt(1),ue=BigInt(2),Vt=BigInt(3),Ut=BigInt(4),Wt=BigInt(5),Gn=BigInt(7),Ft=BigInt(8),Jn=BigInt(9),Zt=BigInt(16);function j(i,e){const t=i%e;return t>=V?t:e+t}function W(i,e,t){let n=i;for(;e-- >V;)n*=n,n%=t;return n}function Kt(i,e){if(i===V)throw new Error("invert: expected non-zero number");if(e<=V)throw new Error("invert: expected positive modulus, got "+e);let t=j(i,e),n=e,r=V,s=M;for(;t!==V;){const o=n/t,c=n%t,u=r-s*o;n=t,t=c,r=s,s=u}if(n!==M)throw new Error("invert: does not exist");return j(r,e)}function tt(i,e,t){if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function jt(i,e){const t=(i.ORDER+M)/Ut,n=i.pow(e,t);return tt(i,n,e),n}function Xn(i,e){const t=(i.ORDER-Wt)/Ft,n=i.mul(e,ue),r=i.pow(n,t),s=i.mul(e,r),a=i.mul(i.mul(s,ue),r),o=i.mul(s,i.sub(a,i.ONE));return tt(i,o,e),o}function Qn(i){const e=Ie(i),t=zt(i),n=t(e,e.neg(e.ONE)),r=t(e,n),s=t(e,e.neg(n)),a=(i+Gn)/Zt;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,n);const l=o.mul(u,r),y=o.mul(u,s),d=o.eql(o.sqr(f),c),b=o.eql(o.sqr(l),c);u=o.cmov(u,f,d),f=o.cmov(y,l,b);const w=o.eql(o.sqr(f),c),p=o.cmov(u,f,w);return tt(o,p,c),p}}function zt(i){if(i<Vt)throw new Error("sqrt is not defined for small field");let e=i-M,t=0;for(;e%ue===V;)e/=ue,t++;let n=ue;const r=Ie(i);for(;Gt(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return jt;let s=r.pow(n,e);const a=(e+M)/ue;return function(c,u){if(c.is0(u))return u;if(Gt(c,u)!==1)throw new Error("Cannot find square root");let f=t,l=c.mul(c.ONE,s),y=c.pow(u,e),d=c.pow(u,a);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let b=1,w=c.sqr(y);for(;!c.eql(w,c.ONE);)if(b++,w=c.sqr(w),b===f)throw new Error("Cannot find square root");const p=M<<BigInt(f-b-1),x=c.pow(l,p);f=b,l=c.sqr(x),y=c.mul(y,l),d=c.mul(d,x)}return d}}function ei(i){return i%Ut===Vt?jt:i%Ft===Wt?Xn:i%Zt===Jn?Qn(i):zt(i)}const ti=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ni(i){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ti.reduce((n,r)=>(n[r]="function",n),e);return Mt(i,t),i}function ii(i,e,t){if(t<V)throw new Error("invalid exponent, negatives unsupported");if(t===V)return i.ONE;if(t===M)return e;let n=i.ONE,r=e;for(;t>V;)t&M&&(n=i.mul(n,r)),r=i.sqr(r),t>>=M;return n}function Yt(i,e,t=!1){const n=new Array(e.length).fill(t?i.ZERO:void 0),r=e.reduce((a,o,c)=>i.is0(o)?a:(n[c]=a,i.mul(a,o)),i.ONE),s=i.inv(r);return e.reduceRight((a,o,c)=>i.is0(o)?a:(n[c]=i.mul(a,n[c]),i.mul(a,o)),s),n}function Gt(i,e){const t=(i.ORDER-M)/ue,n=i.pow(e,t),r=i.eql(n,i.ONE),s=i.eql(n,i.ZERO),a=i.eql(n,i.neg(i.ONE));if(!r&&!s&&!a)throw new Error("invalid Legendre symbol result");return r?1:s?0:-1}function ri(i,e){e!==void 0&&Z(e);const t=e!==void 0?e:i.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}class si{constructor(e,t={}){h(this,"ORDER");h(this,"BITS");h(this,"BYTES");h(this,"isLE");h(this,"ZERO",V);h(this,"ONE",M);h(this,"_lengths");h(this,"_sqrt");h(this,"_mod");var a;if(e<=V)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=(a=t.allowedLengths)==null?void 0:a.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:s}=ri(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 j(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return V<=e&&e<this.ORDER}is0(e){return e===V}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&M)===M}neg(e){return j(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return j(e*e,this.ORDER)}add(e,t){return j(e+t,this.ORDER)}sub(e,t){return j(e-t,this.ORDER)}mul(e,t){return j(e*t,this.ORDER)}pow(e,t){return ii(this,e,t)}div(e,t){return j(e*Kt(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 Kt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ei(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Nt(e,this.BYTES):et(e,this.BYTES)}fromBytes(e,t=!1){L(e);const{_lengths:n,BYTES:r,isLE:s,ORDER:a,_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 c=s?Lt(e):Qe(e);if(o&&(c=j(c,a)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Yt(this,e)}cmov(e,t,n){return n?t:e}}function Ie(i,e={}){return new si(i,e)}function Jt(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 oi(i){const e=Jt(i);return e+Math.ceil(e/2)}function ai(i,e,t=!1){L(i);const n=i.length,r=Jt(e),s=oi(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const a=t?Lt(i):Qe(i),o=j(a,e-M)+M;return t?Nt(o,r):et(o,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ge=BigInt(0),he=BigInt(1);function $e(i,e){const t=e.negate();return i?t:e}function Xt(i,e){const t=Yt(i.Fp,e.map(n=>n.Z));return e.map((n,r)=>i.fromAffine(n.toAffine(t[r])))}function Qt(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function nt(i,e){Qt(i,e);const t=Math.ceil(e/i)+1,n=2**(i-1),r=2**i,s=qt(i),a=BigInt(i);return{windows:t,windowSize:n,mask:s,maxNumber:r,shiftBy:a}}function en(i,e,t){const{windowSize:n,mask:r,maxNumber:s,shiftBy:a}=t;let o=Number(i&r),c=i>>a;o>n&&(o-=s,c+=he);const u=e*n,f=u+Math.abs(o)-1,l=o===0,y=o<0,d=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:y,isNegF:d,offsetF:u}}const it=new WeakMap,tn=new WeakMap;function rt(i){return tn.get(i)||1}function nn(i){if(i!==ge)throw new Error("invalid wNAF")}class ci{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>ge;)t&he&&(n=n.add(r)),r=r.double(),t>>=he;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=nt(t,this.bits),s=[];let a=e,o=a;for(let c=0;c<n;c++){o=a,s.push(o);for(let u=1;u<r;u++)o=o.add(a),s.push(o);a=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 a=nt(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:y,offsetF:d}=en(n,o,a);n=c,f?s=s.add($e(y,t[d])):r=r.add($e(l,t[u]))}return nn(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=nt(e,this.bits);for(let a=0;a<s.windows&&n!==ge;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=en(n,a,s);if(n=o,!u){const l=t[c];r=r.add(f?l.negate():l)}}return nn(n),r}getPrecomputes(e,t,n){let r=it.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(r=n(r)),it.set(t,r))),r}cached(e,t,n){const r=rt(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=rt(e);return s===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Qt(t,this.bits),tn.set(e,t),it.delete(e)}hasCache(e){return rt(e)!==1}}function li(i,e,t,n){let r=e,s=i.ZERO,a=i.ZERO;for(;t>ge||n>ge;)t&he&&(s=s.add(r)),n&he&&(a=a.add(r)),r=r.double(),t>>=he,n>>=he;return{p1:s,p2:a}}function rn(i,e,t){if(e){if(e.ORDER!==i)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ni(e),e}else return Ie(i,{isLE:t})}function ui(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 c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>ge))throw new Error(`CURVE.${c} must be positive bigint`)}const r=rn(e.p,t.Fp,n),s=rn(e.n,t.Fn,n),o=["Gx","Gy","a","b"];for(const c of o)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function hi(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 sn=(i,e)=>(i+(i>=0?e:-e)/di)/e;function fi(i,e,t){const[[n,r],[s,a]]=e,o=sn(a*i,t),c=sn(-r*i,t);let u=i-o*n-c*s,f=-o*r-c*a;const l=u<xe,y=f<xe;l&&(u=-u),y&&(f=-f);const d=qt(Math.ceil(Yn(t)/2))+He;if(u<xe||u>=d||f<xe||f>=d)throw new Error("splitScalar (endomorphism): failed, k="+i);return{k1neg:l,k1:u,k2neg:y,k2:f}}const xe=BigInt(0),He=BigInt(1),di=BigInt(2),Le=BigInt(3),bi=BigInt(4);function yi(i,e={}){const t=ui("weierstrass",i,e),{Fp:n,Fn:r}=t;let s=t.CURVE;const{h:a,n:o}=s;Mt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=gi(n,r);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(_,g,m){const{x:S,y:R}=g.toAffine(),B=n.toBytes(S);if($t(m,"isCompressed"),m){f();const A=!n.isOdd(R);return Oe(wi(A),B)}else return Oe(Uint8Array.of(4),B,n.toBytes(R))}function y(_){L(_,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=u,S=_.length,R=_[0],B=_.subarray(1);if(S===g&&(R===2||R===3)){const A=n.fromBytes(B);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");const T=w(A);let E;try{E=n.sqrt(T)}catch(F){const N=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}f();const k=n.isOdd(E);return(R&1)===1!==k&&(E=n.neg(E)),{x:A,y:E}}else if(S===m&&R===4){const A=n.BYTES,T=n.fromBytes(B.subarray(0,A)),E=n.fromBytes(B.subarray(A,A*2));if(!p(T,E))throw new Error("bad point: is not on curve");return{x:T,y:E}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${m}`)}const d=e.toBytes||l,b=e.fromBytes||y;function w(_){const g=n.sqr(_),m=n.mul(g,_);return n.add(n.add(m,n.mul(_,s.a)),s.b)}function p(_,g){const m=n.sqr(g),S=w(_);return n.eql(m,S)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const x=n.mul(n.pow(s.a,Le),bi),H=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(x,H)))throw new Error("bad curve params: a or b");function v(_,g,m=!1){if(!n.isValid(g)||m&&n.is0(g))throw new Error(`bad point coordinate ${_}`);return g}function q(_){if(!(_ instanceof be))throw new Error("Weierstrass Point expected")}function O(_){if(!c||!c.basises)throw new Error("no endo");return fi(_,c.basises,r.ORDER)}const U=Dt((_,g)=>{const{X:m,Y:S,Z:R}=_;if(n.eql(R,n.ONE))return{x:m,y:S};const B=_.is0();g==null&&(g=B?n.ONE:n.inv(R));const A=n.mul(m,g),T=n.mul(S,g),E=n.mul(R,g);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:A,y:T}}),xr=Dt(_=>{if(_.is0()){if(e.allowInfinityPoint&&!n.is0(_.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=_.toAffine();if(!n.isValid(g)||!n.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(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Sn(_,g,m,S,R){return m=new be(n.mul(m.X,_),m.Y,m.Z),g=$e(S,g),m=$e(R,m),g.add(m)}const $=class ${constructor(g,m,S){h(this,"X");h(this,"Y");h(this,"Z");this.X=v("x",g),this.Y=v("y",m,!0),this.Z=v("z",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){const{x:m,y:S}=g||{};if(!g||!n.isValid(m)||!n.isValid(S))throw new Error("invalid affine point");if(g instanceof $)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(S)?$.ZERO:new $(m,S,n.ONE)}static fromBytes(g){const m=$.fromAffine(b(L(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return $.fromBytes(K(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return Ae.createCache(this,g),m||this.multiply(Le),this}assertValidity(){xr(this)}hasEvenY(){const{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){q(g);const{X:m,Y:S,Z:R}=this,{X:B,Y:A,Z:T}=g,E=n.eql(n.mul(m,T),n.mul(B,R)),k=n.eql(n.mul(S,T),n.mul(A,R));return E&&k}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){const{a:g,b:m}=s,S=n.mul(m,Le),{X:R,Y:B,Z:A}=this;let T=n.ZERO,E=n.ZERO,k=n.ZERO,P=n.mul(R,R),F=n.mul(B,B),N=n.mul(A,A),C=n.mul(R,B);return C=n.add(C,C),k=n.mul(R,A),k=n.add(k,k),T=n.mul(g,k),E=n.mul(S,N),E=n.add(T,E),T=n.sub(F,E),E=n.add(F,E),E=n.mul(T,E),T=n.mul(C,T),k=n.mul(S,k),N=n.mul(g,N),C=n.sub(P,N),C=n.mul(g,C),C=n.add(C,k),k=n.add(P,P),P=n.add(k,P),P=n.add(P,N),P=n.mul(P,C),E=n.add(E,P),N=n.mul(B,A),N=n.add(N,N),P=n.mul(N,C),T=n.sub(T,P),k=n.mul(N,F),k=n.add(k,k),k=n.add(k,k),new $(T,E,k)}add(g){q(g);const{X:m,Y:S,Z:R}=this,{X:B,Y:A,Z:T}=g;let E=n.ZERO,k=n.ZERO,P=n.ZERO;const F=s.a,N=n.mul(s.b,Le);let C=n.mul(m,B),z=n.mul(S,A),Y=n.mul(R,T),Ee=n.add(m,S),D=n.add(B,A);Ee=n.mul(Ee,D),D=n.add(C,z),Ee=n.sub(Ee,D),D=n.add(m,R);let te=n.add(B,T);return D=n.mul(D,te),te=n.add(C,Y),D=n.sub(D,te),te=n.add(S,R),E=n.add(A,T),te=n.mul(te,E),E=n.add(z,Y),te=n.sub(te,E),P=n.mul(F,D),E=n.mul(N,Y),P=n.add(E,P),E=n.sub(z,P),P=n.add(z,P),k=n.mul(E,P),z=n.add(C,C),z=n.add(z,C),Y=n.mul(F,Y),D=n.mul(N,D),z=n.add(z,Y),Y=n.sub(C,Y),Y=n.mul(F,Y),D=n.add(D,Y),C=n.mul(z,D),k=n.add(k,C),C=n.mul(te,D),E=n.mul(Ee,E),E=n.sub(E,C),C=n.mul(Ee,z),P=n.mul(te,P),P=n.add(P,C),new $(E,k,P)}subtract(g){return this.add(g.negate())}is0(){return this.equals($.ZERO)}multiply(g){const{endo:m}=e;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let S,R;const B=A=>Ae.cached(this,A,T=>Xt($,T));if(m){const{k1neg:A,k1:T,k2neg:E,k2:k}=O(g),{p:P,f:F}=B(T),{p:N,f:C}=B(k);R=F.add(C),S=Sn(m.beta,P,N,A,E)}else{const{p:A,f:T}=B(g);S=A,R=T}return Xt($,[S,R])[0]}multiplyUnsafe(g){const{endo:m}=e,S=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===xe||S.is0())return $.ZERO;if(g===He)return S;if(Ae.hasCache(this))return this.multiply(g);if(m){const{k1neg:R,k1:B,k2neg:A,k2:T}=O(g),{p1:E,p2:k}=li($,S,B,T);return Sn(m.beta,E,k,R,A)}else return Ae.unsafe(S,g)}toAffine(g){return U(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return a===He?!0:g?g($,this):Ae.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:g}=e;return a===He?this:g?g($,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(g=!0){return $t(g,"isCompressed"),this.assertValidity(),d($,this,g)}toHex(g=!0){return I(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};h($,"BASE",new $(s.Gx,s.Gy,n.ONE)),h($,"ZERO",new $(n.ZERO,n.ONE,n.ZERO)),h($,"Fp",n),h($,"Fn",r);let be=$;const xn=r.BITS,Ae=new ci(be,e.endo?Math.ceil(xn/2):xn);return be.BASE.precompute(8),be}function wi(i){return Uint8Array.of(i?2:3)}function gi(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 Ne={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},pi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},mi=BigInt(0),st=BigInt(2);function Ei(i){const e=Ne.p,t=BigInt(3),n=BigInt(6),r=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=i*i*i%e,f=u*u*i%e,l=W(f,t,e)*f%e,y=W(l,t,e)*f%e,d=W(y,st,e)*u%e,b=W(d,r,e)*d%e,w=W(b,s,e)*b%e,p=W(w,o,e)*w%e,x=W(p,c,e)*p%e,H=W(x,o,e)*w%e,v=W(H,t,e)*f%e,q=W(v,a,e)*b%e,O=W(q,n,e)*u%e,U=W(O,st,e);if(!qe.eql(qe.sqr(U),i))throw new Error("Cannot find square root");return U}const qe=Ie(Ne.p,{sqrt:Ei}),pe=yi(Ne,{Fp:qe,endo:pi}),on={};function Me(i,...e){let t=on[i];if(t===void 0){const n=Ce(jn(i));t=Oe(n,n),on[i]=t}return Ce(Oe(t,...e))}const ot=i=>i.toBytes(!0).slice(1),at=i=>i%st===mi;function ct(i){const{Fn:e,BASE:t}=pe,n=e.fromBytes(i),r=t.multiply(n);return{scalar:at(r.y)?n:e.neg(n),bytes:ot(r)}}function an(i){const e=qe;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);at(r)||(r=e.neg(r));const s=pe.fromAffine({x:i,y:r});return s.assertValidity(),s}const Re=Qe;function cn(...i){return pe.Fn.create(Re(Me("BIP0340/challenge",...i)))}function ln(i){return ct(i).bytes}function vi(i,e,t=Rt(32)){const{Fn:n}=pe,r=L(i,void 0,"message"),{bytes:s,scalar:a}=ct(e),o=L(t,32,"auxRand"),c=n.toBytes(a^Re(Me("BIP0340/aux",o))),u=Me("BIP0340/nonce",c,s,r),{bytes:f,scalar:l}=ct(u),y=cn(f,s,r),d=new Uint8Array(64);if(d.set(f,0),d.set(n.toBytes(n.create(l+y*a)),32),!un(d,r,s))throw new Error("sign: Invalid signature produced");return d}function un(i,e,t){const{Fp:n,Fn:r,BASE:s}=pe,a=L(i,64,"signature"),o=L(e,void 0,"message"),c=L(t,32,"publicKey");try{const u=an(Re(c)),f=Re(a.subarray(0,32));if(!n.isValidNot0(f))return!1;const l=Re(a.subarray(32,64));if(!r.isValidNot0(l))return!1;const y=cn(r.toBytes(f),ot(u),o),d=s.multiplyUnsafe(l).add(u.multiplyUnsafe(r.neg(y))),{x:b,y:w}=d.toAffine();return!(d.is0()||!at(w)||b!==f)}catch{return!1}}const J=(()=>{const t=(n=Rt(48))=>ai(n,Ne.n);return{keygen:hi(t,ln),getPublicKey:ln,sign:vi,verify:un,Point:pe,utils:{randomSecretKey:t,taggedHash:Me,lift_x:an,pointToBytes:ot},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),fe=Symbol("verified"),Si=i=>i instanceof Object;function xi(i){if(!Si(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}let Ri=class{generateSecretKey(){return J.utils.randomSecretKey()}getPublicKey(e){return I(J.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=I(J.getPublicKey(t)),n.id=lt(n),n.sig=I(J.sign(K(lt(n)),t)),n[fe]=!0,n}verifyEvent(e){if(typeof e[fe]=="boolean")return e[fe];const t=lt(e);if(t!==e.id)return e[fe]=!1,!1;try{const n=J.verify(K(e.sig),K(t),K(e.pubkey));return e[fe]=n,n}catch{return e[fe]=!1,!1}}};function Ti(i){if(!xi(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=Ce(Hn.encode(Ti(i)));return I(e)}const De=new Ri;De.generateSecretKey,De.getPublicKey,De.finalizeEvent;const ki=De.verifyEvent,Ai=22242;function Oi(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,a])=>s===t.slice(1)&&r.indexOf(a)!==-1))return!1}return!(i.since&&e.created_at<i.since||i.until&&e.created_at>i.until)}function Pi(i,e){for(let t=0;t<i.length;t++)if(Oi(i[t],e))return!0;return!1}function _i(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 Bi(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 Ci(i,e){return{kind:Ai,created_at:Math.floor(Date.now()/1e3),tags:[["relay",i],["challenge",e]],content:""}}let hn=class extends Error{constructor(e,t){super(`Tried to send message '${e} on a closed connection to ${t}.`),this.name="SendingOnClosedConnection"}},Ii=class Rn{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=we(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 Rn(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 a of this.openSubs.values()){if(a.eosed=!1,s)for(let o=0;o<a.filters.length;o++)a.lastEmitted&&(a.filters[o].since=a.lastEmitted+1);a.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 hn(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(Ci(this.url,t)),a=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: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 t=new Promise((n,r)=>{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: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,a)=>{this.openCountRequests.set(n,{resolve:s,reject:a})});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,a;const t=e.data;if(!t)return;const n=Bi(t);if(n){const o=this.openSubs.get(n);if(!o)return;const c=_i(t,"id"),u=(r=o.alreadyHaveEvent)==null?void 0:r.call(o,c);if((s=o.receivedEvent)==null||s.call(o,this,c),u)return}try{let o=JSON.parse(t);switch(o[0]){case"EVENT":{const c=this.openSubs.get(o[1]),u=o[2];this.verifyEvent(u)&&Pi(c.filters,u)&&c.onevent(u),(!c.lastEmitted||c.lastEmitted<u.created_at)&&(c.lastEmitted=u.created_at);return}case"COUNT":{const c=o[1],u=o[2],f=this.openCountRequests.get(c);f&&(f.resolve(u.count),this.openCountRequests.delete(c));return}case"EOSE":{const c=this.openSubs.get(o[1]);if(!c)return;c.receivedEose();return}case"OK":{const c=o[1],u=o[2],f=o[3],l=this.openEventPublishes.get(c);l&&(clearTimeout(l.timeout),u?l.resolve(f):l.reject(new Error(f)),this.openEventPublishes.delete(c));return}case"CLOSED":{const c=o[1],u=this.openSubs.get(c);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 c=this.openSubs.get(o[1]);(a=c==null?void 0:c.oncustom)==null||a.call(c,o);return}}}catch(o){const[c,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 hn))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 Hi=i=>(i[fe]=!0,!0);let Li=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=we(e);let n=this.relays.get(e);if(n||(n=new Ii(e,{verifyEvent:this.trustedRelayURLs.has(e)?Hi: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(we).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 a=0;a<e.length;a++){const o=we(e[a]);r.find(c=>c.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:b,filter:w}=d;n.has(b)||n.set(b,[]),n.get(b).push(w)}const r=Array.from(n.entries()).map(([d,b])=>({url:d,filters:b}));this.trackRelays&&(t.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=[],o=[];let c=d=>{var b;o[d]||(o[d]=!0,o.filter(w=>w).length===r.length&&((b=t.oneose)==null||b.call(t),c=()=>{}))};const u=[];let f=(d,b)=>{var w;u[d]||(c(d),u[d]=b,u.filter(p=>p).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 b=s.has(d);return s.add(d),b},y=Promise.all(r.map(async({url:d,filters:b},w)=>{var H,v,q;if(((H=this.allowConnectingToRelay)==null?void 0:H.call(this,d,["read",b]))===!1){f(w,"connection skipped by allowConnectingToRelay");return}let p;try{p=await this.ensureRelay(d,{connectionTimeout:this.maxWaitForConnection<(t.maxWait||0)?Math.max(t.maxWait*.8,t.maxWait-1e3):this.maxWaitForConnection,abort:t.abort})}catch(O){(v=this.onRelayConnectionFailure)==null||v.call(this,d),f(w,(O==null?void 0:O.message)||String(O));return}(q=this.onRelayConnectionSuccess)==null||q.call(this,d);let x=p.subscribe(b,{...t,oneose:()=>c(w),onclose:O=>{O.startsWith("auth-required: ")&&t.onauth?p.auth(t.onauth).then(()=>{p.subscribe(b,{...t,oneose:()=>c(w),onclose:U=>{f(w,U)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort})}).catch(U=>{f(w,`auth was required and attempted, but failed with: ${U}`)}):f(w,O)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort});a.push(x)}));return{async close(d){await y,a.forEach(b=>{b.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(a){s.push(a)},onclose(a){r(s)}})})}async get(e,t,n){t.limit=1;const r=await this.querySync(e,t,n);return r.sort((s,a)=>a.created_at-s.created_at),r[0]||null}publish(e,t,n){return e.map(we).map(async(r,s,a)=>{var c,u;if(a.indexOf(r)!==s)return Promise.reject("duplicate url");if(((c=this.allowConnectingToRelay)==null?void 0:c.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 fn;try{fn=WebSocket}catch{}let Ni=class extends Li{constructor(e){super({verifyEvent:ki,websocketImplementation:fn,maxWaitForConnection:3e3,...e})}};var qi=Math.pow(2,8)-1,Mi=Math.pow(2,16)-1,Di=Math.pow(2,32)-1;const Vi=function(i){var e=i-1;if(e<=qi)return Uint8Array;if(e<=Mi)return Uint16Array;if(e<=Di)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"|