UNPKG

nostr-web-components

Version:

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

1 lines 85 kB
var nostr_event_json=(function(){"use strict";var xr=Object.defineProperty;var Sr=(le,F,H)=>F in le?xr(le,F,{enumerable:!0,configurable:!0,writable:!0,value:H}):le[F]=H;var h=(le,F,H)=>Sr(le,typeof F!="symbol"?F+"":F,H);/*! 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 F(i,e=""){if(!Number.isSafeInteger(i)||i<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${i}`)}}function H(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 Et(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){H(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 Fe(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}function Ze(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Y(i,e){return i<<32-e|i>>>e}const vt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kn=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function P(i){if(H(i),vt)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 Z(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);if(vt)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 Ae(...i){let e=0;for(let n=0;n<i.length;n++){const r=i[n];H(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 On(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 St(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 An=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 Rt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Tt(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 _n(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 kt(i){if(!Number.isSafeInteger(i))throw new Error(`invalid integer: ${i}`)}function Ke(i){if(!Array.isArray(i))throw new Error("array expected")}function Ot(i,e){if(!Tt(!0,e))throw new Error(`${i}: array of strings expected`)}function At(i,e){if(!Tt(!1,e))throw new Error(`${i}: array of numbers expected`)}function Bn(...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 Pn(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=>(Ke(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=>(Ke(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),_e=(i,e)=>i+(e-_t(i,e)),Be=(()=>{let i=[];for(let e=0;e<40;e++)i.push(2**e);return i})();function je(i,e,t,n){if(Ke(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(_e(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${_e(e,t)}`);let r=0,s=0;const a=Be[e],o=Be[t]-1,c=[];for(const u of i){if(kt(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=Be[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(kt(i),i<=0||i>32)throw new Error("radix2: bits should be in (0..32]");if(_e(8,i)>32||_e(i,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!Rt(t))throw new Error("radix2.encode input should be Uint8Array");return je(Array.from(t),8,i,!e)},decode:t=>(At("radix2.decode",t),Uint8Array.from(je(t,i,8,e)))}}function Bt(i){return _n(i),function(...e){try{return i.apply(null,e)}catch{}}}const ze=Bn(Pn("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Cn("")),Pt=[996825010,642813549,513874426,1027748829,705979059];function xe(i){const e=i>>25;let t=(i&33554431)<<5;for(let n=0;n<Pt.length;n++)(e>>n&1)===1&&(t^=Pt[n]);return t}function Ct(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=xe(r)^a>>5}r=xe(r);for(let s=0;s<n;s++)r=xe(r)^i.charCodeAt(s)&31;for(let s of e)r=xe(r)^s;for(let s=0;s<6;s++)r=xe(r);return r^=t,ze.encode(je([r%Be[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,b,d=90){ve("bech32.encode prefix",l),Rt(b)&&(b=Array.from(b)),At("bech32.encode",b);const y=l.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+b.length;if(d!==!1&&w>d)throw new TypeError(`Length ${w} exceeds limit ${d}`);const p=l.toLowerCase(),T=Ct(p,b,e);return`${p}1${ze.encode(b)}${T}`}function o(l,b=90){ve("bech32.decode input",l);const d=l.length;if(d<8||b!==!1&&d>b)throw new TypeError(`invalid string length: ${d} (${l}). Expected (8..${b})`);const y=l.toLowerCase();if(l!==y&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=y.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const p=y.slice(0,w),T=y.slice(w+1);if(T.length<6)throw new Error("Data must be at least 6 characters long");const I=ze.decode(T).slice(0,-6),U=Ct(p,I,e);if(!T.endsWith(U))throw new Error(`Invalid checksum in ${l}: expected "${U}"`);return{prefix:p,words:I}}const c=Bt(o);function u(l){const{prefix:b,words:d}=o(l,!1);return{prefix:b,words:d,bytes:n(d)}}function f(l,b){return a(l,r(b))}return{encode:a,decode:o,encodeFromBytes:f,decodeToBytes:u,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:r}}const be=$n("bech32"),Pe=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}=be.decode(i,Ln),n=new Uint8Array(be.fromWords(t));switch(e){case"nprofile":{let l=Ye(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:P(l[0][0]),relays:l[1]?l[1].map(b=>Pe.decode(b)):[]}}}case"nevent":{let l=Ye(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:P(l[0][0]),relays:l[1]?l[1].map(b=>Pe.decode(b)):[],author:(a=l[2])!=null&&a[0]?P(l[2][0]):void 0,kind:(o=l[3])!=null&&o[0]?parseInt(P(l[3][0]),16):void 0}}}case"naddr":{let l=Ye(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:Pe.decode(l[0][0]),pubkey:P(l[2][0]),kind:parseInt(P(l[3][0]),16),relays:l[1]?l[1].map(b=>Pe.decode(b)):[]}}}case"nsec":return{type:e,data:n};case"npub":case"note":return{type:e,data:P(n)};default:throw new Error(`unknown prefix ${e}`)}}function Ye(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 Un(i,e,t){return i&e^i&t^e&t}class Wn{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=Ze(this.buffer)}update(e){Et(this),H(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=Ze(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){Et(this),Tn(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:s}=this;let{pos:a}=this;t[a++]=128,Fe(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=Ze(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]),Vn=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 Dn extends Wn{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 b=se[l-15],d=se[l-2],y=Y(b,7)^Y(b,18)^b>>>3,w=Y(d,17)^Y(d,19)^d>>>10;se[l]=w+se[l-7]+y+se[l-16]|0}let{A:n,B:r,C:s,D:a,E:o,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const b=Y(o,6)^Y(o,11)^Y(o,25),d=f+b+Mn(o,c,u)+Vn[l]+se[l]|0,w=(Y(n,2)^Y(n,13)^Y(n,22))+Un(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(){Fe(se)}destroy(){this.set(0,0,0,0,0,0,0,0),Fe(this.buffer)}}class Fn extends Dn{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=On(()=>new Fn,An(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Je=BigInt(0),Ge=BigInt(1);function It(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 F(i);return i}function $t(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Je:BigInt("0x"+i)}function Xe(i){return $t(P(i))}function Ht(i){return $t(P(Kn(H(i)).reverse()))}function Qe(i,e){F(e),i=Zn(i);const t=Z(i.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Lt(i,e){return Qe(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>>=Ge,e+=1);return e}const Nt=i=>(Ge<<BigInt(i))-Ge;function qt(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 Mt(i){const e=new WeakMap;return(t,...n)=>{const r=e.get(t);if(r!==void 0)return r;const s=i(t,...n);return e.set(t,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const M=BigInt(0),N=BigInt(1),ue=BigInt(2),Ut=BigInt(3),Wt=BigInt(4),Vt=BigInt(5),Jn=BigInt(7),Dt=BigInt(8),Gn=BigInt(9),Ft=BigInt(16);function K(i,e){const t=i%e;return t>=M?t:e+t}function W(i,e,t){let n=i;for(;e-- >M;)n*=n,n%=t;return n}function Zt(i,e){if(i===M)throw new Error("invert: expected non-zero number");if(e<=M)throw new Error("invert: expected positive modulus, got "+e);let t=K(i,e),n=e,r=M,s=N;for(;t!==M;){const o=n/t,c=n%t,u=r-s*o;n=t,t=c,r=s,s=u}if(n!==N)throw new Error("invert: does not exist");return K(r,e)}function et(i,e,t){if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function Kt(i,e){const t=(i.ORDER+N)/Wt,n=i.pow(e,t);return et(i,n,e),n}function Xn(i,e){const t=(i.ORDER-Vt)/Dt,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 et(i,o,e),o}function Qn(i){const e=Ie(i),t=jt(i),n=t(e,e.neg(e.ONE)),r=t(e,n),s=t(e,e.neg(n)),a=(i+Jn)/Ft;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,n);const l=o.mul(u,r),b=o.mul(u,s),d=o.eql(o.sqr(f),c),y=o.eql(o.sqr(l),c);u=o.cmov(u,f,d),f=o.cmov(b,l,y);const w=o.eql(o.sqr(f),c),p=o.cmov(u,f,w);return et(o,p,c),p}}function jt(i){if(i<Ut)throw new Error("sqrt is not defined for small field");let e=i-N,t=0;for(;e%ue===M;)e/=ue,t++;let n=ue;const r=Ie(i);for(;Yt(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Kt;let s=r.pow(n,e);const a=(e+N)/ue;return function(c,u){if(c.is0(u))return u;if(Yt(c,u)!==1)throw new Error("Cannot find square root");let f=t,l=c.mul(c.ONE,s),b=c.pow(u,e),d=c.pow(u,a);for(;!c.eql(b,c.ONE);){if(c.is0(b))return c.ZERO;let y=1,w=c.sqr(b);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===f)throw new Error("Cannot find square root");const p=N<<BigInt(f-y-1),T=c.pow(l,p);f=y,l=c.sqr(T),b=c.mul(b,l),d=c.mul(d,T)}return d}}function ei(i){return i%Wt===Ut?Kt:i%Dt===Vt?Xn:i%Ft===Gn?Qn(i):jt(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 qt(i,t),i}function ii(i,e,t){if(t<M)throw new Error("invalid exponent, negatives unsupported");if(t===M)return i.ONE;if(t===N)return e;let n=i.ONE,r=e;for(;t>M;)t&N&&(n=i.mul(n,r)),r=i.sqr(r),t>>=N;return n}function zt(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 Yt(i,e){const t=(i.ORDER-N)/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&&F(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",M);h(this,"ONE",N);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 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 K(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return M<=e&&e<this.ORDER}is0(e){return e===M}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&N)===N}neg(e){return K(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return K(e*e,this.ORDER)}add(e,t){return K(e+t,this.ORDER)}sub(e,t){return K(e-t,this.ORDER)}mul(e,t){return K(e*t,this.ORDER)}pow(e,t){return ii(this,e,t)}div(e,t){return K(e*Zt(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 Zt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ei(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Lt(e,this.BYTES):Qe(e,this.BYTES)}fromBytes(e,t=!1){H(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?Ht(e):Xe(e);if(o&&(c=K(c,a)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return zt(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){H(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?Ht(i):Xe(i),o=K(a,e-N)+N;return t?Lt(o,r):Qe(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 Gt(i,e){const t=zt(i.Fp,e.map(n=>n.Z));return e.map((n,r)=>i.fromAffine(n.toAffine(t[r])))}function Xt(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function tt(i,e){Xt(i,e);const t=Math.ceil(e/i)+1,n=2**(i-1),r=2**i,s=Nt(i),a=BigInt(i);return{windows:t,windowSize:n,mask:s,maxNumber:r,shiftBy:a}}function Qt(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,b=o<0,d=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:b,isNegF:d,offsetF:u}}const nt=new WeakMap,en=new WeakMap;function it(i){return en.get(i)||1}function tn(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}=tt(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=tt(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:b,offsetF:d}=Qt(n,o,a);n=c,f?s=s.add($e(b,t[d])):r=r.add($e(l,t[u]))}return tn(n),{p:r,f:s}}wNAFUnsafe(e,t,n,r=this.ZERO){const s=tt(e,this.bits);for(let a=0;a<s.windows&&n!==ge;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=Qt(n,a,s);if(n=o,!u){const l=t[c];r=r.add(f?l.negate():l)}}return tn(n),r}getPrecomputes(e,t,n){let r=nt.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(r=n(r)),nt.set(t,r))),r}cached(e,t,n){const r=it(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const s=it(e);return s===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,r)}createCache(e,t){Xt(t,this.bits),en.set(e,t),nt.delete(e)}hasCache(e){return it(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 nn(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=nn(e.p,t.Fp,n),s=nn(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 rn=(i,e)=>(i+(i>=0?e:-e)/di)/e;function fi(i,e,t){const[[n,r],[s,a]]=e,o=rn(a*i,t),c=rn(-r*i,t);let u=i-o*n-c*s,f=-o*r-c*a;const l=u<Se,b=f<Se;l&&(u=-u),b&&(f=-f);const d=Nt(Math.ceil(Yn(t)/2))+He;if(u<Se||u>=d||f<Se||f>=d)throw new Error("splitScalar (endomorphism): failed, k="+i);return{k1neg:l,k1:u,k2neg:b,k2:f}}const Se=BigInt(0),He=BigInt(1),di=BigInt(2),Le=BigInt(3),yi=BigInt(4);function bi(i,e={}){const t=ui("weierstrass",i,e),{Fp:n,Fn:r}=t;let s=t.CURVE;const{h:a,n:o}=s;qt(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(A,g,m){const{x:v,y:x}=g.toAffine(),_=n.toBytes(v);if(It(m,"isCompressed"),m){f();const k=!n.isOdd(x);return Ae(wi(k),_)}else return Ae(Uint8Array.of(4),_,n.toBytes(x))}function b(A){H(A,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=u,v=A.length,x=A[0],_=A.subarray(1);if(v===g&&(x===2||x===3)){const k=n.fromBytes(_);if(!n.isValid(k))throw new Error("bad point: is not on curve, wrong x");const S=w(k);let E;try{E=n.sqrt(S)}catch(D){const L=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+L)}f();const R=n.isOdd(E);return(x&1)===1!==R&&(E=n.neg(E)),{x:k,y:E}}else if(v===m&&x===4){const k=n.BYTES,S=n.fromBytes(_.subarray(0,k)),E=n.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,y=e.fromBytes||b;function w(A){const g=n.sqr(A),m=n.mul(g,A);return n.add(n.add(m,n.mul(A,s.a)),s.b)}function p(A,g){const m=n.sqr(g),v=w(A);return n.eql(m,v)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const T=n.mul(n.pow(s.a,Le),yi),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(T,I)))throw new Error("bad curve params: a or b");function U(A,g,m=!1){if(!n.isValid(g)||m&&n.is0(g))throw new Error(`bad point coordinate ${A}`);return g}function ee(A){if(!(A instanceof ye))throw new Error("Weierstrass Point expected")}function $(A){if(!c||!c.basises)throw new Error("no endo");return fi(A,c.basises,r.ORDER)}const V=Mt((A,g)=>{const{X:m,Y:v,Z:x}=A;if(n.eql(x,n.ONE))return{x:m,y:v};const _=A.is0();g==null&&(g=_?n.ONE:n.inv(x));const k=n.mul(m,g),S=n.mul(v,g),E=n.mul(x,g);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:k,y:S}}),vr=Mt(A=>{if(A.is0()){if(e.allowInfinityPoint&&!n.is0(A.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=A.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(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function xn(A,g,m,v,x){return m=new ye(n.mul(m.X,A),m.Y,m.Z),g=$e(v,g),m=$e(x,m),g.add(m)}const C=class C{constructor(g,m,v){h(this,"X");h(this,"Y");h(this,"Z");this.X=U("x",g),this.Y=U("y",m,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){const{x:m,y:v}=g||{};if(!g||!n.isValid(m)||!n.isValid(v))throw new Error("invalid affine point");if(g instanceof C)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(v)?C.ZERO:new C(m,v,n.ONE)}static fromBytes(g){const m=C.fromAffine(y(H(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return C.fromBytes(Z(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return Oe.createCache(this,g),m||this.multiply(Le),this}assertValidity(){vr(this)}hasEvenY(){const{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){ee(g);const{X:m,Y:v,Z:x}=this,{X:_,Y:k,Z:S}=g,E=n.eql(n.mul(m,S),n.mul(_,x)),R=n.eql(n.mul(v,S),n.mul(k,x));return E&&R}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){const{a:g,b:m}=s,v=n.mul(m,Le),{X:x,Y:_,Z:k}=this;let S=n.ZERO,E=n.ZERO,R=n.ZERO,O=n.mul(x,x),D=n.mul(_,_),L=n.mul(k,k),B=n.mul(x,_);return B=n.add(B,B),R=n.mul(x,k),R=n.add(R,R),S=n.mul(g,R),E=n.mul(v,L),E=n.add(S,E),S=n.sub(D,E),E=n.add(D,E),E=n.mul(S,E),S=n.mul(B,S),R=n.mul(v,R),L=n.mul(g,L),B=n.sub(O,L),B=n.mul(g,B),B=n.add(B,R),R=n.add(O,O),O=n.add(R,O),O=n.add(O,L),O=n.mul(O,B),E=n.add(E,O),L=n.mul(_,k),L=n.add(L,L),O=n.mul(L,B),S=n.sub(S,O),R=n.mul(L,D),R=n.add(R,R),R=n.add(R,R),new C(S,E,R)}add(g){ee(g);const{X:m,Y:v,Z:x}=this,{X:_,Y:k,Z:S}=g;let E=n.ZERO,R=n.ZERO,O=n.ZERO;const D=s.a,L=n.mul(s.b,Le);let B=n.mul(m,_),j=n.mul(v,k),z=n.mul(x,S),Ee=n.add(m,v),q=n.add(_,k);Ee=n.mul(Ee,q),q=n.add(B,j),Ee=n.sub(Ee,q),q=n.add(m,x);let te=n.add(_,S);return q=n.mul(q,te),te=n.add(B,z),q=n.sub(q,te),te=n.add(v,x),E=n.add(k,S),te=n.mul(te,E),E=n.add(j,z),te=n.sub(te,E),O=n.mul(D,q),E=n.mul(L,z),O=n.add(E,O),E=n.sub(j,O),O=n.add(j,O),R=n.mul(E,O),j=n.add(B,B),j=n.add(j,B),z=n.mul(D,z),q=n.mul(L,q),j=n.add(j,z),z=n.sub(B,z),z=n.mul(D,z),q=n.add(q,z),B=n.mul(j,q),R=n.add(R,B),B=n.mul(te,q),E=n.mul(Ee,E),E=n.sub(E,B),B=n.mul(Ee,j),O=n.mul(te,O),O=n.add(O,B),new C(E,R,O)}subtract(g){return this.add(g.negate())}is0(){return this.equals(C.ZERO)}multiply(g){const{endo:m}=e;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let v,x;const _=k=>Oe.cached(this,k,S=>Gt(C,S));if(m){const{k1neg:k,k1:S,k2neg:E,k2:R}=$(g),{p:O,f:D}=_(S),{p:L,f:B}=_(R);x=D.add(B),v=xn(m.beta,O,L,k,E)}else{const{p:k,f:S}=_(g);v=k,x=S}return Gt(C,[v,x])[0]}multiplyUnsafe(g){const{endo:m}=e,v=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===Se||v.is0())return C.ZERO;if(g===He)return v;if(Oe.hasCache(this))return this.multiply(g);if(m){const{k1neg:x,k1:_,k2neg:k,k2:S}=$(g),{p1:E,p2:R}=li(C,v,_,S);return xn(m.beta,E,R,x,k)}else return Oe.unsafe(v,g)}toAffine(g){return V(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return a===He?!0:g?g(C,this):Oe.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:g}=e;return a===He?this:g?g(C,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(g=!0){return It(g,"isCompressed"),this.assertValidity(),d(C,this,g)}toHex(g=!0){return P(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};h(C,"BASE",new C(s.Gx,s.Gy,n.ONE)),h(C,"ZERO",new C(n.ZERO,n.ONE,n.ZERO)),h(C,"Fp",n),h(C,"Fn",r);let ye=C;const Sn=r.BITS,Oe=new ci(ye,e.endo?Math.ceil(Sn/2):Sn);return ye.BASE.precompute(8),ye}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),rt=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,b=W(l,t,e)*f%e,d=W(b,rt,e)*u%e,y=W(d,r,e)*d%e,w=W(y,s,e)*y%e,p=W(w,o,e)*w%e,T=W(p,c,e)*p%e,I=W(T,o,e)*w%e,U=W(I,t,e)*f%e,ee=W(U,a,e)*y%e,$=W(ee,n,e)*u%e,V=W($,rt,e);if(!qe.eql(qe.sqr(V),i))throw new Error("Cannot find square root");return V}const qe=Ie(Ne.p,{sqrt:Ei}),pe=bi(Ne,{Fp:qe,endo:pi}),sn={};function Me(i,...e){let t=sn[i];if(t===void 0){const n=Ce(jn(i));t=Ae(n,n),sn[i]=t}return Ce(Ae(t,...e))}const st=i=>i.toBytes(!0).slice(1),ot=i=>i%rt===mi;function at(i){const{Fn:e,BASE:t}=pe,n=e.fromBytes(i),r=t.multiply(n);return{scalar:ot(r.y)?n:e.neg(n),bytes:st(r)}}function on(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);ot(r)||(r=e.neg(r));const s=pe.fromAffine({x:i,y:r});return s.assertValidity(),s}const Re=Xe;function an(...i){return pe.Fn.create(Re(Me("BIP0340/challenge",...i)))}function cn(i){return at(i).bytes}function vi(i,e,t=St(32)){const{Fn:n}=pe,r=H(i,void 0,"message"),{bytes:s,scalar:a}=at(e),o=H(t,32,"auxRand"),c=n.toBytes(a^Re(Me("BIP0340/aux",o))),u=Me("BIP0340/nonce",c,s,r),{bytes:f,scalar:l}=at(u),b=an(f,s,r),d=new Uint8Array(64);if(d.set(f,0),d.set(n.toBytes(n.create(l+b*a)),32),!ln(d,r,s))throw new Error("sign: Invalid signature produced");return d}function ln(i,e,t){const{Fp:n,Fn:r,BASE:s}=pe,a=H(i,64,"signature"),o=H(e,void 0,"message"),c=H(t,32,"publicKey");try{const u=on(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 b=an(r.toBytes(f),st(u),o),d=s.multiplyUnsafe(l).add(u.multiplyUnsafe(r.neg(b))),{x:y,y:w}=d.toAffine();return!(d.is0()||!ot(w)||y!==f)}catch{return!1}}const J=(()=>{const t=(n=St(48))=>ai(n,Ne.n);return{keygen:hi(t,cn),getPublicKey:cn,sign:vi,verify:ln,Point:pe,utils:{randomSecretKey:t,taggedHash:Me,lift_x:on,pointToBytes:st},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),fe=Symbol("verified"),xi=i=>i instanceof Object;function Si(i){if(!xi(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 P(J.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=P(J.getPublicKey(t)),n.id=ct(n),n.sig=P(J.sign(Z(ct(n)),t)),n[fe]=!0,n}verifyEvent(e){if(typeof e[fe]=="boolean")return e[fe];const t=ct(e);if(t!==e.id)return e[fe]=!1,!1;try{const n=J.verify(Z(e.sig),Z(t),Z(e.pubkey));return e[fe]=n,n}catch{return e[fe]=!1,!1}}};function Ti(i){if(!Si(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 ct(i){let e=Ce(Hn.encode(Ti(i)));return P(e)}const Ue=new Ri;Ue.generateSecretKey,Ue.getPublicKey,Ue.finalizeEvent;const ki=Ue.verifyEvent,Oi=22242;function Ai(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 _i(i,e){for(let t=0;t<i.length;t++)if(Ai(i[t],e))return!0;return!1}function Bi(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 Pi(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:Oi,created_at:Math.floor(Date.now()/1e3),tags:[["relay",i],["challenge",e]],content:""}}let un=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 un(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=Pi(t);if(n){const o=this.openSubs.get(n);if(!o)return;const c=Bi(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)&&_i(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 un))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:y,filter:w}=d;n.has(y)||n.set(y,[]),n.get(y).push(w)}const r=Array.from(n.entries()).map(([d,y])=>({url:d,filters:y}));this.trackRelays&&(t.receivedEvent=(d,y)=>{let w=this.seenOn.get(y);w||(w=new Set,this.seenOn.set(y,w)),w.add(d)});const s=new Set,a=[],o=[];let c=d=>{var y;o[d]||(o[d]=!0,o.filter(w=>w).length===r.length&&((y=t.oneose)==null||y.call(t),c=()=>{}))};const u=[];let f=(d,y)=>{var w;u[d]||(c(d),u[d]=y,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 y=s.has(d);return s.add(d),y},b=Promise.all(r.map(async({url:d,filters:y},w)=>{var I,U,ee;if(((I=this.allowConnectingToRelay)==null?void 0:I.call(this,d,["read",y]))===!1){f(w,"connection skipped by allowConnectingToRelay");return}let 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($){(U=this.onRelayConnectionFailure)==null||U.call(this,d),f(w,($==null?void 0:$.message)||String($));return}(ee=this.onRelayConnectionSuccess)==null||ee.call(this,d);let T=p.subscribe(y,{...t,oneose:()=>c(w),onclose:$=>{$.startsWith("auth-required: ")&&t.onauth?p.auth(t.onauth).then(()=>{p.subscribe(y,{...t,oneose:()=>c(w),onclose:V=>{f(w,V)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort})}).catch(V=>{f(w,`auth was required and attempted, but failed with: ${V}`)}):f(w,$)},alreadyHaveEvent:l,eoseTimeout:t.maxWait,abort:t.abort});a.push(T)}));return{async close(d){await b,a.forEach(y=>{y.close(d)})}}}subscribeEose(e,t,n){const r=this.subscribe(e,t,{...n,oneose(){r.close("closed automatically on eose")}});return r}subscribeManyEose(e,t,n){return this.subscribeEose(e,t,n)}async querySync(e,t,n){return new Promise(async r=>{const s=[];this.subscribeEose(e,t,{...n,onevent(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 hn;try{hn=WebSocket}catch{}let Ni=class extends Li{constructor(e){super({verifyEvent:ki,websocketImplementation:hn,maxWaitForConnection:3e3,...e})}};var qi=Math.pow(2,8)-1,Mi=Math.pow(2,16)-1,Ui=Math.pow(2,32)-1;const Wi=function(i){var e=i-1;if(e<=qi)return Uint8Array;if(e<=Mi)return Uint16Array;if(e<=Ui)return Uint32Array;throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};function oe(i){if(this.capacity=i,typeof this.capac