@konemono/nostr-login 1.7.52 → 1.7.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js
CHANGED
|
@@ -14,5 +14,5 @@ function isBytes$1(e){return e instanceof Uint8Array||null!=e&&"object"==typeof
|
|
|
14
14
|
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function chain(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map((e=>e.encode)).reduceRight(n,t),decode:e.map((e=>e.decode)).reduce(n,t)}}function alphabet(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map((t=>{if(t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]}))},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map((t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const n=e.indexOf(t);if(-1===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}}function join(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function padding(e,t="="){if("string"!=typeof t)throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let e of n)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let e of n)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let r=n.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function convertRadix(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const o=[],s=Array.from(e);for(s.forEach((e=>{if(e<0||e>=t)throw new Error(`Wrong integer: ${e}`)}));;){let e=0,i=!0;for(let o=r;o<s.length;o++){const a=s[o],l=t*e+a;if(!Number.isSafeInteger(l)||t*e/t!==e||l-a!=t*e)throw new Error("convertRadix: carry overflow");e=l%n;const c=Math.floor(l/n);if(s[o]=c,!Number.isSafeInteger(c)||c*n+e!==l)throw new Error("convertRadix: carry overflow");i&&(c?i=!1:r=o)}if(o.push(e),i)break}for(let t=0;t<e.length-1&&0===e[t];t++)o.push(0);return o.reverse()}const gcd=(e,t)=>t?gcd(t,e%t):e,radix2carry=(e,t)=>e+(t-gcd(e,t));function convertRadix2(e,t,n,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(radix2carry(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${radix2carry(t,n)}`);let o=0,s=0;const i=2**n-1,a=[];for(const r of e){if(r>=2**t)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(o=o<<t|r,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)a.push((o>>s-n&i)>>>0);o&=2**s-1}if(o=o<<n-s&i,!r&&s>=t)throw new Error("Excess padding");if(!r&&o)throw new Error(`Non-zero padding: ${o}`);return r&&s>0&&a.push(o>>>0),a}function radix(e){return{encode:t=>{if(!isBytes(t))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(convertRadix(t,e,256))}}}function radix2(e,t=!1){if(e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,e)>32||radix2carry(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!isBytes(n))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(convertRadix2(n,e,8,t))}}}function unsafeWrapper(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function checksum(e,t){if("function"!=typeof t)throw new Error("checksum fn should be function");return{encode(n){if(!isBytes(n))throw new Error("checksum.encode: input should be Uint8Array");const r=t(n).slice(0,e),o=new Uint8Array(n.length+e);return o.set(n),o.set(r,n.length),o},decode(n){if(!isBytes(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-e),o=t(r).slice(0,e),s=n.slice(-e);for(let t=0;t<e;t++)if(o[t]!==s[t])throw new Error("Invalid checksum");return r}}}const utils$1={alphabet:alphabet,chain:chain,checksum:checksum,convertRadix:convertRadix,convertRadix2:convertRadix2,radix:radix,radix2:radix2,join:join,padding:padding},base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),genBase58=e=>chain(radix(58),alphabet(e),join("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),createBase58check=e=>chain(checksum(4,(t=>e(e(t)))),base58),base58check$1=createBase58check,BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<POLYMOD_GENERATORS.length;e++)1==(t>>e&1)&&(n^=POLYMOD_GENERATORS[e]);return n}function bechChecksum(e,t,n=1){const r=e.length;let o=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);o=bech32Polymod(o)^n>>5}o=bech32Polymod(o);for(let t=0;t<r;t++)o=bech32Polymod(o)^31&e.charCodeAt(t);for(let e of t)o=bech32Polymod(o)^e;for(let e=0;e<6;e++)o=bech32Polymod(o);return o^=n,BECH_ALPHABET.encode(convertRadix2([o%2**30],30,5,!1))}function genBech32(e){const t="bech32"===e?1:734539939,n=radix2(5),r=n.decode,o=n.encode,s=unsafeWrapper(r);function i(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=r).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const s=e.slice(0,o),i=e.slice(o+1);if(i.length<6)throw new Error("Data must be at least 6 characters long");const a=BECH_ALPHABET.decode(i).slice(0,-6),l=bechChecksum(s,a,t);if(!i.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:s,words:a}}return{encode:function(e,n,r=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const o=e.length+7+n.length;if(!1!==r&&o>r)throw new TypeError(`Length ${o} exceeds limit ${r}`);const s=e.toLowerCase(),i=bechChecksum(s,n,t);return`${s}1${BECH_ALPHABET.encode(n)}${i}`},decode:i,decodeToBytes:function(e){const{prefix:t,words:n}=i(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:unsafeWrapper(i),fromWords:r,fromWordsUnsafe:s,toWords:o}}const bech32$1=genBech32("bech32"),isJapanese=e=>"あいこくしん"===e[0];function nfkd(e){if("string"!=typeof e)throw new TypeError("Invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function normalize(e){const t=nfkd(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}function assertEntropy(e){assert$1.bytes(e,16,20,24,28,32)}function generateMnemonic(e,t=128){if(assert$1.number(t),t%32!=0||t>256)throw new TypeError("Invalid entropy");return entropyToMnemonic(randomBytes(t/8),e)}const calcChecksum=e=>{const t=8-e.length/4;return new Uint8Array([sha256(e)[0]>>t<<t])};function getCoder(e){if(!Array.isArray(e)||2048!==e.length||"string"!=typeof e[0])throw new Error("Worlist: expected array of 2048 strings");return e.forEach((e=>{if("string"!=typeof e)throw new Error(`Wordlist: non-string element: ${e}`)})),utils$1.chain(utils$1.checksum(1,calcChecksum),utils$1.radix2(11,!0),utils$1.alphabet(e))}function mnemonicToEntropy(e,t){const{words:n}=normalize(e),r=getCoder(t).decode(n);return assertEntropy(r),r}function entropyToMnemonic(e,t){assertEntropy(e);return getCoder(t).encode(e).join(isJapanese(t)?" ":" ")}function validateMnemonic(e,t){try{mnemonicToEntropy(e,t)}catch(e){return!1}return!0}const salt=e=>nfkd(`mnemonic${e}`);function mnemonicToSeedSync(e,t=""){return pbkdf2(sha512,normalize(e).nfkd,salt(t),{c:2048,dkLen:64})}const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Id=Uint8Array.from({length:16},((e,t)=>t)),Pi=Id.map((e=>(9*e+5)%16));let idxL=[Id],idxR=[Pi];for(let e=0;e<4;e++)for(let t of[idxL,idxR])t.push(t[e].map((e=>Rho[e])));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>new Uint8Array(e))),shiftsL=idxL.map(((e,t)=>e.map((e=>shifts[t][e])))),shiftsR=idxR.map(((e,t)=>e.map((e=>shifts[t][e])))),Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),rotl$1=(e,t)=>e<<t|e>>>32-t;function f(e,t,n,r){return 0===e?t^n^r:1===e?t&n|~t&r:2===e?(t|~n)^r:3===e?t&r|n&~r:t^(n|~r)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:t,h2:n,h3:r,h4:o}=this;return[e,t,n,r,o]}set(e,t,n,r,o){this.h0=0|e,this.h1=0|t,this.h2=0|n,this.h3=0|r,this.h4=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)BUF[n]=e.getUint32(t,!0);let n=0|this.h0,r=n,o=0|this.h1,s=o,i=0|this.h2,a=i,l=0|this.h3,c=l,d=0|this.h4,h=d;for(let e=0;e<5;e++){const t=4-e,u=Kl[e],p=Kr[e],g=idxL[e],m=idxR[e],b=shiftsL[e],y=shiftsR[e];for(let t=0;t<16;t++){const r=rotl$1(n+f(e,o,i,l)+BUF[g[t]]+u,b[t])+d|0;n=d,d=l,l=0|rotl$1(i,10),i=o,o=r}for(let e=0;e<16;e++){const n=rotl$1(r+f(t,s,a,c)+BUF[m[e]]+p,y[e])+h|0;r=h,h=c,c=0|rotl$1(a,10),a=s,s=n}}this.set(this.h1+i+c|0,this.h2+l+h|0,this.h3+d+r|0,this.h4+n+s|0,this.h0+o+a|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}}const ripemd160=wrapConstructor((()=>new RIPEMD160)),Point=secp256k1.ProjectivePoint,base58check=base58check$1(sha256);function bytesToNumber(e){return BigInt(`0x${bytesToHex(e)}`)}function numberToBytes(e){return hexToBytes(e.toString(16).padStart(64,"0"))}const MASTER_SECRET=utf8ToBytes$1("Bitcoin seed"),BITCOIN_VERSIONS={private:76066276,public:76067358},HARDENED_OFFSET=2147483648,hash160=e=>ripemd160(sha256(e)),fromU32=e=>createView(e).getUint32(0,!1),toU32=e=>{if(!Number.isSafeInteger(e)||e<0||e>2**32-1)throw new Error(`Invalid number=${e}. Should be from 0 to 2 ** 32 - 1`);const t=new Uint8Array(4);return createView(t).setUint32(0,e,!1),t};class HDKey{get fingerprint(){if(!this.pubHash)throw new Error("No publicKey set!");return fromU32(this.pubHash)}get identifier(){return this.pubHash}get pubKeyHash(){return this.pubHash}get privateKey(){return this.privKeyBytes||null}get publicKey(){return this.pubKey||null}get privateExtendedKey(){const e=this.privateKey;if(!e)throw new Error("No private key");return base58check.encode(this.serialize(this.versions.private,concatBytes(new Uint8Array([0]),e)))}get publicExtendedKey(){if(!this.pubKey)throw new Error("No public key");return base58check.encode(this.serialize(this.versions.public,this.pubKey))}static fromMasterSeed(e,t=BITCOIN_VERSIONS){if(bytes$1(e),8*e.length<128||8*e.length>512)throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);const n=hmac$1(sha512,MASTER_SECRET,e);return new HDKey({versions:t,chainCode:n.slice(32),privateKey:n.slice(0,32)})}static fromExtendedKey(e,t=BITCOIN_VERSIONS){const n=base58check.decode(e),r=createView(n),o=r.getUint32(0,!1),s={versions:t,depth:n[4],parentFingerprint:r.getUint32(5,!1),index:r.getUint32(9,!1),chainCode:n.slice(13,45)},i=n.slice(45),a=0===i[0];if(o!==t[a?"private":"public"])throw new Error("Version mismatch");return new HDKey(a?{...s,privateKey:i.slice(1)}:{...s,publicKey:i})}static fromJSON(e){return HDKey.fromExtendedKey(e.xpriv)}constructor(e){if(this.depth=0,this.index=0,this.chainCode=null,this.parentFingerprint=0,!e||"object"!=typeof e)throw new Error("HDKey.constructor must not be called directly");if(this.versions=e.versions||BITCOIN_VERSIONS,this.depth=e.depth||0,this.chainCode=e.chainCode,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");if(e.publicKey&&e.privateKey)throw new Error("HDKey: publicKey and privateKey at same time.");if(e.privateKey){if(!secp256k1.utils.isValidPrivateKey(e.privateKey))throw new Error("Invalid private key");this.privKey="bigint"==typeof e.privateKey?e.privateKey:bytesToNumber(e.privateKey),this.privKeyBytes=numberToBytes(this.privKey),this.pubKey=secp256k1.getPublicKey(e.privateKey,!0)}else{if(!e.publicKey)throw new Error("HDKey: no public or private key provided");this.pubKey=Point.fromHex(e.publicKey).toRawBytes(!0)}this.pubHash=hash160(this.pubKey)}derive(e){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;const t=e.replace(/^[mM]'?\//,"").split("/");let n=this;for(const e of t){const t=/^(\d+)('?)$/.exec(e);if(!t||3!==t.length)throw new Error(`Invalid child index: ${e}`);let r=+t[1];if(!Number.isSafeInteger(r)||r>=HARDENED_OFFSET)throw new Error("Invalid index");"'"===t[2]&&(r+=HARDENED_OFFSET),n=n.deriveChild(r)}return n}deriveChild(e){if(!this.pubKey||!this.chainCode)throw new Error("No publicKey or chainCode set");let t=toU32(e);if(e>=HARDENED_OFFSET){const e=this.privateKey;if(!e)throw new Error("Could not derive hardened child key");t=concatBytes(new Uint8Array([0]),e,t)}else t=concatBytes(this.pubKey,t);const n=hmac$1(sha512,this.chainCode,t),r=bytesToNumber(n.slice(0,32)),o=n.slice(32);if(!secp256k1.utils.isValidPrivateKey(r))throw new Error("Tweak bigger than curve order");const s={versions:this.versions,chainCode:o,depth:this.depth+1,parentFingerprint:this.fingerprint,index:e};try{if(this.privateKey){const e=mod(this.privKey+r,secp256k1.CURVE.n);if(!secp256k1.utils.isValidPrivateKey(e))throw new Error("The tweak was out of range or the resulted private key is invalid");s.privateKey=e}else{const e=Point.fromHex(this.pubKey).add(Point.fromPrivateKey(r));if(e.equals(Point.ZERO))throw new Error("The tweak was equal to negative P, which made the result key invalid");s.publicKey=e.toRawBytes(!0)}return new HDKey(s)}catch(t){return this.deriveChild(e+1)}}sign(e){if(!this.privateKey)throw new Error("No privateKey set!");return bytes$1(e,32),secp256k1.sign(e,this.privKey).toCompactRawBytes()}verify(e,t){if(bytes$1(e,32),bytes$1(t,64),!this.publicKey)throw new Error("No publicKey set!");let n;try{n=secp256k1.Signature.fromCompact(t)}catch(e){return!1}return secp256k1.verify(n,e,this.publicKey)}wipePrivateData(){return this.privKey=void 0,this.privKeyBytes&&(this.privKeyBytes.fill(0),this.privKeyBytes=void 0),this}toJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(e,t){if(!this.chainCode)throw new Error("No chainCode set");return bytes$1(t,33),concatBytes(toU32(e),new Uint8Array([this.depth]),toU32(this.parentFingerprint),toU32(this.index),this.chainCode,t)}}
|
|
15
15
|
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u8a=e=>e instanceof Uint8Array,u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes(e){if("string"==typeof e&&(e=utf8ToBytes(e)),!u8a(e))throw new Error("expected Uint8Array, got "+typeof e);return e}const isPlainObject=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function checkOpts(e,t){if(void 0!==t&&("object"!=typeof t||!isPlainObject(t)))throw new Error("options must be object or undefined");return Object.assign(e,t)}function ensureBytes(e,t){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");if(e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}function equalBytes(e,t){if(e.length!==t.length)throw new Error("equalBytes: Different size of Uint8Arrays");let n=!0;for(let r=0;r<e.length;r++)n&&(n=e[r]===t[r]);return n}function number(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool(e){if("boolean"!=typeof e)throw new Error(`Expected boolean, not ${e}`)}function bytes(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("hash must be wrapped by utils.wrapConstructor");number(e.outputLen),number(e.blockLen)}function exists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output(e,t){bytes(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const assert={number:number,bool:bool,bytes:bytes,hash:hash,exists:exists,output:output},u8to16=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Poly1305{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,ensureBytes(e=toBytes(e),32);const t=u8to16(e,0),n=u8to16(e,2),r=u8to16(e,4),o=u8to16(e,6),s=u8to16(e,8),i=u8to16(e,10),a=u8to16(e,12),l=u8to16(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|o<<9),this.r[4]=255&(o>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|i<<2),this.r[7]=8065&(i>>>11|a<<5),this.r[8]=8191&(a>>>8|l<<8),this.r[9]=l>>>5&127;for(let t=0;t<8;t++)this.pad[t]=u8to16(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:o,r:s}=this,i=s[0],a=s[1],l=s[2],c=s[3],d=s[4],h=s[5],u=s[6],p=s[7],f=s[8],g=s[9],m=u8to16(e,t+0),b=u8to16(e,t+2),y=u8to16(e,t+4),w=u8to16(e,t+6),v=u8to16(e,t+8),k=u8to16(e,t+10),x=u8to16(e,t+12),E=u8to16(e,t+14);let C=o[0]+(8191&m),$=o[1]+(8191&(m>>>13|b<<3)),S=o[2]+(8191&(b>>>10|y<<6)),_=o[3]+(8191&(y>>>7|w<<9)),A=o[4]+(8191&(w>>>4|v<<12)),N=o[5]+(v>>>1&8191),L=o[6]+(8191&(v>>>14|k<<2)),R=o[7]+(8191&(k>>>11|x<<5)),T=o[8]+(8191&(x>>>8|E<<8)),U=o[9]+(E>>>5|r),B=0,I=B+C*i+$*(5*g)+S*(5*f)+_*(5*p)+A*(5*u);B=I>>>13,I&=8191,I+=N*(5*h)+L*(5*d)+R*(5*c)+T*(5*l)+U*(5*a),B+=I>>>13,I&=8191;let M=B+C*a+$*i+S*(5*g)+_*(5*f)+A*(5*p);B=M>>>13,M&=8191,M+=N*(5*u)+L*(5*h)+R*(5*d)+T*(5*c)+U*(5*l),B+=M>>>13,M&=8191;let O=B+C*l+$*a+S*i+_*(5*g)+A*(5*f);B=O>>>13,O&=8191,O+=N*(5*p)+L*(5*u)+R*(5*h)+T*(5*d)+U*(5*c),B+=O>>>13,O&=8191;let P=B+C*c+$*l+S*a+_*i+A*(5*g);B=P>>>13,P&=8191,P+=N*(5*f)+L*(5*p)+R*(5*u)+T*(5*h)+U*(5*d),B+=P>>>13,P&=8191;let D=B+C*d+$*c+S*l+_*a+A*i;B=D>>>13,D&=8191,D+=N*(5*g)+L*(5*f)+R*(5*p)+T*(5*u)+U*(5*h),B+=D>>>13,D&=8191;let H=B+C*h+$*d+S*c+_*l+A*a;B=H>>>13,H&=8191,H+=N*i+L*(5*g)+R*(5*f)+T*(5*p)+U*(5*u),B+=H>>>13,H&=8191;let F=B+C*u+$*h+S*d+_*c+A*l;B=F>>>13,F&=8191,F+=N*a+L*i+R*(5*g)+T*(5*f)+U*(5*p),B+=F>>>13,F&=8191;let K=B+C*p+$*u+S*h+_*d+A*c;B=K>>>13,K&=8191,K+=N*l+L*a+R*i+T*(5*g)+U*(5*f),B+=K>>>13,K&=8191;let j=B+C*f+$*p+S*u+_*h+A*d;B=j>>>13,j&=8191,j+=N*c+L*l+R*a+T*i+U*(5*g),B+=j>>>13,j&=8191;let z=B+C*g+$*f+S*p+_*u+A*h;B=z>>>13,z&=8191,z+=N*d+L*c+R*l+T*a+U*i,B+=z>>>13,z&=8191,B=(B<<2)+B|0,B=B+I|0,I=8191&B,B>>>=13,M+=B,o[0]=I,o[1]=M,o[2]=O,o[3]=P,o[4]=D,o[5]=H,o[6]=F,o[7]=K,o[8]=j,o[9]=z}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let o=(1^r)-1;for(let e=0;e<10;e++)n[e]&=o;o=~o;for(let t=0;t<10;t++)e[t]=e[t]&o|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let s=e[0]+t[0];e[0]=65535&s;for(let n=1;n<8;n++)s=(e[n]+t[n]|0)+(s>>>16)|0,e[n]=65535&s}update(e){assert.exists(this);const{buffer:t,blockLen:n}=this,r=(e=toBytes(e)).length;for(let o=0;o<r;){const s=Math.min(n-this.pos,r-o);if(s!==n)t.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=r-o;o+=n)this.process(e,o)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(e){assert.exists(this),assert.output(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=n[t]>>>0,e[o++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}function wrapConstructorWithKey(e){const t=(t,n)=>e(n).update(toBytes(t)).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}wrapConstructorWithKey((e=>new Poly1305(e)));const sigma16=utf8ToBytes("expand 16-byte k"),sigma32=utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32),isAligned32=e=>!(e.byteOffset%4),salsaBasic=e=>{const{core:t,rounds:n,counterRight:r,counterLen:o,allow128bitKeys:s,extendNonceFn:i,blockLen:a}=checkOpts({rounds:20,counterRight:!1,counterLen:8,allow128bitKeys:!0,blockLen:64},e);assert.number(o),assert.number(n),assert.number(a),assert.bool(r),assert.bool(s);const l=a/4;if(a%4!=0)throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes");return(e,c,d,h,u=0)=>{if(assert.bytes(e),assert.bytes(c),assert.bytes(d),h||(h=new Uint8Array(d.length)),assert.bytes(h),assert.number(u),u<0||u>=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");if(h.length<d.length)throw new Error(`Salsa/ChaCha: output (${h.length}) is shorter than data (${d.length})`);const p=[];let f,g;if(32===e.length)f=e,g=sigma32_32;else{if(16!==e.length||!s)throw new Error(`Salsa/ChaCha: invalid 32-byte key, got length=${e.length}`);f=new Uint8Array(32),f.set(e),f.set(e,16),g=sigma16_32,p.push(f)}if(i){if(c.length<=16)throw new Error("Salsa/ChaCha: extended nonce must be bigger than 16 bytes");f=i(g,f,c.subarray(0,16),new Uint8Array(32)),p.push(f),c=c.subarray(16)}const m=16-o;if(c.length!==m)throw new Error(`Salsa/ChaCha: nonce must be ${m} or 16 bytes`);if(12!==m){const e=new Uint8Array(12);e.set(c,r?0:12-c.length),p.push(c=e)}const b=new Uint8Array(a),y=u32(b),w=u32(f),v=u32(c),k=isAligned32(d)&&u32(d),x=isAligned32(h)&&u32(h);p.push(y);const E=d.length;for(let e=0,r=u;e<E;r++){if(t(g,w,v,y,r,n),r>=2**32-1)throw new Error("Salsa/ChaCha: counter overflow");const o=Math.min(a,E-e);if(o===a&&x&&k){const t=e/4;if(e%4!=0)throw new Error("Salsa/ChaCha: invalid block position");for(let e=0;e<l;e++)x[t+e]=k[t+e]^y[e];e+=a}else{for(let t=0;t<o;t++)h[e+t]=d[e+t]^b[t];e+=o}}for(let e=0;e<p.length;e++)p[e].fill(0);return h}},rotl=(e,t)=>e<<t|e>>>32-t;function chachaCore(e,t,n,r,o,s=20){let i=e[0],a=e[1],l=e[2],c=e[3],d=t[0],h=t[1],u=t[2],p=t[3],f=t[4],g=t[5],m=t[6],b=t[7],y=o,w=n[0],v=n[1],k=n[2],x=i,E=a,C=l,$=c,S=d,_=h,A=u,N=p,L=f,R=g,T=m,U=b,B=y,I=w,M=v,O=k;for(let e=0;e<s;e+=2)x=x+S|0,B=rotl(B^x,16),L=L+B|0,S=rotl(S^L,12),x=x+S|0,B=rotl(B^x,8),L=L+B|0,S=rotl(S^L,7),E=E+_|0,I=rotl(I^E,16),R=R+I|0,_=rotl(_^R,12),E=E+_|0,I=rotl(I^E,8),R=R+I|0,_=rotl(_^R,7),C=C+A|0,M=rotl(M^C,16),T=T+M|0,A=rotl(A^T,12),C=C+A|0,M=rotl(M^C,8),T=T+M|0,A=rotl(A^T,7),$=$+N|0,O=rotl(O^$,16),U=U+O|0,N=rotl(N^U,12),$=$+N|0,O=rotl(O^$,8),U=U+O|0,N=rotl(N^U,7),x=x+_|0,O=rotl(O^x,16),T=T+O|0,_=rotl(_^T,12),x=x+_|0,O=rotl(O^x,8),T=T+O|0,_=rotl(_^T,7),E=E+A|0,B=rotl(B^E,16),U=U+B|0,A=rotl(A^U,12),E=E+A|0,B=rotl(B^E,8),U=U+B|0,A=rotl(A^U,7),C=C+N|0,I=rotl(I^C,16),L=L+I|0,N=rotl(N^L,12),C=C+N|0,I=rotl(I^C,8),L=L+I|0,N=rotl(N^L,7),$=$+S|0,M=rotl(M^$,16),R=R+M|0,S=rotl(S^R,12),$=$+S|0,M=rotl(M^$,8),R=R+M|0,S=rotl(S^R,7);let P=0;r[P++]=i+x|0,r[P++]=a+E|0,r[P++]=l+C|0,r[P++]=c+$|0,r[P++]=d+S|0,r[P++]=h+_|0,r[P++]=u+A|0,r[P++]=p+N|0,r[P++]=f+L|0,r[P++]=g+R|0,r[P++]=m+T|0,r[P++]=b+U|0,r[P++]=y+B|0,r[P++]=w+I|0,r[P++]=v+M|0,r[P++]=k+O|0}const chacha20=salsaBasic({core:chachaCore,counterRight:!1,counterLen:4,allow128bitKeys:!1});class HMAC extends Hash$1{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert$2.hash(e);const n=toBytes$2(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),o.fill(0)}update(e){return assert$2.exists(this),this.iHash.update(e),this}digestInto(e){assert$2.exists(this),assert$2.bytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:s,outputLen:i}=this;return e.finished=r,e.destroyed=o,e.blockLen=s,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(e,t,n)=>new HMAC(e,t).update(n).digest();function extract$1(e,t,n){return assert$2.hash(e),void 0===n&&(n=new Uint8Array(e.outputLen)),hmac(e,toBytes$2(n),toBytes$2(t))}hmac.create=(e,t)=>new HMAC(e,t);const HKDF_COUNTER$1=new Uint8Array([0]),EMPTY_BUFFER$1=new Uint8Array;function expand$1(e,t,n,r=32){if(assert$2.hash(e),assert$2.number(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/e.outputLen),s=new Uint8Array(o*e.outputLen),i=hmac.create(e,t),a=i._cloneInto(),l=new Uint8Array(i.outputLen);for(let t=0;t<o;t++)HKDF_COUNTER$1[0]=t+1,a.update(0===t?EMPTY_BUFFER$1:l).update(n).update(HKDF_COUNTER$1).digestInto(l),s.set(l,e.outputLen*t),i._cloneInto(a);return i.destroy(),a.destroy(),l.fill(0),HKDF_COUNTER$1.fill(0),s.slice(0,r)}const hkdf=(e,t,n,r,o)=>expand$1(e,extract$1(e,t,n),r,o);var __defProp=Object.defineProperty,__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})};function generatePrivateKey(){return bytesToHex$1(schnorr.utils.randomPrivateKey())}function getPublicKey(e){return bytesToHex$1(schnorr.getPublicKey(e))}var utils_exports={};__export(utils_exports,{MessageNode:()=>MessageNode,MessageQueue:()=>MessageQueue,insertEventIntoAscendingList:()=>insertEventIntoAscendingList,insertEventIntoDescendingList:()=>insertEventIntoDescendingList,normalizeURL:()=>normalizeURL,utf8Decoder:()=>utf8Decoder,utf8Encoder:()=>utf8Encoder});var utf8Decoder=new TextDecoder("utf-8"),utf8Encoder=new TextEncoder;function normalizeURL(e){let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),("80"===t.port&&"ws:"===t.protocol||"443"===t.port&&"wss:"===t.protocol)&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}function insertEventIntoDescendingList(e,t){let n,r=0,o=e.length-1,s=r;if(o<0)s=0;else if(t.created_at<e[o].created_at)s=o+1;else if(t.created_at>=e[r].created_at)s=r;else for(;;){if(o<=r+1){s=o;break}if(n=Math.floor(r+(o-r)/2),e[n].created_at>t.created_at)r=n;else{if(!(e[n].created_at<t.created_at)){s=n;break}o=n}}return e[s]?.id!==t.id?[...e.slice(0,s),t,...e.slice(s)]:e}function insertEventIntoAscendingList(e,t){let n,r=0,o=e.length-1,s=r;if(o<0)s=0;else if(t.created_at>e[o].created_at)s=o+1;else if(t.created_at<=e[r].created_at)s=r;else for(;;){if(o<=r+1){s=o;break}if(n=Math.floor(r+(o-r)/2),e[n].created_at<t.created_at)r=n;else{if(!(e[n].created_at>t.created_at)){s=n;break}o=n}}return e[s]?.id!==t.id?[...e.slice(0,s),t,...e.slice(s)]:e}var MessageNode=class{_value;_next;get value(){return this._value}set value(e){this._value=e}get next(){return this._next}set next(e){this._next=e}constructor(e){this._value=e,this._next=null}},MessageQueue=class{_first;_last;get first(){return this._first}set first(e){this._first=e}get last(){return this._last}set last(e){this._last=e}_size;get size(){return this._size}set size(e){this._size=e}constructor(){this._first=null,this._last=null,this._size=0}enqueue(e){const t=new MessageNode(e);return 0!==this._size&&this._last?(this._last.next=t,this._last=t):(this._first=t,this._last=t),this._size++,!0}dequeue(){if(0===this._size||!this._first)return null;let e=this._first;return this._first=e.next,e.next=null,this._size--,e.value}},verifiedSymbol=Symbol("verified");function getBlankEvent(e=255){return{kind:e,content:"",tags:[],created_at:0}}function finishEvent(e,t){const n=e;return n.pubkey=getPublicKey(t),n.id=getEventHash(n),n.sig=getSignature(n,t),n[verifiedSymbol]=!0,n}function serializeEvent(e){if(!validateEvent(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function getEventHash(e){return bytesToHex$1(sha256$1(utf8Encoder.encode(serializeEvent(e))))}var isRecord=e=>e instanceof Object;function validateEvent(e){if(!isRecord(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!e.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let e=0;e<n.length;e++)if("object"==typeof n[e])return!1}return!0}function verifySignature(e){if("boolean"==typeof e[verifiedSymbol])return e[verifiedSymbol];const t=getEventHash(e);if(t!==e.id)return e[verifiedSymbol]=!1;try{return e[verifiedSymbol]=schnorr.verify(e.sig,t,e.pubkey)}catch(t){return e[verifiedSymbol]=!1}}function getSignature(e,t){return bytesToHex$1(schnorr.sign(getEventHash(e),t))}function matchFilter(e,t){if(e.ids&&-1===e.ids.indexOf(t.id)&&!e.ids.some((e=>t.id.startsWith(e))))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey)&&!e.authors.some((e=>t.pubkey.startsWith(e))))return!1;for(let n in e)if("#"===n[0]){let r=e[`#${n.slice(1)}`];if(r&&!t.tags.find((([e,t])=>e===n.slice(1)&&-1!==r.indexOf(t))))return!1}return!(e.since&&t.created_at<e.since)&&!(e.until&&t.created_at>e.until)}function matchFilters(e,t){for(let n=0;n<e.length;n++)if(matchFilter(e[n],t))return!0;return!1}var fakejson_exports={};function getHex64(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,o=e.slice(r).indexOf('"')+r+1;return e.slice(o,o+64)}function getInt(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,o=e.slice(r),s=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,s),10)}function getSubscriptionId(e){let t=e.slice(0,22).indexOf('"EVENT"');if(-1===t)return null;let n=e.slice(t+7+1).indexOf('"');if(-1===n)return null;let r=t+7+1+n,o=e.slice(r+1,80).indexOf('"');if(-1===o)return null;let s=r+1+o;return e.slice(r+1,s)}function matchEventId(e,t){return t===getHex64(e,"id")}function matchEventPubkey(e,t){return t===getHex64(e,"pubkey")}function matchEventKind(e,t){return t===getInt(e,"kind")}__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});var newListeners=()=>({connect:[],disconnect:[],error:[],notice:[],auth:[]});function relayInit(e,t={}){let{listTimeout:n=3e3,getTimeout:r=3e3,countTimeout:o=3e3}=t;var s,i,a={},l=newListeners(),c={},d={};function h(){return 1===s?.readyState}async function u(e){let t=JSON.stringify(e);if(h()||(await new Promise((e=>setTimeout(e,1e3))),h()))try{s.send(t)}catch(e){console.log(e)}}const p=(e,{verb:t="REQ",skipVerification:n=!1,alreadyHaveEvent:r=null,id:o=Math.random().toString().slice(2)}={})=>{let s=o;a[s]={id:s,filters:e,skipVerification:n,alreadyHaveEvent:r},u([t,s,...e]);let i={sub:(t,o={})=>p(t||e,{skipVerification:o.skipVerification||n,alreadyHaveEvent:o.alreadyHaveEvent||r,id:s}),unsub:()=>{delete a[s],delete c[s],u(["CLOSE",s])},on:(e,t)=>{c[s]=c[s]||{event:[],count:[],eose:[]},c[s][e].push(t)},off:(e,t)=>{let n=c[s],r=n[e].indexOf(t);r>=0&&n[e].splice(r,1)},get events(){return eventsGenerator(i)}};return i};function f(e,t){return new Promise(((n,r)=>{if(!e.id)return void r(new Error(`event ${e} has no id`));let o=e.id;u([t,e]),d[o]={resolve:n,reject:r}}))}return{url:e,sub:p,on:(e,t)=>{l[e].push(t),"connect"===e&&1===s?.readyState&&t()},off:(e,t)=>{let n=l[e].indexOf(t);-1!==n&&l[e].splice(n,1)},list:(e,t)=>new Promise((r=>{let o=p(e,t),s=[],i=setTimeout((()=>{o.unsub(),r(s)}),n);o.on("eose",(()=>{o.unsub(),clearTimeout(i),r(s)})),o.on("event",(e=>{s.push(e)}))})),get:(e,t)=>new Promise((n=>{let o=p([e],t),s=setTimeout((()=>{o.unsub(),n(null)}),r);o.on("event",(e=>{o.unsub(),clearTimeout(s),n(e)}))})),count:e=>new Promise((t=>{let n=p(e,{...p,verb:"COUNT"}),r=setTimeout((()=>{n.unsub(),t(null)}),o);n.on("count",(e=>{n.unsub(),clearTimeout(r),t(e)}))})),async publish(e){await f(e,"EVENT")},async auth(e){await f(e,"AUTH")},connect:async function(){h()||await async function(){return i||(i=new Promise(((t,n)=>{try{s=new WebSocket(e)}catch(e){n(e)}s.onopen=()=>{l.connect.forEach((e=>e())),t()},s.onerror=()=>{i=void 0,l.error.forEach((e=>e())),n()},s.onclose=async()=>{i=void 0,l.disconnect.forEach((e=>e()))};let r,o=new MessageQueue;function h(){if(0===o.size)return clearInterval(r),void(r=null);var t=o.dequeue();if(!t)return;let n=getSubscriptionId(t);if(n){let r=a[n];if(r&&r.alreadyHaveEvent&&r.alreadyHaveEvent(getHex64(t,"id"),e))return}try{let e=JSON.parse(t);switch(e[0]){case"EVENT":{let t=e[1],n=e[2];return void(validateEvent(n)&&a[t]&&(a[t].skipVerification||verifySignature(n))&&matchFilters(a[t].filters,n)&&(a[t],(c[t]?.event||[]).forEach((e=>e(n)))))}case"COUNT":let t=e[1],n=e[2];return void(a[t]&&(c[t]?.count||[]).forEach((e=>e(n))));case"EOSE":{let t=e[1];return void(t in c&&(c[t].eose.forEach((e=>e())),c[t].eose=[]))}case"OK":{let t=e[1],n=e[2],r=e[3]||"";if(t in d){let{resolve:e,reject:o}=d[t];n?e(null):o(new Error(r))}return}case"NOTICE":let r=e[1];return void l.notice.forEach((e=>e(r)));case"AUTH":{let t=e[1];return void l.auth?.forEach((e=>e(t)))}}}catch(e){return}}s.onmessage=e=>{o.enqueue(e.data),r||(r=setInterval(h,0))}})),i)}()},close(){l=newListeners(),c={},d={},s?.readyState===WebSocket.OPEN&&s.close()},get status(){return s?.readyState??3}}}async function*eventsGenerator(e){let t;const n=[],r=e=>{t?(t(e),t=void 0):n.push(e)};e.on("event",r);try{for(;;)if(n.length>0)yield n.shift();else{const e=await new Promise((e=>{t=e}));yield e}}finally{e.off("event",r)}}var nip19_exports={};__export(nip19_exports,{BECH32_REGEX:()=>BECH32_REGEX,decode:()=>decode,naddrEncode:()=>naddrEncode,neventEncode:()=>neventEncode,noteEncode:()=>noteEncode,nprofileEncode:()=>nprofileEncode,npubEncode:()=>npubEncode,nrelayEncode:()=>nrelayEncode,nsecEncode:()=>nsecEncode});var Bech32MaxSize=5e3,BECH32_REGEX=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}function decode(e){let{prefix:t,words:n}=bech32$2.decode(e,Bech32MaxSize),r=new Uint8Array(bech32$2.fromWords(n));switch(t){case"nprofile":{let e=parseTLV(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map((e=>utf8Decoder.decode(e))):[]}}}case"nevent":{let e=parseTLV(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map((e=>utf8Decoder.decode(e))):[],author:e[2]?.[0]?bytesToHex$1(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$1(e[3][0]),16):void 0}}}case"naddr":{let e=parseTLV(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder.decode(e[0][0]),pubkey:bytesToHex$1(e[2][0]),kind:parseInt(bytesToHex$1(e[3][0]),16),relays:e[1]?e[1].map((e=>utf8Decoder.decode(e))):[]}}}case"nrelay":{let e=parseTLV(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nrelay");return{type:"nrelay",data:utf8Decoder.decode(e[0][0])}}case"nsec":case"npub":case"note":return{type:t,data:bytesToHex$1(r)};default:throw new Error(`unknown prefix ${t}`)}}function parseTLV(e){let t={},n=e;for(;n.length>0;){let e=n[0],r=n[1];if(!r)throw new Error(`malformed TLV ${e}`);let o=n.slice(2,2+r);if(n=n.slice(2+r),o.length<r)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(o)}return t}function nsecEncode(e){return encodeBytes("nsec",e)}function npubEncode(e){return encodeBytes("npub",e)}function noteEncode(e){return encodeBytes("note",e)}function encodeBech32(e,t){let n=bech32$2.toWords(t);return bech32$2.encode(e,n,Bech32MaxSize)}function encodeBytes(e,t){return encodeBech32(e,hexToBytes$1(t))}function nprofileEncode(e){return encodeBech32("nprofile",encodeTLV({0:[hexToBytes$1(e.pubkey)],1:(e.relays||[]).map((e=>utf8Encoder.encode(e)))}))}function neventEncode(e){let t;return null!=e.kind&&(t=integerToUint8Array(e.kind)),encodeBech32("nevent",encodeTLV({0:[hexToBytes$1(e.id)],1:(e.relays||[]).map((e=>utf8Encoder.encode(e))),2:e.author?[hexToBytes$1(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function naddrEncode(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),encodeBech32("naddr",encodeTLV({0:[utf8Encoder.encode(e.identifier)],1:(e.relays||[]).map((e=>utf8Encoder.encode(e))),2:[hexToBytes$1(e.pubkey)],3:[new Uint8Array(t)]}))}function nrelayEncode(e){return encodeBech32("nrelay",encodeTLV({0:[utf8Encoder.encode(e)]}))}function encodeTLV(e){let t=[];return Object.entries(e).forEach((([e,n])=>{n.forEach((n=>{let r=new Uint8Array(n.length+2);r.set([parseInt(e)],0),r.set([n.length],1),r.set(n,2),t.push(r)}))})),concatBytes$1(...t)}var nip04_exports={};async function encrypt$1(e,t,n){const r=getNormalizedX(secp256k1.getSharedSecret(e,"02"+t));let o=Uint8Array.from(randomBytes$1(16)),s=utf8Encoder.encode(n),i=await crypto.subtle.importKey("raw",r,{name:"AES-CBC"},!1,["encrypt"]),a=await crypto.subtle.encrypt({name:"AES-CBC",iv:o},i,s);return`${base64$1.encode(new Uint8Array(a))}?iv=${base64$1.encode(new Uint8Array(o.buffer))}`}async function decrypt$1(e,t,n){let[r,o]=n.split("?iv="),s=getNormalizedX(secp256k1.getSharedSecret(e,"02"+t)),i=await crypto.subtle.importKey("raw",s,{name:"AES-CBC"},!1,["decrypt"]),a=base64$1.decode(r),l=base64$1.decode(o),c=await crypto.subtle.decrypt({name:"AES-CBC",iv:l},i,a);return utf8Decoder.decode(c)}function getNormalizedX(e){return e.slice(1,33)}__export(nip04_exports,{decrypt:()=>decrypt$1,encrypt:()=>encrypt$1}),"undefined"!=typeof crypto&&!crypto.subtle&&crypto.webcrypto&&(crypto.subtle=crypto.webcrypto.subtle);var nip05_exports={};__export(nip05_exports,{NIP05_REGEX:()=>NIP05_REGEX$1,queryProfile:()=>queryProfile,searchDomain:()=>searchDomain,useFetchImplementation:()=>useFetchImplementation});var NIP05_REGEX$1=/^(?:([\w.+-]+)@)?([\w.-]+)$/,_fetch;try{_fetch=fetch}catch{}function useFetchImplementation(e){_fetch=e}async function searchDomain(e,t=""){try{return(await(await _fetch(`https://${e}/.well-known/nostr.json?name=${t}`)).json()).names}catch(e){return{}}}async function queryProfile(e){const t=e.match(NIP05_REGEX$1);if(!t)return null;const[n,r="_",o]=t;try{const e=await _fetch(`https://${o}/.well-known/nostr.json?name=${r}`),{names:t,relays:n}=parseNIP05Result$1(await e.json()),s=t[r];return s?{pubkey:s,relays:n?.[s]}:null}catch(e){return null}}function parseNIP05Result$1(e){const t={names:{}};for(const[n,r]of Object.entries(e.names))"string"==typeof n&&"string"==typeof r&&(t.names[n]=r);if(e.relays){t.relays={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.relays[n]=r.filter((e=>"string"==typeof e)))}return t}var nip06_exports={};function privateKeyFromSeedWords(e,t){let n=HDKey.fromMasterSeed(mnemonicToSeedSync(e,t)).derive("m/44'/1237'/0'/0/0").privateKey;if(!n)throw new Error("could not derive private key");return bytesToHex$1(n)}function generateSeedWords(){return generateMnemonic(wordlist)}function validateWords(e){return validateMnemonic(e,wordlist)}__export(nip06_exports,{generateSeedWords:()=>generateSeedWords,privateKeyFromSeedWords:()=>privateKeyFromSeedWords,validateWords:()=>validateWords});var nip10_exports={};function parse(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[]},n=[];for(const r of e.tags)"e"===r[0]&&r[1]&&n.push(r),"p"===r[0]&&r[1]&&t.profiles.push({pubkey:r[1],relays:r[2]?[r[2]]:[]});for(let e=0;e<n.length;e++){const r=n[e],[o,s,i,a]=r,l={id:s,relays:i?[i]:[]},c=0===e,d=e===n.length-1;"root"!==a?"reply"!==a?"mention"!==a?c?t.root=l:d?t.reply=l:t.mentions.push(l):t.mentions.push(l):t.reply=l:t.root=l}return t}__export(nip10_exports,{parse:()=>parse});var nip13_exports={};function getPow(e){let t=0;for(let n=0;n<e.length;n++){const r=parseInt(e[n],16);if(0!==r){t+=Math.clz32(r)-28;break}t+=4}return t}function minePow(e,t){let n=0;const r=e,o=["nonce",n.toString(),t.toString()];for(r.tags.push(o);;){const e=Math.floor((new Date).getTime()/1e3);if(e!==r.created_at&&(n=0,r.created_at=e),o[1]=(++n).toString(),r.id=getEventHash(r),getPow(r.id)>=t)break}return r}__export(nip13_exports,{getPow:()=>getPow,minePow:()=>minePow});var nip18_exports={};function finishRepostEvent(e,t,n,r){return finishEvent({kind:6,tags:[...e.tags??[],["e",t.id,n],["p",t.pubkey]],content:""===e.content?"":JSON.stringify(t),created_at:e.created_at},r)}function getRepostedEventPointer(e){if(6!==e.kind)return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t?{id:t[1],relays:[t[2],n?.[2]].filter((e=>"string"==typeof e)),author:n?.[1]}:void 0}function getRepostedEvent(e,{skipVerification:t}={}){const n=getRepostedEventPointer(e);if(void 0===n||""===e.content)return;let r;try{r=JSON.parse(e.content)}catch(e){return}return r.id===n.id&&(t||verifySignature(r))?r:void 0}__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});var nip21_exports={};__export(nip21_exports,{NOSTR_URI_REGEX:()=>NOSTR_URI_REGEX,parse:()=>parse2,test:()=>test});var NOSTR_URI_REGEX=new RegExp(`nostr:(${BECH32_REGEX.source})`);function test(e){return"string"==typeof e&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(e)}function parse2(e){const t=e.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:decode(t[1])}}var nip25_exports={};function finishReactionEvent(e,t,n){const r=t.tags.filter((e=>e.length>=2&&("e"===e[0]||"p"===e[0])));return finishEvent({...e,kind:7,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function getReactedEventPointer(e){if(7!==e.kind)return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t&&void 0!==n?{id:t[1],relays:[t[2],n[2]].filter((e=>void 0!==e)),author:n[1]}:void 0}__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});var nip26_exports={};function createDelegation(e,t){let n=[];(t.kind||-1)>=0&&n.push(`kind=${t.kind}`),t.until&&n.push(`created_at<${t.until}`),t.since&&n.push(`created_at>${t.since}`);let r=n.join("&");if(""===r)throw new Error("refusing to create a delegation without any conditions");let o=sha256$1(utf8Encoder.encode(`nostr:delegation:${t.pubkey}:${r}`)),s=bytesToHex$1(schnorr.sign(o,e));return{from:getPublicKey(e),to:t.pubkey,cond:r,sig:s}}function getDelegator(e){let t=e.tags.find((e=>"delegation"===e[0]&&e.length>=4));if(!t)return null;let n=t[1],r=t[2],o=t[3],s=r.split("&");for(let t=0;t<s.length;t++){let[n,r,o]=s[t].split(/\b/);if(("kind"!==n||"="!==r||e.kind!==parseInt(o))&&!("created_at"===n&&"<"===r&&e.created_at<parseInt(o)||"created_at"===n&&">"===r&&e.created_at>parseInt(o)))return null}let i=sha256$1(utf8Encoder.encode(`nostr:delegation:${e.pubkey}:${r}`));return schnorr.verify(o,i,n)?n:null}__export(nip26_exports,{createDelegation:()=>createDelegation,getDelegator:()=>getDelegator});var nip27_exports={};__export(nip27_exports,{matchAll:()=>matchAll,regex:()=>regex,replaceAll:()=>replaceAll});var regex=()=>new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`,"g");function*matchAll(e){const t=e.matchAll(regex());for(const e of t)try{const[t,n]=e;yield{uri:t,value:n,decoded:decode(n),start:e.index,end:e.index+t.length}}catch(e){}}function replaceAll(e,t){return e.replaceAll(regex(),((e,n)=>t({uri:e,value:n,decoded:decode(n)})))}var nip28_exports={};__export(nip28_exports,{channelCreateEvent:()=>channelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finishEvent({kind:40,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},channelMetadataEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finishEvent({kind:41,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},channelMessageEvent=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),finishEvent({kind:42,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},channelHideMessageEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finishEvent({kind:43,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},channelMuteUserEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finishEvent({kind:44,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},nip39_exports={},_fetch2;__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation2,validateGithub:()=>validateGithub});try{_fetch2=fetch}catch{}function useFetchImplementation2(e){_fetch2=e}async function validateGithub(e,t,n){try{return await(await _fetch2(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch(e){return!1}}var nip42_exports={};__export(nip42_exports,{authenticate:()=>authenticate});var authenticate=async({challenge:e,relay:t,sign:n})=>{const r={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t.url],["challenge",e]],content:""};return t.auth(await n(r))},nip44_exports={};__export(nip44_exports,{decrypt:()=>decrypt2,encrypt:()=>encrypt2,utils:()=>utils});var utils={v2:{maxPlaintextSize:65408,minCiphertextSize:100,maxCiphertextSize:102400,getConversationKey:(e,t)=>secp256k1.getSharedSecret(e,"02"+t).subarray(1,33),getMessageKeys(e,t){const n=hkdf(sha256$1,e,t,"nip44-v2",76);return{encryption:n.subarray(0,32),nonce:n.subarray(32,44),auth:n.subarray(44,76)}},calcPadding(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)},pad(e){const t=utf8Encoder.encode(e),n=t.length;if(n<1||n>=utils.v2.maxPlaintextSize)throw new Error("invalid plaintext length: must be between 1b and 64KB");const r=utils.v2.calcPadding(n),o=new Uint8Array(r-n),s=new Uint8Array(2);return new DataView(s.buffer).setUint16(0,n),concatBytes$1(s,t,o)},unpad(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(0===t||n.length!==t||e.length!==2+utils.v2.calcPadding(t))throw new Error("invalid padding");return utf8Decoder.decode(n)}}};function encrypt2(e,t,n={}){const r=n.version??2;if(2!==r)throw new Error("unknown encryption version "+r);const o=n.salt??randomBytes$1(32);ensureBytes(o,32);const s=utils.v2.getMessageKeys(e,o),i=utils.v2.pad(t),a=chacha20(s.encryption,s.nonce,i),l=hmac(sha256$1,s.auth,a);return base64$1.encode(concatBytes$1(new Uint8Array([r]),o,a,l))}function decrypt2(e,t){const n=utils.v2;ensureBytes(e,32);const r=t.length;if(r<n.minCiphertextSize||r>=n.maxCiphertextSize)throw new Error("invalid ciphertext length: "+r);if("#"===t[0])throw new Error("unknown encryption version");let o;try{o=base64$1.decode(t)}catch(e){throw new Error("invalid base64: "+e.message)}const s=o.subarray(0,1)[0];if(2!==s)throw new Error("unknown encryption version "+s);const i=o.subarray(1,33),a=o.subarray(33,-32),l=o.subarray(-32),c=n.getMessageKeys(e,i);if(!equalBytes(hmac(sha256$1,c.auth,a),l))throw new Error("invalid MAC");const d=chacha20(c.encryption,c.nonce,a);return n.unpad(d)}var nip47_exports={};function parseConnectionString(e){const{pathname:t,searchParams:n}=new URL(e),r=t,o=n.get("relay"),s=n.get("secret");if(!r||!o||!s)throw new Error("invalid connection string");return{pubkey:r,relay:o,secret:s}}async function makeNwcRequestEvent({pubkey:e,secret:t,invoice:n}){const r={method:"pay_invoice",params:{invoice:n}},o=await encrypt$1(t,e,JSON.stringify(r));return finishEvent({kind:23194,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e]]},t)}__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});var nip57_exports={},_fetch3;__export(nip57_exports,{getZapEndpoint:()=>getZapEndpoint,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation3,validateZapRequest:()=>validateZapRequest});try{_fetch3=fetch}catch{}function useFetchImplementation3(e){_fetch3=e}async function getZapEndpoint(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:e}=bech32$2.decode(n,1e3),r=bech32$2.fromWords(e);t=utf8Decoder.decode(r)}else{if(!r)return null;{let[e,n]=r.split("@");t=`https://${n}/.well-known/lnurlp/${e}`}}let o=await _fetch3(t),s=await o.json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch(e){}return null}function makeZapRequest({profile:e,event:t,amount:n,relays:r,comment:o=""}){if(!n)throw new Error("amount not given");if(!e)throw new Error("profile not given");let s={kind:9734,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e],["amount",n.toString()],["relays",...r]]};return t&&s.tags.push(["e",t]),s}function validateZapRequest(e){let t;try{t=JSON.parse(e)}catch(e){return"Invalid zap request JSON."}if(!validateEvent(t))return"Zap request is not a valid Nostr event.";if(!verifySignature(t))return"Invalid signature on zap request.";let n=t.tags.find((([e,t])=>"p"===e&&t));if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find((([e,t])=>"e"===e&&t));return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find((([e,t])=>"relays"===e&&t))?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let o=JSON.parse(e).tags.filter((([e])=>"e"===e||"p"===e||"a"===e)),s={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...o,["bolt11",n],["description",e]]};return t&&s.tags.push(["preimage",t]),s}var nip98_exports={};__export(nip98_exports,{getToken:()=>getToken,unpackEventFromToken:()=>unpackEventFromToken,validateEvent:()=>validateEvent2,validateToken:()=>validateToken});var _authorizationScheme="Nostr ";async function getToken(e,t,n,r=!1){if(!e||!t)throw new Error("Missing loginUrl or httpMethod");const o=getBlankEvent(27235);o.tags=[["u",e],["method",t]],o.created_at=Math.round((new Date).getTime()/1e3);const s=await n(o);return(r?_authorizationScheme:"")+base64$1.encode(utf8Encoder.encode(JSON.stringify(s)))}async function validateToken(e,t,n){const r=await unpackEventFromToken(e).catch((e=>{throw e}));return await validateEvent2(r,t,n).catch((e=>{throw e}))}async function unpackEventFromToken(e){if(!e)throw new Error("Missing token");e=e.replace(_authorizationScheme,"");const t=utf8Decoder.decode(base64$1.decode(e));if(!t||0===t.length||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}async function validateEvent2(e,t,n){if(!e)throw new Error("Invalid nostr event");if(!verifySignature(e))throw new Error("Invalid nostr event, signature invalid");if(27235!==e.kind)throw new Error("Invalid nostr event, kind invalid");if(!e.created_at)throw new Error("Invalid nostr event, created_at invalid");if(Math.round((new Date).getTime()/1e3)-e.created_at>60)throw new Error("Invalid nostr event, expired");const r=e.tags.find((e=>"u"===e[0]));if(1!==r?.length&&r?.[1]!==t)throw new Error("Invalid nostr event, url tag invalid");const o=e.tags.find((e=>"method"===e[0]));if(1!==o?.length&&o?.[1].toLowerCase()!==n.toLowerCase())throw new Error("Invalid nostr event, method tag invalid");return!0}var browser={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var e=1e3,t=60*e,n=60*t,r=24*n,o=7*r,s=365.25*r;function i(e,t,n,r){var o=t>=1.5*n;return Math.round(e/n)+" "+r+(o?"s":"")}return ms=function(a,l){l=l||{};var c=typeof a;if("string"===c&&a.length>0)return function(i){if((i=String(i)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(!a)return;var l=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*s;case"weeks":case"week":case"w":return l*o;case"days":case"day":case"d":return l*r;case"hours":case"hour":case"hrs":case"hr":case"h":return l*n;case"minutes":case"minute":case"mins":case"min":case"m":return l*t;case"seconds":case"second":case"secs":case"sec":case"s":return l*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(a);if("number"===c&&isFinite(a))return l.long?function(o){var s=Math.abs(o);if(s>=r)return i(o,s,r,"day");if(s>=n)return i(o,s,n,"hour");if(s>=t)return i(o,s,t,"minute");if(s>=e)return i(o,s,e,"second");return o+" ms"}(a):function(o){var s=Math.abs(o);if(s>=r)return Math.round(o/r)+"d";if(s>=n)return Math.round(o/n)+"h";if(s>=t)return Math.round(o/t)+"m";if(s>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function setup(e){function t(e){let r,o,s,i=null;function a(...e){if(!a.enabled)return;const n=a,o=Number(new Date),s=o-(r||o);n.diff=s,n.prev=r,n.curr=o,r=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,o)=>{if("%%"===r)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];r=s.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),o=r.length;for(n=0;n<o;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=requireMs(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}var common=setup;!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(o=r))})),t.splice(o,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=common(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(browser,browser.exports);var browserExports=browser.exports,debug3=getDefaultExportFromCjs(browserExports),dist={},LRUCache$1={},LRUCacheNode$1={};Object.defineProperty(LRUCacheNode$1,"__esModule",{value:!0}),LRUCacheNode$1.LRUCacheNode=void 0;class LRUCacheNode{constructor(e,t,n){const{entryExpirationTimeInMS:r=null,next:o=null,prev:s=null,onEntryEvicted:i,onEntryMarkedAsMostRecentlyUsed:a,clone:l,cloneFn:c}=null!=n?n:{};if("number"==typeof r&&(r<=0||Number.isNaN(r)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.clone=null!=l&&l,this.cloneFn=null!=c?c:this.defaultClone,this.key=e,this.internalValue=this.clone?this.cloneFn(t):t,this.created=Date.now(),this.entryExpirationTimeInMS=r,this.next=o,this.prev=s,this.onEntryEvicted=i,this.onEntryMarkedAsMostRecentlyUsed=a}get value(){return this.clone?this.cloneFn(this.internalValue):this.internalValue}get isExpired(){return"number"==typeof this.entryExpirationTimeInMS&&Date.now()-this.created>this.entryExpirationTimeInMS}invokeOnEvicted(){if(this.onEntryEvicted){const{key:e,value:t,isExpired:n}=this;this.onEntryEvicted({key:e,value:t,isExpired:n})}}invokeOnEntryMarkedAsMostRecentlyUsed(){if(this.onEntryMarkedAsMostRecentlyUsed){const{key:e,value:t}=this;this.onEntryMarkedAsMostRecentlyUsed({key:e,value:t})}}defaultClone(e){return"boolean"==typeof e||"string"==typeof e||"number"==typeof e?e:JSON.parse(JSON.stringify(e))}}LRUCacheNode$1.LRUCacheNode=LRUCacheNode,Object.defineProperty(LRUCache$1,"__esModule",{value:!0}),LRUCache$1.LRUCache=void 0;const LRUCacheNode_1=LRUCacheNode$1;class LRUCache{constructor(e){this.lookupTable=new Map,this.head=null,this.tail=null;const{maxSize:t=25,entryExpirationTimeInMS:n=null,onEntryEvicted:r,onEntryMarkedAsMostRecentlyUsed:o,cloneFn:s,clone:i}=null!=e?e:{};if(Number.isNaN(t)||t<=0)throw new Error("maxSize must be greater than 0.");if("number"==typeof n&&(n<=0||Number.isNaN(n)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.maxSizeInternal=t,this.entryExpirationTimeInMS=n,this.onEntryEvicted=r,this.onEntryMarkedAsMostRecentlyUsed=o,this.clone=i,this.cloneFn=s}get size(){return this.cleanCache(),this.lookupTable.size}get remainingSize(){return this.maxSizeInternal-this.size}get newest(){return this.head?this.head.isExpired?(this.removeNodeFromListAndLookupTable(this.head),this.newest):this.mapNodeToEntry(this.head):null}get oldest(){return this.tail?this.tail.isExpired?(this.removeNodeFromListAndLookupTable(this.tail),this.oldest):this.mapNodeToEntry(this.tail):null}get maxSize(){return this.maxSizeInternal}set maxSize(e){if(Number.isNaN(e)||e<=0)throw new Error("maxSize must be greater than 0.");this.maxSizeInternal=e,this.enforceSizeLimit()}set(e,t,n){const r=this.lookupTable.get(e);r&&this.removeNodeFromListAndLookupTable(r);const o=new LRUCacheNode_1.LRUCacheNode(e,t,{entryExpirationTimeInMS:this.entryExpirationTimeInMS,onEntryEvicted:this.onEntryEvicted,onEntryMarkedAsMostRecentlyUsed:this.onEntryMarkedAsMostRecentlyUsed,clone:this.clone,cloneFn:this.cloneFn,...n});return this.setNodeAsHead(o),this.lookupTable.set(e,o),this.enforceSizeLimit(),this}get(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):(this.setNodeAsHead(t),t.value):null}peek(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):t.value:null}delete(e){const t=this.lookupTable.get(e);return!!t&&this.removeNodeFromListAndLookupTable(t)}has(e){const t=this.lookupTable.get(e);return!!t&&(!t.isExpired||(this.removeNodeFromListAndLookupTable(t),!1))}clear(){this.head=null,this.tail=null,this.lookupTable.clear()}find(e){let t=this.head;for(;t;){if(t.isExpired){const e=t.next;this.removeNodeFromListAndLookupTable(t),t=e;continue}const n=this.mapNodeToEntry(t);if(e(n))return this.setNodeAsHead(t),n;t=t.next}return null}forEach(e){let t=this.head,n=0;for(;t;)if(t.isExpired){const e=t.next;this.removeNodeFromListAndLookupTable(t),t=e}else e(t.value,t.key,n),t=t.next,n++}*values(){let e=this.head;for(;e;)if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t}else yield e.value,e=e.next}*keys(){let e=this.head;for(;e;)if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t}else yield e.key,e=e.next}*entries(){let e=this.head;for(;e;)if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t}else yield this.mapNodeToEntry(e),e=e.next}*[Symbol.iterator](){let e=this.head;for(;e;)if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t}else yield this.mapNodeToEntry(e),e=e.next}enforceSizeLimit(){let e=this.tail;for(;null!==e&&this.size>this.maxSizeInternal;){const t=e.prev;this.removeNodeFromListAndLookupTable(e),e=t}}mapNodeToEntry({key:e,value:t}){return{key:e,value:t}}setNodeAsHead(e){this.removeNodeFromList(e),this.head?(e.next=this.head,this.head.prev=e,this.head=e):(this.head=e,this.tail=e),e.invokeOnEntryMarkedAsMostRecentlyUsed()}removeNodeFromList(e){null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(e.next.prev=e.prev),this.head===e&&(this.head=e.next),this.tail===e&&(this.tail=e.prev),e.next=null,e.prev=null}removeNodeFromListAndLookupTable(e){return e.invokeOnEvicted(),this.removeNodeFromList(e),this.lookupTable.delete(e.key)}cleanCache(){if(!this.entryExpirationTimeInMS)return;const e=[];for(const t of this.lookupTable.values())t.isExpired&&e.push(t);e.forEach((e=>this.removeNodeFromListAndLookupTable(e)))}}LRUCache$1.LRUCache=LRUCache,function(e){var t=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=commonjsGlobal&&commonjsGlobal.__exportStar||function(e,n){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(n,r)||t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),n(LRUCache$1,e)}(dist);var lib={};!function(e){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const t=(e,t)=>n=>e(t(n));return{encode:Array.from(e).reverse().reduce(((e,n)=>e?t(e,n.encode):n.encode),void 0),decode:e.reduce(((e,n)=>e?t(e,n.decode):n.decode),void 0)}}function r(e){return{encode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("alphabet.encode input should be an array of numbers");return n.map((n=>{if(t(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]}))},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map((t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const n=e.indexOf(t);if(-1===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}}function o(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function s(e,n="="){if(t(e),"string"!=typeof n)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(n);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let r=t.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&t[r-1]===n;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,r)}}}function i(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function a(e,n,r){if(n<2)throw new Error(`convertRadix: wrong from=${n}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const s=[],i=Array.from(e);for(i.forEach((e=>{if(t(e),e<0||e>=n)throw new Error(`Wrong integer: ${e}`)}));;){let e=0,t=!0;for(let s=o;s<i.length;s++){const a=i[s],l=n*e+a;if(!Number.isSafeInteger(l)||n*e/n!==e||l-a!=n*e)throw new Error("convertRadix: carry overflow");if(e=l%r,i[s]=Math.floor(l/r),!Number.isSafeInteger(i[s])||i[s]*r+e!==l)throw new Error("convertRadix: carry overflow");t&&(i[s]?t=!1:o=s)}if(s.push(e),t)break}for(let t=0;t<e.length-1&&0===e[t];t++)s.push(0);return s.reverse()}
|
|
16
16
|
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
17
|
-
Object.defineProperty(e,"__esModule",{value:!0}),e.bytes=e.stringToBytes=e.str=e.bytesToString=e.hex=e.utf8=e.bech32m=e.bech32=e.base58check=e.base58xmr=e.base58xrp=e.base58flickr=e.base58=e.base64url=e.base64=e.base32crockford=e.base32hex=e.base32=e.base16=e.utils=e.assertNumber=void 0,e.assertNumber=t;const l=(e,t)=>t?l(t,e%t):e,c=(e,t)=>e+(t-l(e,t));function d(e,n,r,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(c(n,r)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${r} carryBits=${c(n,r)}`);let s=0,i=0;const a=2**r-1,l=[];for(const o of e){if(t(o),o>=2**n)throw new Error(`convertRadix2: invalid data word=${o} from=${n}`);if(s=s<<n|o,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=r;i-=r)l.push((s>>i-r&a)>>>0);s&=2**i-1}if(s=s<<r-i&a,!o&&i>=n)throw new Error("Excess padding");if(!o&&s)throw new Error(`Non-zero padding: ${s}`);return o&&i>0&&l.push(s>>>0),l}function h(e){return t(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return a(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(a(t,e,256))}}}function u(e,n=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(c(8,e)>32||c(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return d(Array.from(t),8,e,!n)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(d(t,e,8,n))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function f(e,n){if(t(e),"function"!=typeof n)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const r=n(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(r,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const r=t.slice(0,-e),o=n(r).slice(0,e),s=t.slice(-e);for(let t=0;t<e;t++)if(o[t]!==s[t])throw new Error("Invalid checksum");return r}}}e.utils={alphabet:r,chain:n,checksum:f,radix:h,radix2:u,join:o,padding:s},e.base16=n(u(4),r("0123456789ABCDEF"),o("")),e.base32=n(u(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),o("")),e.base32hex=n(u(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),o("")),e.base32crockford=n(u(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),o(""),i((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),e.base64=n(u(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),o("")),e.base64url=n(u(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),o(""));const g=e=>n(h(58),r(e),o(""));e.base58=g("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.base58flickr=g("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),e.base58xrp=g("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const m=[0,2,3,5,6,7,9,10,11];e.base58xmr={encode(t){let n="";for(let r=0;r<t.length;r+=8){const o=t.subarray(r,r+8);n+=e.base58.encode(o).padStart(m[o.length],"1")}return n},decode(t){let n=[];for(let r=0;r<t.length;r+=11){const o=t.slice(r,r+11),s=m.indexOf(o.length),i=e.base58.decode(o);for(let e=0;e<i.length-s;e++)if(0!==i[e])throw new Error("base58xmr: wrong padding");n=n.concat(Array.from(i.slice(i.length-s)))}return Uint8Array.from(n)}};e.base58check=t=>n(f(4,(e=>t(t(e)))),e.base58);const b=n(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),o("")),y=[996825010,642813549,513874426,1027748829,705979059];function w(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<y.length;e++)1==(t>>e&1)&&(n^=y[e]);return n}function v(e,t,n=1){const r=e.length;let o=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);o=w(o)^n>>5}o=w(o);for(let t=0;t<r;t++)o=w(o)^31&e.charCodeAt(t);for(let e of t)o=w(o)^e;for(let e=0;e<6;e++)o=w(o);return o^=n,b.encode(d([o%2**30],30,5,!1))}function k(e){const t="bech32"===e?1:734539939,n=u(5),r=n.decode,o=n.encode,s=p(r);function i(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=r).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const s=e.slice(0,o),i=e.slice(o+1);if(i.length<6)throw new Error("Data must be at least 6 characters long");const a=b.decode(i).slice(0,-6),l=v(s,a,t);if(!i.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:s,words:a}}return{encode:function(e,n,r=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const o=e.length+7+n.length;if(!1!==r&&o>r)throw new TypeError(`Length ${o} exceeds limit ${r}`);return`${e=e.toLowerCase()}1${b.encode(n)}${v(e,n,t)}`},decode:i,decodeToBytes:function(e){const{prefix:t,words:n}=i(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:p(i),fromWords:r,fromWordsUnsafe:s,toWords:o}}e.bech32=k("bech32"),e.bech32m=k("bech32m"),e.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},e.hex=n(u(4),r("0123456789abcdef"),o(""),i((e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));const x={utf8:e.utf8,hex:e.hex,base16:e.base16,base32:e.base32,base64:e.base64,base64url:e.base64url,base58:e.base58,base58xmr:e.base58xmr},E=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;e.bytesToString=(e,t)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(E);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(t)},e.str=e.bytesToString;e.stringToBytes=(e,t)=>{if(!x.hasOwnProperty(e))throw new TypeError(E);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return x[e].decode(t)},e.bytes=e.stringToBytes}(lib);const{bech32:bech32,hex:hex,utf8:utf8}=lib;BigInt(1e3),BigInt(1e6),BigInt(1e9),BigInt(1e12),BigInt("2100000000000000000"),BigInt(1e11);const TAGCODES={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27};for(let e=0,t=Object.keys(TAGCODES);e<t.length;e++)t[e],TAGCODES[t[e]].toString();var NDKRelayConnectivity=class{ndkRelay;_status;relay;connectedAt;_connectionStats={attempts:0,success:0,durations:[]};debug;constructor(e){this.ndkRelay=e,this._status=3,this.relay=relayInit(this.ndkRelay.url),this.debug=this.ndkRelay.debug.extend("connectivity"),this.relay.on("notice",(e=>this.handleNotice(e)))}async initiateAuth(e={limit:1}){this.debug("Initiating authentication");const t=this.relay.sub([e],{id:"auth-test"});t.on("eose",(()=>{t.unsub(),this._status=1,this.ndkRelay.emit("ready"),this.debug("Authentication not required"),t.unsub()})),this.debug("Authentication request started")}async connect(){const e=()=>{this.updateConnectionStats.connected(),this.ndkRelay.authRequired?(this._status=6,this.ndkRelay.emit("connect"),this.initiateAuth()):(this._status=1,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready"))},t=()=>{this.updateConnectionStats.disconnected(),1===this._status&&(this._status=3,this.handleReconnection()),this.ndkRelay.emit("disconnect")},n=async e=>{this.debug("Relay requested authentication",{havePolicy:!!this.ndkRelay.authPolicy}),this.ndkRelay.authPolicy?7!==this._status&&(this._status=7,await this.ndkRelay.authPolicy(this.ndkRelay,e),7===this._status&&(this.debug("Authentication policy finished"),this._status=1,this.ndkRelay.emit("ready"))):await this.ndkRelay.emit("auth",e)};try{this.updateConnectionStats.attempt(),this._status=0,this.relay.off("connect",e),this.relay.off("disconnect",t),this.relay.on("connect",e),this.relay.on("disconnect",t),this.relay.on("auth",n),await this.relay.connect()}catch(e){throw this.debug("Failed to connect",e),this._status=3,e}}disconnect(){this._status=2,this.relay.close()}get status(){return this._status}isAvailable(){return 1===this._status}isFlapping(){const e=this._connectionStats.durations;if(e.length%3!=0)return!1;const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.map((e=>Math.pow(e-t,2))).reduce(((e,t)=>e+t),0)/e.length;return Math.sqrt(n)<1e3}async handleNotice(e){(e.includes("oo many")||e.includes("aximum"))&&(this.disconnect(),setTimeout((()=>this.connect()),2e3),this.debug(this.relay.url,"Relay complaining?",e)),this.ndkRelay.emit("notice",this,e)}handleReconnection(e=0){if(this.isFlapping())return this.ndkRelay.emit("flapping",this,this._connectionStats),void(this._status=5);const t=this.connectedAt?Math.max(0,6e4-(Date.now()-this.connectedAt)):0;setTimeout((()=>{this._status=4,this.connect().then((()=>{this.debug("Reconnected")})).catch((t=>{this.debug("Reconnect failed",t),e<5?setTimeout((()=>{this.handleReconnection(e+1)}),6e4):this.debug("Reconnect failed after 5 attempts")}))}),t)}updateConnectionStats={connected:()=>{this._connectionStats.success++,this._connectionStats.connectedAt=Date.now()},disconnected:()=>{this._connectionStats.connectedAt&&(this._connectionStats.durations.push(Date.now()-this._connectionStats.connectedAt),this._connectionStats.durations.length>100&&this._connectionStats.durations.shift()),this._connectionStats.connectedAt=void 0},attempt:()=>{this._connectionStats.attempts++}};get connectionStats(){return this._connectionStats}},NDKRelayPublisher=class{ndkRelay;constructor(e){this.ndkRelay=e}async publish(e,t=2500){const n=()=>new Promise(((n,r)=>{try{this.publishEvent(e,t).then((e=>n(e))).catch((e=>r(e)))}catch(e){r(e)}})),r=new Promise(((e,n)=>{setTimeout((()=>n(new Error("Timeout"))),t)})),o=()=>{n().then((e=>s(e))).catch((e=>i(e)))};let s,i;return 1===this.ndkRelay.status?Promise.race([n(),r]):Promise.race([new Promise(((e,t)=>{s=e,i=t,this.ndkRelay.once("connect",o)})),r]).finally((()=>{this.ndkRelay.removeListener("connect",o)}))}async publishEvent(e,t){const n=await e.toNostrEvent(),r=this.ndkRelay.connectivity.relay.publish(n);let o;const s=new Promise(((t,n)=>{r.then((()=>{clearTimeout(o),this.ndkRelay.emit("published",e),t(!0)})).catch((t=>{clearTimeout(o),this.ndkRelay.debug("Publish failed",t,e.id),this.ndkRelay.emit("publish:failed",e,t),n(t)}))}));if(!t||e.isEphemeral())return s;const i=new Promise(((n,r)=>{o=setTimeout((()=>{this.ndkRelay.debug("Publish timed out",e.rawEvent()),this.ndkRelay.emit("publish:failed",e,"Timeout"),r(new Error("Publish operation timed out"))}),t)}));return Promise.race([s,i])}async auth(e){return this.ndkRelay.connectivity.relay.auth(e.rawEvent())}};function calculateGroupableId(e){const t=[];for(const n of e){if(n.since||n.until)return null;const e=Object.keys(n||{}).sort().join("-");t.push(e)}return t.join("|")}function mergeFilters(e){const t={};return e.forEach((e=>{Object.entries(e).forEach((([e,n])=>{Array.isArray(n)?void 0===t[e]?t[e]=[...n]:t[e]=Array.from(new Set([...t[e],...n])):t[e]=n}))})),t}var MAX_SUBID_LENGTH=20;function queryFullyFilled(e){return!(!filterIncludesIds(e.filter)||!resultHasAllRequestedIds(e))}function compareFilter(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const[n,r]of Object.entries(e)){const e=t[n];if(!e)return!1;if(Array.isArray(r)&&Array.isArray(e)){const t=r;for(const n of e){const e=n;if(!t.includes(e))return!1}}else if(e!==r)return!1}return!0}function filterIncludesIds(e){return!!e.ids}function resultHasAllRequestedIds(e){const t=e.filter.ids;return!!t&&t.length===e.eventFirstSeen.size}function generateSubId(e,t){const n=e.map((e=>e.subId)).filter(Boolean),r=[],o=new Set,s=new Set;if(n.length>0)r.push(Array.from(new Set(n)).join(","));else{for(const e of t)for(const t of Object.keys(e))"kinds"===t?e.kinds?.forEach((e=>s.add(e))):o.add(t);s.size>0&&r.push("kinds:"+Array.from(s).join(",")),o.size>0&&r.push(Array.from(o).join(","))}let i=r.join("-");return i.length>MAX_SUBID_LENGTH&&(i=i.substring(0,MAX_SUBID_LENGTH)),1!==n.length&&(i+="-"+Math.floor(999*Math.random()).toString()),i}function filterFromId(e){let t;if(e.match(NIP33_A_REGEX)){const[t,n,r]=e.split(":"),o={authors:[n],kinds:[parseInt(t)]};return r&&(o["#d"]=[r]),o}try{switch(t=nip19_exports.decode(e),t.type){case"nevent":return{ids:[t.data.id]};case"note":return{ids:[t.data]};case"naddr":return{authors:[t.data.pubkey],"#d":[t.data.identifier],kinds:[t.data.kind]}}}catch(e){}return{ids:[e]}}function isNip33AValue(e){return null!==e.match(NIP33_A_REGEX)}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/;function relaysFromBech32(e){try{const t=nip19_exports.decode(e);if(["naddr","nevent"].includes(t?.type)){const e=t.data;if(e?.relays)return e.relays.map((e=>new NDKRelay(e)))}}catch(e){}return[]}var NDKGroupedSubscriptions=class extends lib$1.EventEmitter{subscriptions;req;debug;constructor(e,t){super(),this.subscriptions=e,this.debug=t||this.subscriptions[0].subscription.debug.extend("grouped");for(const t of e)this.handleSubscriptionClosure(t)}addSubscription(e){this.subscriptions.push(e),this.handleSubscriptionClosure(e)}eventReceived(e){for(const t of this.subscriptions)t.eventReceived(e)}eoseReceived(e){Array.from(this.subscriptions).forEach((async t=>{t.subscription.eoseReceived(e)}))}handleSubscriptionClosure(e){e.subscription.on("close",(()=>{const t=this.subscriptions.findIndex((t=>t.subscription===e.subscription));this.subscriptions.splice(t,1),this.subscriptions.length<=0&&this.emit("close")}))}map(e){return this.subscriptions.map(e)}[Symbol.iterator](){let e=0;const t=this.subscriptions;return{next:()=>e<t.length?{value:t[e++],done:!1}:{value:null,done:!0}}}},NDKSubscriptionFilters=class{subscription;filters=[];ndkRelay;constructor(e,t,n){this.subscription=e,this.filters=t,this.ndkRelay=n}eventReceived(e){this.eventMatchesLocalFilter(e)&&this.subscription.eventReceived(e,this.ndkRelay,!1)}eventMatchesLocalFilter(e){const t=e.rawEvent();return this.filters.some((e=>matchFilter(e,t)))}};function findMatchingActiveSubscriptions(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length&&compareFilter(e[n],t[n]);n++)return e[n]}var NDKRelaySubscriptions=class{ndkRelay;delayedItems=new Map;delayedTimers=new Map;activeSubscriptions=new Map;activeSubscriptionsByGroupId=new Map;executionTimeoutsByGroupId=new Map;debug;groupingDebug;conn;constructor(e){this.ndkRelay=e,this.conn=e.connectivity,this.debug=e.debug.extend("subscriptions"),this.groupingDebug=e.debug.extend("grouping")}subscribe(e,t){const n=calculateGroupableId(t),r=new NDKSubscriptionFilters(e,t,this.ndkRelay);if(!n||!e.isGroupable())return void this.executeSubscriptions(n,new NDKGroupedSubscriptions([r]),t);const o=this.activeSubscriptionsByGroupId.get(n);if(o){if(findMatchingActiveSubscriptions(o.filters,t)){const n=this.activeSubscriptions.get(o.sub);return void n?.addSubscription(new NDKSubscriptionFilters(e,t,this.ndkRelay))}}let s=this.delayedItems.get(n);s?s.addSubscription(r):(s=new NDKGroupedSubscriptions([r]),this.delayedItems.set(n,s),s.once("close",(()=>{this.delayedItems.get(n)&&this.delayedItems.delete(n)})));let i=this.executionTimeoutsByGroupId.get(n);i&&"at-most"!==e.opts.groupableDelayType||(i=setTimeout((()=>{this.executeGroup(n,e)}),e.opts.groupableDelay),this.executionTimeoutsByGroupId.set(n,i)),this.delayedTimers.has(n)?this.delayedTimers.get(n).push(i):this.delayedTimers.set(n,[i])}executeGroup(e,t){const n=this.delayedItems.get(e);this.delayedItems.delete(e);const r=this.delayedTimers.get(e);if(this.delayedTimers.delete(e),r)for(const e of r)clearTimeout(e);if(n){const t=n.subscriptions[0].filters.length,r=[];for(let e=0;e<t;e++){const t=n.map((t=>t.filters[e]));r.push(mergeFilters(t))}this.executeSubscriptions(e,n,r)}}executeSubscriptionsWhenConnected(e,t,n){const r=()=>{this.debug("new relay coming online for active subscription",{relay:this.ndkRelay.url,mergeFilters:mergeFilters}),this.executeSubscriptionsConnected(e,t,n)};this.ndkRelay.once("ready",r),t.once("close",(()=>{this.ndkRelay.removeListener("ready",r)}))}executeSubscriptions(e,t,n){this.conn.isAvailable()?this.executeSubscriptionsConnected(e,t,n):this.executeSubscriptionsWhenConnected(e,t,n)}executeSubscriptionsConnected(e,t,n){const r=[];for(const{subscription:e}of t)r.push(e);const o=generateSubId(r,n);t.req=n;const s={id:o};(this.ndkRelay.trusted||r.every((e=>e.opts.skipVerification)))&&(s.skipVerification=!0);const i=this.conn.relay.sub(n,s);return this.activeSubscriptions.set(i,t),e&&this.activeSubscriptionsByGroupId.set(e,{filters:n,sub:i}),i.on("event",(e=>{const t=new NDKEvent(void 0,e);t.relay=this.ndkRelay;const n=this.activeSubscriptions.get(i);n?.eventReceived(t)})),i.on("eose",(()=>{const e=this.activeSubscriptions.get(i);e?.eoseReceived(this.ndkRelay)})),t.once("close",(()=>{i.unsub(),this.activeSubscriptions.delete(i),e&&this.activeSubscriptionsByGroupId.delete(e)})),this.executeSubscriptionsWhenConnected(e,t,n),i}executedFilters(){const e=new Map;for(const[,t]of this.activeSubscriptions)e.set(t.req,t.map((e=>e.subscription)));return e}},NDKRelay=class extends lib$1.EventEmitter{url;scores;connectivity;subs;publisher;authPolicy;authRequired=!1;trusted=!1;complaining=!1;debug;constructor(e,t){super(),this.url=e,this.scores=new Map,this.debug=debug3(`ndk:relay:${e}`),this.connectivity=new NDKRelayConnectivity(this),this.subs=new NDKRelaySubscriptions(this),this.publisher=new NDKRelayPublisher(this),this.authPolicy=t}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(){return this.connectivity.connect()}disconnect(){3!==this.status&&this.connectivity.disconnect()}subscribe(e,t){this.subs.subscribe(e,t)}async publish(e,t=2500){return this.publisher.publish(e,t)}async auth(e){return this.publisher.auth(e)}scoreSlowerEvent(e){}tagReference(e){const t=["r",this.url];return e&&t.push(e),t}referenceTags(){return[["r",this.url]]}activeSubscriptions(){return this.subs.executedFilters()}},PublishError=class extends Error{errors;constructor(e,t){super(e),this.errors=t}},NDKRelaySet=class e{relays;debug;ndk;constructor(e,t){this.relays=e,this.ndk=t,this.debug=t.debug.extend("relayset")}addRelay(e){this.relays.add(e)}static fromRelayUrls(t,n){const r=new Set;for(const e of t){const t=n.pool.relays.get(e);if(t)r.add(t);else{const t=new NDKRelay(e);n.pool.useTemporaryRelay(t),r.add(t)}}return new e(new Set(r),n)}async publish(e,t){const n=new Set,r=new Map,o=e.isEphemeral(),s=Array.from(this.relays).map((s=>new Promise((i=>{s.publish(e,t).then((()=>{n.add(s),i()})).catch((e=>{o||(r.set(s,e),this.debug("error publishing to relay",{relay:s.url,err:e})),i()}))}))));if(await Promise.all(s),0===n.size&&!o)throw new PublishError("No relay was able to receive the event",r);return n}size(){return this.relays.size}};function calculateRelaySetFromEvent(e,t){const n=new Set;return e.pool?.relays.forEach((e=>n.add(e))),new NDKRelaySet(n,e)}function getWriteRelaysFor(e,t){if(e.outboxTracker)return e.outboxTracker.data.get(t)?.writeRelays}function calculateRelaySetsFromFilter(e,t){const n=new Map,r=new Set;if(t.forEach((e=>{e.authors&&e.authors.forEach((e=>r.add(e)))})),r.size>0){const o=new Map;for(const t of r){const n=getWriteRelaysFor(e,t);n&&n.size>0?(e.debug(`Adding ${n.size} relays for ${t}`),n.forEach((e=>{const n=o.get(e)||[];n.push(t),o.set(e,n)}))):e.explicitRelayUrls?.forEach((e=>{const n=o.get(e)||[];n.push(t),o.set(e,n)}))}for(const e of o.keys())n.set(e,[]);for(const e of t)if(e.authors)for(const[t,r]of o.entries()){const o=e.authors.filter((e=>r.includes(e)));n.set(t,[...n.get(t),{...e,authors:o}])}else for(const t of o.keys())n.set(t,[...n.get(t),e])}else e.explicitRelayUrls?.forEach((e=>{n.set(e,t)}));return n}function calculateRelaySetsFromFilters(e,t){return calculateRelaySetsFromFilter(e,t)}var DEFAULT_RELAYS=["wss://nos.lol","wss://relay.nostr.band","wss://relay.f7z.io","wss://relay.damus.io","wss://nostr.mom","wss://no.str.cr"],Zap=class extends lib$1.EventEmitter{ndk;zappedEvent;zappedUser;constructor(e){super(),this.ndk=e.ndk,this.zappedEvent=e.zappedEvent,this.zappedUser=e.zappedUser||this.ndk.getUser({hexpubkey:this.zappedEvent?.pubkey})}async getZapEndpoint(){let e,t,n,r;if(this.zappedUser&&(this.zappedUser.profile||await this.zappedUser.fetchProfile({groupable:!1}),e=(this.zappedUser.profile||{}).lud06,t=(this.zappedUser.profile||{}).lud16),t&&!t.startsWith("LNURL")){const[e,r]=t.split("@");n=`https://${r}/.well-known/lnurlp/${e}`}else if(e){const{words:t}=bech32$1.decode(e,1e3),r=bech32$1.fromWords(t);n=new TextDecoder("utf-8").decode(r)}if(!n)throw new Error("No zap endpoint found");try{const e=this.ndk.httpFetch||fetch,t=await e(n);if(200!==t.status){const e=await t.text();throw new Error(`Unable to fetch zap endpoint ${n}: ${e}`)}const o=await t.json();return o?.allowsNostr&&(o?.nostrPubkey||o?.nostrPubKey)&&(r=o.callback),r}catch(e){throw new Error(`Unable to fetch zap endpoint ${n}: ${e}`)}}async createZapRequest(e,t,n,r,o){const s=await this.generateZapRequest(e,t,n,r);if(!s)return null;const{event:i,zapEndpoint:a}=s;if(!i)throw new Error("No zap request event found");let l;await i.sign(o);try{l=await this.getInvoice(i,e,a)}catch(e){throw new Error("Failed to get invoice: "+e)}return l}async getInvoice(e,t,n){const r=await fetch(`${n}?`+new URLSearchParams({amount:t.toString(),nostr:JSON.stringify(e.rawEvent())}));return(await r.json()).pr}async generateZapRequest(e,t,n,r,o){const s=await this.getZapEndpoint();if(!s)throw new Error("No zap endpoint found");if(!this.zappedEvent&&!this.zappedUser)throw new Error("No zapped event or user found");const i=nip57_exports.makeZapRequest({profile:this.zappedUser.pubkey,event:null,amount:e,comment:t||"",relays:r??this.relays()});if(this.zappedEvent){const e=this.zappedEvent.referenceTags();i.tags.push(...e)}i.tags.push(["lnurl",s]);const a=new NDKEvent(this.ndk,i);return n&&(a.tags=a.tags.concat(n)),{event:a,zapEndpoint:s}}relays(){let e=[];return this.ndk?.pool?.relays&&(e=this.ndk.pool.urls()),e.length||(e=DEFAULT_RELAYS),e}};function mergeTags(e,t){const n=new Map,r=(e,t)=>e.every(((e,n)=>e===t[n]));return e.concat(t).forEach((e=>{for(let[t,o]of n)if(r(o,e)||r(e,o))return void(e.length>=o.length&&n.set(t,e));n.set((e=>e.join(","))(e),e)})),Array.from(n.values())}async function generateContentTags(e,t=[]){let n=[];const r=e=>{t.find((t=>t[0]===e[0]&&t[1]===e[1]))||t.push(e)};return e=e.replace(/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,(e=>{try{const t=e.split(/(@|nostr:)/)[2],{type:o,data:s}=nip19_exports.decode(t);let i;switch(o){case"npub":i=["p",s];break;case"nprofile":i=["p",s.pubkey];break;case"note":n.push(new Promise((async e=>{r(["e",s,await maybeGetEventRelayUrl(t),"mention"]),e()})));break;case"nevent":n.push(new Promise((async e=>{let{id:n,relays:o,author:i}=s;o&&0!==o.length||(o=[await maybeGetEventRelayUrl(t)]),r(["e",n,o[0],"mention"]),i&&r(["p",i]),e()})));break;case"naddr":n.push(new Promise((async e=>{const n=[s.kind,s.pubkey,s.identifier].join(":");let o=s.relays??[];0===o.length&&(o=[await maybeGetEventRelayUrl(t)]),r(["a",n,o[0],"mention"]),r(["p",s.pubkey]),e()})));break;default:return e}return i&&r(i),`nostr:${t}`}catch(t){return e}})),await Promise.all(n),{content:e=e.replace(/#(\w+)/g,((e,n)=>{const r=["t",n];return t.find((e=>e[0]===r[0]&&e[1]===r[1]))||t.push(r),e})),tags:t}}async function maybeGetEventRelayUrl(e){return""}function isReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=1e4&&this.kind<2e4}function isEphemeral(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}async function encrypt(e,t){if(!this.ndk)throw new Error("No NDK instance found!");if(t||(await this.ndk.assertSigner(),t=this.ndk.signer),!e){const t=this.getMatchingTags("p");if(1!==t.length)throw new Error("No recipient could be determined and no explicit recipient was provided");e=this.ndk.getUser({hexpubkey:t[0][1]})}this.content=await(t?.encrypt(e,this.content))}async function decrypt(e,t){if(!this.ndk)throw new Error("No NDK instance found!");t||(await this.ndk.assertSigner(),t=this.ndk.signer),e||(e=this.author),this.content=await(t?.decrypt(e,this.content))}function encode(){return this.isParamReplaceable()?nip19_exports.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:this.relay?[this.relay.url]:[]}):this.relay?nip19_exports.neventEncode({id:this.tagId(),relays:[this.relay.url],author:this.pubkey}):nip19_exports.noteEncode(this.tagId())}async function repost(e=!0,t){if(!t&&e){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t=this.ndk.signer}const n=new NDKEvent(this.ndk,{kind:getKind(this),content:""});return n.tag(this),16===n.kind&&n.tags.push(["k",`${this.kind}`]),t&&await n.sign(t),e&&await n.publish(),n}function getKind(e){return 1===e.kind?6:16}var NDKEvent=class e extends lib$1.EventEmitter{ndk;created_at;content="";tags=[];kind;id="";sig;pubkey="";_author=void 0;relay;constructor(e,t){super(),this.ndk=e,this.created_at=t?.created_at,this.content=t?.content||"",this.tags=t?.tags||[],this.id=t?.id||"",this.sig=t?.sig,this.pubkey=t?.pubkey||"",this.kind=t?.kind}rawEvent(){return{created_at:this.created_at,content:this.content,tags:this.tags,kind:this.kind,pubkey:this.pubkey,id:this.id,sig:this.sig}}set author(e){this.pubkey=e.hexpubkey,this._author=void 0}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const e=this.ndk.getUser({hexpubkey:this.pubkey});return this._author=e,e}tag(t,n){let r=[];if(t instanceof NDKUser){const e=["p",t.pubkey];n&&e.push(n),r.push(e)}else if(t instanceof e){const e=t,o=e?.pubkey===this.pubkey;r=e.referenceTags(n,o);for(const t of e.getMatchingTags("p"))t[1]!==this.pubkey&&(this.tags.find((e=>"p"===e[0]&&e[1]===t[1]))||this.tags.push(["p",t[1]]))}else r=[t];this.tags=mergeTags(this.tags,r)}async toNostrEvent(e){if(!e&&""===this.pubkey){const e=await(this.ndk?.signer?.user());this.pubkey=e?.hexpubkey||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const t=this.rawEvent(),{content:n,tags:r}=await this.generateTags();t.content=n||"",t.tags=r;try{this.id=getEventHash(t)}catch(e){}return this.id&&(t.id=this.id),this.sig&&(t.sig=this.sig),t}isReplaceable=isReplaceable.bind(this);isEphemeral=isEphemeral.bind(this);isParamReplaceable=isParamReplaceable.bind(this);encode=encode.bind(this);encrypt=encrypt.bind(this);decrypt=decrypt.bind(this);getMatchingTags(e){return this.tags.filter((t=>t[0]===e))}tagValue(e){const t=this.getMatchingTags(e);if(0!==t.length)return t[0][1]}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}removeTag(e){this.tags=this.tags.filter((t=>t[0]!==e))}async sign(e){e?this.author=await e.user():(this.ndk?.assertSigner(),e=this.ndk.signer),await this.generateTags(),this.isReplaceable()&&(this.created_at=Math.floor(Date.now()/1e3));const t=await this.toNostrEvent();return this.sig=await e.sign(t),this.sig}async publish(e,t){if(this.sig||await this.sign(),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");return e||(e=this.ndk.devWriteRelaySet||calculateRelaySetFromEvent(this.ndk)),e.publish(this,t)}async generateTags(){let e=[];const t=await generateContentTags(this.content,this.tags),n=t.content;if(e=t.tags,this.kind&&this.isParamReplaceable()){if(!this.getMatchingTags("d")[0]){const t=this.tagValue("title");let n=[...Array(t?6:16)].map((()=>Math.random().toString(36)[2])).join("");t&&t.length>0&&(n=t.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")+"-"+n),e.push(["d",n])}}if((this.ndk?.clientName||this.ndk?.clientNip89)&&!this.tagValue("client")){const t=["client",this.ndk.clientName??""];this.ndk.clientNip89&&t.push(this.ndk.clientNip89),e.push(t)}return{content:n||"",tags:e}}muted(){const e=this.ndk?.mutedIds.get(this.pubkey);if(e&&"p"===e)return"author";const t=this.tagReference(),n=this.ndk?.mutedIds.get(t[1]);return n&&n===t[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const e=this.getMatchingTags("d")[0];return e?e[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return 0===this.kind||3===this.kind||this.kind&&this.kind>=1e4&&this.kind<2e4?`${this.kind}:${this.pubkey}`:this.tagId()}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}tagAddress(){if(!this.isParamReplaceable())throw new Error("This must only be called on replaceable events");const e=this.replaceableDTag();return`${this.kind}:${this.pubkey}:${e}`}tagReference(e){let t;return t=this.isParamReplaceable()?["a",this.tagAddress()]:["e",this.tagId()],this.relay?t.push(this.relay.url):t.push(""),e&&t.push(e),t}referenceTags(e,t){let n=[];return n=this.isParamReplaceable()?[["a",this.tagAddress()],["e",this.id]]:[["e",this.id]],this.relay?.url?n=n.map((e=>(e.push(this.relay?.url),e))):e&&(n=n.map((e=>(e.push(""),e)))),e&&n.forEach((t=>t.push(e))),t||n.push(...this.author.referenceTags()),n}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}async zap(e,t,n,r,o){if(!this.ndk)throw new Error("No NDK instance found");o||this.ndk.assertSigner();const s=new Zap({ndk:this.ndk,zappedEvent:this,zappedUser:r}),i=Array.from(this.ndk.pool.relays.keys());return await s.createZapRequest(e,t,n,i,o)}async delete(t){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const n=new e(this.ndk,{kind:5,content:t||""});return n.tag(this),await n.publish(),n}repost=repost.bind(this);async react(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const r=new e(this.ndk,{kind:7,content:t});return r.tag(this),n?await r.publish():await r.sign(),r}get isValid(){return!0}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class e extends NDKEvent{constructor(e,t){super(e,t),this.kind??=10002}static from(t){return new e(t.ndk,t.rawEvent())}get readRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2]||e[2]&&e[2]===READ_MARKER)).map((e=>e[1]))}set readRelayUrls(e){for(const t of e)this.tags.push(["r",t,READ_MARKER])}get writeRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2]||e[2]&&e[2]===WRITE_MARKER)).map((e=>e[1]))}set writeRelayUrls(e){for(const t of e)this.tags.push(["r",t,WRITE_MARKER])}get bothRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2])).map((e=>e[1]))}set bothRelayUrls(e){for(const t of e)this.tags.push(["r",t])}get relays(){return this.getMatchingTags("r").map((e=>e[1]))}},NDKSubscriptionCacheUsage=(e=>(e.ONLY_CACHE="ONLY_CACHE",e.CACHE_FIRST="CACHE_FIRST",e.PARALLEL="PARALLEL",e.ONLY_RELAY="ONLY_RELAY",e))(NDKSubscriptionCacheUsage||{}),defaultOpts={closeOnEose:!1,cacheUsage:"CACHE_FIRST",groupable:!0,groupableDelay:100,groupableDelayType:"at-most"},NDKSubscription=class extends lib$1.EventEmitter{subId;filters;opts;pool;skipVerification=!1;skipValidation=!1;relayFilters;relaySet;ndk;debug;eoseDebug;eventFirstSeen=new Map;eosesSeen=new Set;eventsPerRelay=new Map;lastEventReceivedAt;internalId;constructor(e,t,n,r,o){if(super(),this.ndk=e,this.pool=n?.pool||e.pool,this.opts={...defaultOpts,...n||{}},this.filters=t instanceof Array?t:[t],this.subId=o||n?.subId,this.internalId=Math.random().toString(36).substring(7),this.relaySet=r,this.debug=e.debug.extend(`subscription[${n?.subId??this.internalId}]`),this.eoseDebug=this.debug.extend("eose"),this.skipVerification=n?.skipVerification||!1,this.skipValidation=n?.skipValidation||!1,this.opts.closeOnEose||this.debug("Creating a permanent subscription",this.opts,JSON.stringify(this.filters)),"ONLY_CACHE"===this.opts.cacheUsage&&!this.opts.closeOnEose)throw new Error("Cannot use cache-only options with a persistent subscription")}get filter(){return this.filters[0]}isGroupable(){return this.opts?.groupable||!1}shouldQueryCache(){return"ONLY_RELAY"!==this.opts?.cacheUsage}shouldQueryRelays(){return"ONLY_CACHE"!==this.opts?.cacheUsage}shouldWaitForCache(){return this.opts.closeOnEose&&!!this.ndk.cacheAdapter?.locking&&"PARALLEL"!==this.opts.cacheUsage}async start(){let e;this.shouldQueryCache()&&(e=this.startWithCache(),this.shouldWaitForCache()&&(await e,queryFullyFilled(this)))?this.emit("eose",this):this.shouldQueryRelays()?this.startWithRelays():this.emit("eose",this)}stop(){this.emit("close",this),this.removeAllListeners()}hasAuthorsFilter(){return this.filters.some((e=>e.authors?.length))}async startWithCache(){if(this.ndk.cacheAdapter?.query){const e=this.ndk.cacheAdapter.query(this);this.ndk.cacheAdapter.locking&&await e}}startWithRelays(){if(this.relaySet){this.relayFilters=new Map;for(const e of this.relaySet.relays)this.relayFilters.set(e.url,this.filters)}else this.relayFilters=calculateRelaySetsFromFilters(this.ndk,this.filters);if(this.relayFilters&&0!==this.relayFilters.size)for(const[e,t]of this.relayFilters){this.pool.getRelay(e).subscribe(this,t)}else this.debug("No relays to subscribe to",this.ndk.explicitRelayUrls)}eventReceived(e,t,n=!1){if(t&&(e.relay=t),t||(t=e.relay),this.skipValidation||e.isValid){if(!n&&t){let n=this.eventsPerRelay.get(t);n||(n=new Set,this.eventsPerRelay.set(t,n)),n.add(e.id);if(this.eventFirstSeen.has(e.id)){const n=Date.now()-(this.eventFirstSeen.get(e.id)||0);return t.scoreSlowerEvent(n),void this.emit("event:dup",e,t,n,this)}this.ndk.cacheAdapter&&this.ndk.cacheAdapter.setEvent(e,this.filters,t),this.eventFirstSeen.set(e.id,Date.now())}else this.eventFirstSeen.set(e.id,0);e.ndk||(e.ndk=this.ndk),this.emit("event",e,t,this),this.lastEventReceivedAt=Date.now()}else this.debug("Event failed validation",e)}eoseTimeout;eoseReceived(e){this.eosesSeen.add(e),this.eoseDebug(`received from ${e.url}`);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const n=this.eosesSeen.size===this.relayFilters?.size;if(queryFullyFilled(this))this.emit("eose"),this.eoseDebug("Query fully filled"),this.opts?.closeOnEose&&this.stop();else if(n)this.emit("eose"),this.eoseDebug("All EOSEs seen"),this.opts?.closeOnEose&&this.stop();else{let e=1e3;const n=this.eosesSeen.size/this.relayFilters.size;if(this.eosesSeen.size>=2&&n>=.5){e*=1-n,this.eoseTimeout&&clearTimeout(this.eoseTimeout);const r=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,void 0!==t&&t<20?this.eoseTimeout=setTimeout(r,e):(this.emit("eose"),this.opts?.closeOnEose&&this.stop())};this.eoseTimeout=setTimeout(r,e)}}}};async function follows(e,t,n=3){if(!this.ndk)throw new Error("NDK not set");const r=Array.from(await this.ndk.fetchEvents({kinds:[n],authors:[this.pubkey]},e||{groupable:!1}))[0];if(r){const e=new Set;return r.tags.forEach((n=>{if("p"===n[0])try{e.add(n[1]),t&&this.ndk?.outboxTracker?.trackUsers([n[1]])}catch(e){}})),[...e].reduce(((e,t)=>{const n=new NDKUser({pubkey:t});return n.ndk=this.ndk,e.add(n),e}),new Set)}return new Set}function profileFromEvent(e){const t={};let n;try{n=JSON.parse(e.content)}catch(e){throw new Error(`Failed to parse profile event: ${e}`)}return Object.keys(n).forEach((e=>{switch(e){case"name":t.name=n.name;break;case"display_name":t.displayName=n.display_name;break;case"image":case"picture":t.image=n.image||n.picture;break;case"banner":t.banner=n.banner;break;case"bio":t.bio=n.bio;break;case"nip05":t.nip05=n.nip05;break;case"lud06":t.lud06=n.lud06;break;case"lud16":t.lud16=n.lud16;break;case"about":t.about=n.about;break;case"zapService":t.zapService=n.zapService;break;case"website":t.website=n.website;break;default:t[e]=n[e]}})),t}function serializeProfile(e){const t={};for(const[n,r]of Object.entries(e))switch(n){case"username":case"name":t.name=r;break;case"displayName":t.display_name=r;break;case"image":case"picture":t.picture=r;break;case"bio":case"about":t.about=r;break;default:t[n]=r}return JSON.stringify(t)}var NDKList=class e extends NDKEvent{_encryptedTags;encryptedTagsLength;constructor(e,t){super(e,t),this.kind??=30001}static from(t){return new e(t.ndk,t.rawEvent())}get title(){const e=this.tagValue("title")||this.tagValue("name");return 3!==this.kind||e?1e4!==this.kind||e?10001!==this.kind||e?10002!==this.kind||e?10003!==this.kind||e?10004!==this.kind||e?10005!==this.kind||e?10006!==this.kind||e?10007!==this.kind||e?10015!==this.kind||e?10030!==this.kind||e?e??this.tagValue("d"):"Emojis":"Interests":"Search Relays":"Blocked Relays":"Public Chats":"Communities":"Bookmarks":"Relay Metadata":"Pinned Notes":"Mute":"Contacts"}set title(e){if(this.removeTag("title"),this.removeTag("name"),!e)throw new Error("Title cannot be empty");this.tags.push(["title",e])}get name(){const e=this.tagValue("name");return 3!==this.kind||e?1e4!==this.kind||e?10001!==this.kind||e?10002!==this.kind||e?10003!==this.kind||e?10004!==this.kind||e?10005!==this.kind||e?10006!==this.kind||e?10007!==this.kind||e?10015!==this.kind||e?10030!==this.kind||e?e??this.tagValue("d"):"Emojis":"Interests":"Search Relays":"Blocked Relays":"Public Chats":"Communities":"Bookmarks":"Relay Metadata":"Pinned Notes":"Mute":"Contacts"}set name(e){if(this.removeTag("name"),!e)throw new Error("Name cannot be empty");this.tags.push(["title",e])}get description(){return this.tagValue("description")}set description(e){e?this.tags.push(["description",e]):this.removeTag("description")}isEncryptedTagsCacheValid(){return!(!this._encryptedTags||this.encryptedTagsLength!==this.content.length)}async encryptedTags(e=!0){if(e&&this.isEncryptedTagsCacheValid())return this._encryptedTags;if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const t=await this.ndk.signer.user();try{if(this.content.length>0)try{const e=await this.ndk.signer.decrypt(t,this.content),n=JSON.parse(e);return n&&n[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=n):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch(e){console.log(`error decrypting ${this.content}`)}}catch(e){}return[]}validateTag(e){return!0}get items(){return this.tags.filter((e=>!["d","L","l","title","name","description","summary","image","thumb","alt","expiration","subject"].includes(e[0])))}async addItem(e,t=void 0,n=!1){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let r;if(e instanceof NDKEvent)r=e.referenceTags();else if(e instanceof NDKUser)r=e.referenceTags();else if(e instanceof NDKRelay)r=e.referenceTags();else{if(!Array.isArray(e))throw new Error("Invalid object type");r=[e]}if(t&&r[0].push(t),n){const e=await this.ndk.signer.user(),t=await this.encryptedTags();t.push(...r),this._encryptedTags=t,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(t),await this.encrypt(e)}else this.tags.push(...r);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(e,t){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(t){const t=await this.ndk.signer.user(),n=await this.encryptedTags();n.splice(e,1),this._encryptedTags=n,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(n),await this.encrypt(t)}else this.tags.splice(e,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}},lists_default=NDKList;async function pin(e,t,n){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),!t){const e=await this.ndk.fetchEvents({kinds:[10001],authors:[this.pubkey]},{cacheUsage:"ONLY_RELAY"});t=e.size>0?lists_default.from(Array.from(e)[0]):new NDKEvent(this.ndk,{kind:10001})}return t.tag(e),n&&await t.publish(),t}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(e,t=fetch,n={}){const r=e.match(NIP05_REGEX);if(!r)return null;const[o,s="_",i]=r;try{const e=await t(`https://${i}/.well-known/nostr.json?name=${s}`,n),{names:r,relays:o,nip46:a}=parseNIP05Result(await e.json()),l=r[s];return l?{pubkey:l,relays:o?.[l],nip46:a?.[l]}:null}catch(e){return null}}function parseNIP05Result(e){const t={names:{}};for(const[n,r]of Object.entries(e.names))"string"==typeof n&&"string"==typeof r&&(t.names[n]=r);if(e.relays){t.relays={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.relays[n]=r.filter((e=>"string"==typeof e)))}if(e.nip46){t.nip46={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.nip46[n]=r.filter((e=>"string"==typeof e)))}return t}var NDKUser=class e{ndk;profile;_npub;_pubkey;relayUrls=[];nip46Urls=[];constructor(e){e.npub&&(this._npub=e.npub),e.hexpubkey&&(this._pubkey=e.hexpubkey),e.pubkey&&(this._pubkey=e.pubkey),e.relayUrls&&(this.relayUrls=e.relayUrls),e.nip46Urls&&(this.nip46Urls=e.nip46Urls)}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("hexpubkey not set");this._npub=nip19_exports.npubEncode(this.pubkey)}return this._npub}set npub(e){this._npub=e}get hexpubkey(){return this.pubkey}set hexpubkey(e){this._pubkey=e}get pubkey(){if(!this._pubkey){if(!this._npub)throw new Error("npub not set");this._pubkey=nip19_exports.decode(this.npub).data}return this._pubkey}set pubkey(e){this._pubkey=e}static async fromNip05(t,n,r=!1){if(n?.cacheAdapter&&n.cacheAdapter.loadNip05){const r=await n.cacheAdapter.loadNip05(t);if(r){const t=new e({pubkey:r.pubkey,relayUrls:r.relays,nip46Urls:r.nip46});return t.ndk=n,t}}let o={};r&&(o.cache="no-cache");const s=await getNip05For(t,n?.httpFetch,o);if(s&&n?.cacheAdapter&&n.cacheAdapter.saveNip05&&n?.cacheAdapter.saveNip05(t,s),s){const t=new e({pubkey:s.pubkey,relayUrls:s.relays,nip46Urls:s.nip46});return t.ndk=n,t}}async fetchProfile(e){if(!this.ndk)throw new Error("NDK not set");this.profile||(this.profile={});let t=null;if(this.ndk.cacheAdapter&&this.ndk.cacheAdapter.fetchProfile&&"ONLY_RELAY"!==e?.cacheUsage){const e=await this.ndk.cacheAdapter.fetchProfile(this.pubkey);if(e)return this.profile=e,e}!e&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.locking&&(t=await this.ndk.fetchEvents({kinds:[0],authors:[this.pubkey]},{cacheUsage:"ONLY_CACHE",closeOnEose:!0,groupable:!1}),e={cacheUsage:"ONLY_RELAY",closeOnEose:!0,groupable:!0,groupableDelay:250}),t&&0!==t.size||(t=await this.ndk.fetchEvents({kinds:[0],authors:[this.pubkey]},e));const n=Array.from(t).sort(((e,t)=>e.created_at-t.created_at));return 0===n.length?null:(this.profile=profileFromEvent(n[0]),this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile)}follows=follows.bind(this);pin=pin.bind(this);async relayList(){if(!this.ndk)throw new Error("NDK not set");const e=this.ndk.outboxPool||this.ndk.pool,t=new Set;for(const n of e.relays.values())t.add(n);const n=new NDKRelaySet(t,this.ndk),r=await this.ndk.fetchEvent({kinds:[10002],authors:[this.pubkey]},{closeOnEose:!0,pool:e,groupable:!0,subId:`relay-list-${this.pubkey.slice(0,6)}`},n);return r?NDKRelayList.from(r):await this.relayListFromKind3()}async relayListFromKind3(){if(!this.ndk)throw new Error("NDK not set");const e=await this.ndk.fetchEvent({kinds:[3],authors:[this.pubkey]});if(e)try{const t=JSON.parse(e.content),n=new NDKRelayList(this.ndk),r=new Set,o=new Set;for(const[e,n]of Object.entries(t))if(n){const t=n;t.write&&o.add(e),t.read&&r.add(e)}else r.add(e),o.add(e);return n.readRelayUrls=Array.from(r),n.writeRelayUrls=Array.from(o),n}catch(e){}}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e?(t[0].push("",e),t):t}async publish(){if(!this.ndk)throw new Error("No NDK instance found");if(!this.profile)throw new Error("No profile available");this.ndk.assertSigner();const e=new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)});await e.publish()}async follow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n)),t.has(e))return!1;t.add(e);const r=new NDKEvent(this.ndk,{kind:n});for(const e of t)r.tag(e);return await r.publish(),!0}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(e);return null===t?null:t.pubkey===this.pubkey}async zap(e,t,n,r){if(!this.ndk)throw new Error("No NDK instance found");r||this.ndk.assertSigner();const o=new Zap({ndk:this.ndk,zappedUser:this}),s=Array.from(this.ndk.pool.relays.keys());return await o.createZapRequest(e,t,n,s,r)}},NDKPrivateKeySigner=class e{_user;privateKey;constructor(e){e&&(this.privateKey=e,this._user=new NDKUser({hexpubkey:getPublicKey(this.privateKey)}))}static generate(){const t=generatePrivateKey();return new e(t)}async blockUntilReady(){if(!this._user)throw new Error("NDKUser not initialized");return this._user}async user(){return await this.blockUntilReady(),this._user}async sign(e){if(!this.privateKey)throw Error("Attempted to sign without a private key");return getSignature(e,this.privateKey)}async encrypt(e,t){if(!this.privateKey)throw Error("Attempted to encrypt without a private key");const n=e.hexpubkey;return await nip04_exports.encrypt(this.privateKey,n,t)}async decrypt(e,t){if(!this.privateKey)throw Error("Attempted to decrypt without a private key");const n=e.hexpubkey;return await nip04_exports.decrypt(this.privateKey,n,t)}},NDKNostrRpc=class extends lib$1.EventEmitter{ndk;signer;debug;constructor(e,t,n){super(),this.ndk=e,this.signer=t,this.debug=n.extend("rpc")}subscribe(e){const t=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1});return t.on("event",(async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):this.emit(`response-${t.id}`,t)}catch(t){this.debug("error parsing event",t,e.rawEvent())}})),new Promise(((e,n)=>{t.on("eose",(()=>e(t)))}))}async parseEvent(e){const t=this.ndk.getUser({hexpubkey:e.pubkey});t.ndk=this.ndk;const n=await this.signer.decrypt(t,e.content),r=JSON.parse(n),{id:o,method:s,params:i,result:a,error:l}=r;return s?{id:o,pubkey:e.pubkey,method:s,params:i,event:e}:{id:o,result:a,error:l,event:e}}async sendResponse(e,t,n,r=24133,o){const s={id:e,result:n};o&&(s.error=o);const i=await this.signer.user(),a=this.ndk.getUser({hexpubkey:t}),l=new NDKEvent(this.ndk,{kind:r,content:JSON.stringify(s),tags:[["p",t]],pubkey:i.hexpubkey});l.content=await this.signer.encrypt(a,l.content),await l.sign(this.signer),await l.publish()}async sendRequest(e,t,n=[],r=24133,o){const s=Math.random().toString(36).substring(7),i=await this.signer.user(),a=this.ndk.getUser({hexpubkey:e}),l={id:s,method:t,params:n},c=new Promise((e=>{const t=e=>{"auth_url"===e.result?(this.once(`response-${s}`,t),this.emit("authUrl",e.error)):o&&o(e)};this.once(`response-${s}`,t)})),d=new NDKEvent(this.ndk,{kind:r,content:JSON.stringify(l),tags:[["p",e]],pubkey:i.pubkey});return d.content=await this.signer.encrypt(a,d.content),await d.sign(this.signer),this.debug(`sending ${t} request to`,e),await d.publish(),c}},NDKNip46Signer=class extends lib$1.EventEmitter{ndk;remoteUser;remotePubkey;token;localSigner;nip05;rpc;debug;relayUrls=[];constructor(e,t,n){let r,o;if(super(),t.includes("#")){const e=t.split("#");r=new NDKUser({npub:e[0]}).pubkey,o=e[1]}else t.startsWith("npub")?r=new NDKUser({npub:t}).pubkey:t.match(/\./)?this.nip05=t:r=t;this.ndk=e,r&&(this.remotePubkey=r),this.token=o,this.debug=e.debug.extend("nip46:signer"),this.remoteUser=new NDKUser({pubkey:r}),this.localSigner=n||NDKPrivateKeySigner.generate(),this.rpc=new NDKNostrRpc(e,this.localSigner,this.debug),this.rpc.on("authUrl",((...e)=>{this.emit("authUrl",...e)})),this.localSigner.user().then((e=>{this.rpc.subscribe({kinds:[24133,24134],"#p":[e.pubkey]})}))}async user(){return this.remoteUser}async blockUntilReady(){const e=await this.localSigner.user(),t=this.ndk.getUser({pubkey:this.remotePubkey});if(this.nip05&&!this.remotePubkey&&NDKUser.fromNip05(this.nip05).then((e=>{e&&(this.remoteUser=e,this.remotePubkey=e.pubkey,this.relayUrls=e.nip46Urls)})),!this.remotePubkey)throw new Error("Remote pubkey not set");return new Promise(((n,r)=>{setTimeout((()=>{const o=[e.pubkey];this.token&&o.push(this.token),this.rpc.sendRequest(this.remotePubkey,"connect",o,24133,(e=>{"ack"===e.result?n(t):r(e.error)}))}),100)}))}async encrypt(e,t){this.debug("asking for encryption");return new Promise(((n,r)=>{this.rpc.sendRequest(this.remotePubkey,"nip04_encrypt",[e.pubkey,t],24133,(e=>{e.error?r(e.error):n(e.result)}))}))}async decrypt(e,t){this.debug("asking for decryption");return new Promise(((n,r)=>{this.rpc.sendRequest(this.remotePubkey,"nip04_decrypt",[e.pubkey,t],24133,(e=>{if(e.error)r(e.error);else{const t=JSON.parse(e.result);n(t[0])}}))}))}async sign(e){this.debug("asking for a signature");return new Promise(((t,n)=>{this.rpc.sendRequest(this.remotePubkey,"sign_event",[JSON.stringify(e)],24133,(e=>{if(this.debug("got a response",e),e.error)n(e.error);else{const n=JSON.parse(e.result);t(n.sig)}}))}))}async createAccount(e,t,n){this.debug("asking to create an account");const r=[];return e&&r.push(e),t&&r.push(t),n&&r.push(n),new Promise(((e,t)=>{this.rpc.sendRequest(this.remotePubkey,"create_account",r,24134,(n=>{if(this.debug("got a response",n),n.error)t(n.error);else{const t=n.result;e(t)}}))}))}};function dedup(e,t){return e.created_at>t.created_at?e:t}var OutboxItem=class{type;relayUrlScores;readRelays;writeRelays;constructor(e){this.type=e,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{data;ndk;debug;constructor(e){super(),this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:5e3})}trackUsers(e){for(const t of e){const e=getKeyFromItem(t);if(this.data.has(e))continue;const n=this.track(t,"user"),r=t instanceof NDKUser?t:new NDKUser({hexpubkey:t});r.ndk=this.ndk,r.relayList().then((t=>{if(t){n.readRelays=new Set(t.readRelayUrls),n.writeRelays=new Set(t.writeRelayUrls);for(const e of n.readRelays)this.ndk.pool.blacklistRelayUrls.has(e)&&(this.debug(`removing blacklisted relay ${e} from read relays`),n.readRelays.delete(e));for(const e of n.writeRelays)this.ndk.pool.blacklistRelayUrls.has(e)&&(this.debug(`removing blacklisted relay ${e} from write relays`),n.writeRelays.delete(e));this.data.set(e,n),this.debug(`Adding ${n.readRelays.size} read relays and ${n.writeRelays.size} write relays for ${r.hexpubkey}`)}}))}}track(e,t){const n=getKeyFromItem(e);t??=getTypeFromItem(e);let r=this.data.get(n);return r||(r=new OutboxItem(t)),this.data.set(n,r),r}};function getKeyFromItem(e){return e instanceof NDKUser?e.hexpubkey:e}function getTypeFromItem(e){return e instanceof NDKUser?"user":"kind"}var NDKPool=class extends lib$1.EventEmitter{relays=new Map;blacklistRelayUrls;debug;temporaryRelayTimers=new Map;flappingRelays=new Set;backoffTimes=new Map;constructor(e=[],t=[],n,r){super(),this.debug=r??n.debug.extend("pool");for(const t of e){const e=new NDKRelay(t);this.addRelay(e,!1)}this.blacklistRelayUrls=new Set(t)}useTemporaryRelay(e,t=6e5){const n=this.relays.has(e.url);n||this.addRelay(e);const r=this.temporaryRelayTimers.get(e.url);if(r&&clearTimeout(r),!n||r){const n=setTimeout((()=>{this.removeRelay(e.url)}),t);this.temporaryRelayTimers.set(e.url,n)}}addRelay(e,t=!0){const n=e.url;this.blacklistRelayUrls?.has(n)?this.debug(`Relay ${n} is blacklisted`):(e.on("notice",(async(e,t)=>this.emit("notice",e,t))),e.on("connect",(()=>this.handleRelayConnect(n))),e.on("ready",(()=>this.handleRelayReady(e))),e.on("disconnect",(async()=>this.emit("relay:disconnect",e))),e.on("flapping",(()=>this.handleFlapping(e))),e.on("auth",(async t=>this.emit("relay:auth",e,t))),this.relays.set(n,e),t&&e.connect().catch((e=>{this.debug(`Failed to connect to relay ${n}`,e)})))}removeRelay(e){const t=this.relays.get(e);if(t)return t.disconnect(),this.relays.delete(e),this.emit("relay:disconnect",t),!0;const n=this.temporaryRelayTimers.get(e);return n&&(clearTimeout(n),this.temporaryRelayTimers.delete(e)),!1}getRelay(e,t=!0){let n=this.relays.get(e);return n||(n=new NDKRelay(e),this.addRelay(n,t)),n}handleRelayConnect(e){this.debug(`Relay ${e} connected`),this.emit("relay:connect",this.relays.get(e)),this.stats().connected===this.relays.size&&this.emit("connect")}handleRelayReady(e){this.debug(`Relay ${e.url} ready`),this.emit("relay:ready",e)}async connect(e){const t=[];this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}...`:""}`);for(const n of this.relays.values())if(e){const r=new Promise(((t,n)=>{setTimeout((()=>n(`Timed out after ${e}ms`)),e)}));t.push(Promise.race([n.connect(),r]).catch((e=>{this.debug(`Failed to connect to relay ${n.url}: ${e??"No reason specified"}`)})))}else t.push(n.connect());e&&setTimeout((()=>{const e=this.stats().connected===this.relays.size,t=this.stats().connected>0;!e&&t&&this.emit("connect")}),e),await Promise.all(t)}checkOnFlappingRelays(){if(this.flappingRelays.size/this.relays.size>=.8)for(const e of this.flappingRelays)this.backoffTimes.set(e,0)}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t*=2,this.backoffTimes.set(e.url,t),this.debug(`Backoff time for ${e.url} is ${t}ms`),setTimeout((()=>{this.debug(`Attempting to reconnect to ${e.url}`),e.connect(),this.checkOnFlappingRelays()}),t),e.disconnect(),this.emit("flapping",e)}size(){return this.relays.size}stats(){const e={total:0,connected:0,disconnected:0,connecting:0};for(const t of this.relays.values())e.total++,1===t.status?e.connected++:3===t.status?e.disconnected++:0===t.status&&e.connecting++;return e}connectedRelays(){return Array.from(this.relays.values()).filter((e=>1===e.status))}urls(){return Array.from(this.relays.keys())}};function correctRelaySet(e,t){const n=t.connectedRelays();if(!Array.from(e.relays).some((e=>n.map((e=>e.url)).includes(e.url))))for(const t of n)e.addRelay(t);if(0===n.length)for(const n of t.relays.values())e.addRelay(n);return e}var SPEC_PATH="/.well-known/nostr/nip96.json",Nip96=class{ndk;spec;url;nip98Required=!1;constructor(e,t){this.url=`https://${e}${SPEC_PATH}`,this.ndk=t}async prepareUpload(e,t="POST"){if(this.validateHttpFetch(),this.spec||await this.fetchSpec(),!this.spec)throw new Error("Failed to fetch NIP96 spec");let n={};if(this.nip98Required){n={Authorization:await this.generateNip98Header(this.spec.api_url,t,e)}}return{url:this.spec.api_url,headers:n}}async xhrUpload(e,t){const n="POST",{url:r,headers:o}=await this.prepareUpload(t,n);e.open(n,r,!0),o.Authorization&&e.setRequestHeader("Authorization",o.Authorization);const s=new FormData;return s.append("file",t),new Promise(((t,n)=>{e.onload=function(){e.status>=200&&e.status<300?t(JSON.parse(e.responseText)):n(new Error(e.statusText))},e.onerror=function(){n(new Error("Network Error"))},e.send(s)}))}async upload(e){const t="POST",{url:n,headers:r}=await this.prepareUpload(e,t),o=new FormData;o.append("file",e);const s=await this.ndk.httpFetch(this.spec.api_url,{method:t,headers:r,body:o});if(200!==s.status)throw new Error(`Failed to upload file to ${n}`);const i=await s.json();if("success"!==i.status)throw new Error(i.message);return i}validateHttpFetch(){if(!this.ndk)throw new Error("NDK is required to fetch NIP96 spec");if(!this.ndk.httpFetch)throw new Error("NDK must have an httpFetch method to fetch NIP96 spec")}async fetchSpec(){this.validateHttpFetch();const e=await this.ndk.httpFetch(this.url);if(200!==e.status)throw new Error(`Failed to fetch NIP96 spec from ${this.url}`);const t=await e.json();if(!t)throw new Error(`Failed to parse NIP96 spec from ${this.url}`);this.spec=t,this.nip98Required=this.spec.plans.free.is_nip98_required}async generateNip98Header(e,t,n){const r=new NDKEvent(this.ndk,{kind:27235,tags:[["u",e],["method",t]]});if(["POST","PUT","PATCH"].includes(t)){const e=await this.calculateSha256(n);r.tags.push(["payload",e])}await r.sign();return`Nostr ${btoa(JSON.stringify(r.rawEvent()))}`}async calculateSha256(e){const t=await e.arrayBuffer(),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}},DEFAULT_OUTBOX_RELAYS=["wss://purplepag.es","wss://relay.snort.social"],DEFAULT_BLACKLISTED_RELAYS=["wss://brb.io"],NDK=class extends lib$1.EventEmitter{explicitRelayUrls;pool;outboxPool;_signer;_activeUser;cacheAdapter;debug;devWriteRelaySet;outboxTracker;mutedIds;clientName;clientNip89;relayAuthDefaultPolicy;httpFetch;autoConnectUserRelays=!0;autoFetchUserMutelist=!0;constructor(e={}){super(),this.debug=e.debug||debug3("ndk"),this.explicitRelayUrls=e.explicitRelayUrls||[],this.pool=new NDKPool(e.explicitRelayUrls||[],e.blacklistRelayUrls,this),this.debug(`Starting with explicit relays: ${JSON.stringify(this.explicitRelayUrls)}`),this.pool.on("relay:auth",(async(e,t)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(e,t)})),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.autoFetchUserMutelist=e.autoFetchUserMutelist??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,e.enableOutboxModel&&(this.outboxPool=new NDKPool(e.outboxRelayUrls||DEFAULT_OUTBOX_RELAYS,e.blacklistRelayUrls||DEFAULT_BLACKLISTED_RELAYS,this,this.debug.extend("outbox-pool")),this.outboxTracker=new OutboxTracker(this)),this.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.mutedIds=e.mutedIds||new Map,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this));try{this.httpFetch=fetch}catch{}}addExplicitRelay(e,t,n=!0){let r;return r="string"==typeof e?new NDKRelay(e,t):e,this.pool.addRelay(r,n),this.explicitRelayUrls.push(r.url),r}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){const t=this._activeUser?.pubkey!==e?.pubkey;if(this._activeUser=e,e&&t){const t=async e=>{const t=await e.relayList();if(t){this.debug("Connecting to user relays",{npub:e.npub,relays:t.relays});for(const e of t.relays){let t=this.pool.relays.get(e);t||(t=new NDKRelay(e),this.pool.addRelay(t))}}else this.debug("No relay list found for user",{npub:e.npub})},n=async e=>{const t=await this.fetchEvents([{kinds:[1e4],authors:[e.pubkey]},{kinds:[3e4],authors:[e.pubkey],"#d":["mute"],limit:1}]);if(t)for(const e of t){const t=lists_default.from(e);for(const e of t.items)this.mutedIds.set(e[1],e[0])}else this.debug("No mute list found for user",{npub:e.npub})},r=[];this.autoConnectUserRelays&&r.push(t),this.autoFetchUserMutelist&&r.push(n);const o=async e=>{for(const t of r)await t(e)},s=this.outboxPool||this.pool;s.connectedRelays.length>0?o(e):(this.debug("Waiting for connection to main relays"),s.once("relay:ready",(t=>{this.debug("New relay ready",t?.url),o(e)})))}else e||(this.mutedIds=new Map)}get signer(){return this._signer}set signer(e){this._signer=e,this.emit("signer:ready",e),e?.user().then((e=>{e.ndk=this,this.activeUser=e}))}async connect(e){if(this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer"),this._signer.relays)){(await this._signer.relays()).forEach((e=>this.pool.addRelay(e)))}const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),this.debug("Connecting to relays",{timeoutMs:e}),Promise.allSettled(t).then((()=>{}))}getUser(e){const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}subscribe(e,t,n,r=!0){const o=new NDKSubscription(this,e,t,n);if(n)for(const e of n.relays)this.pool.useTemporaryRelay(e);if(this.outboxPool&&o.hasAuthorsFilter()){const e=o.filters.filter((e=>e.authors&&e.authors?.length>0)).map((e=>e.authors)).flat();this.outboxTracker?.trackUsers(e)}return r&&o.start(),o}async publish(e,t,n){return this.debug("Deprecated: Use `event.publish()` instead"),e.publish(t,n)}async fetchEvent(e,t,n){let r,o;if(n instanceof NDKRelay?o=new NDKRelaySet(new Set([n]),this):n instanceof NDKRelaySet&&(o=n),!n&&"string"==typeof e&&!isNip33AValue(e)){const t=relaysFromBech32(e);t.length>0&&(o=new NDKRelaySet(new Set(t),this),o=correctRelaySet(o,this.pool))}if(r="string"==typeof e?filterFromId(e):e,!r)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise((e=>{const n=this.subscribe(r,{...t||{},closeOnEose:!0},o,!1);n.on("event",(t=>{t.ndk=this,e(t)})),n.on("eose",(()=>{e(null)})),n.start()}))}async fetchEvents(e,t,n){return new Promise((r=>{const o=new Map,s=this.subscribe(e,{...t||{},closeOnEose:!0},n,!1),i=e=>{const t=e.deduplicationKey(),n=o.get(t);n&&(e=dedup(n,e)),e.ndk=this,o.set(t,e)};s.on("event",i),s.on("event:dup",i),s.on("eose",(()=>{r(new Set(o.values()))})),s.start()}))}assertSigner(){if(!this.signer)throw this.emit("signerRequired"),new Error("Signer required")}getNip96(e){return new Nip96(e,this)}};const LOCAL_STORE_KEY="__nostrlogin_nip46",LOGGED_IN_ACCOUNTS="__nostrlogin_accounts",RECENT_ACCOUNTS="__nostrlogin_recent",OUTBOX_RELAYS$1=["wss://purplepag.es","wss://relay.nos.social","wss://user.kindpag.es","wss://relay.damus.io","wss://nos.lol"],DEFAULT_SIGNUP_RELAYS=["wss://relay.damus.io/","wss://nos.lol/","wss://relay.primal.net/"],localStorageSetItem=(e,t)=>{localStorage.setItem(e,t)},localStorageGetItem=e=>{const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch{}return null},localStorageRemoveItem=e=>{localStorage.removeItem(e)},fetchProfile=async(e,t)=>{const n=new NDKUser({pubkey:e.pubkey});return n.ndk=t,await n.fetchProfile()},prepareSignupRelays=e=>{const t=(e||"").split(",").map((e=>e.trim())).filter((e=>e.startsWith("ws")));return t.length||t.push(...DEFAULT_SIGNUP_RELAYS),t},createProfile=async(e,t,n,r,o)=>{const s={name:e.name},i=new NDKEvent(t,{kind:0,created_at:Math.floor(Date.now()/1e3),pubkey:e.pubkey,content:JSON.stringify(s),tags:[]});window.location.hostname&&i.tags.push(["client",window.location.hostname]);const a=new NDKEvent(t,{kind:10002,created_at:Math.floor(Date.now()/1e3),pubkey:e.pubkey,content:"",tags:[]}),l=prepareSignupRelays(r);for(const e of l)a.tags.push(["r",e]);await i.sign(n),console.log("signed profile",i),await a.sign(n),console.log("signed relays",a);const c=o&&o.length?o:OUTBOX_RELAYS$1;await i.publish(NDKRelaySet.fromRelayUrls(c,t)),console.log("published profile",i),await a.publish(NDKRelaySet.fromRelayUrls(c,t)),console.log("published relays",a)},bunkerUrlToInfo=(e,t="")=>{const n=new URL(e);return{pubkey:"",signerPubkey:n.hostname||n.pathname.split("//")[1],sk:t||generatePrivateKey(),relays:n.searchParams.getAll("relay"),token:n.searchParams.get("secret")||"",authMethod:"connect"}},isBunkerUrl=e=>e.startsWith("bunker://"),getBunkerUrl=async(e,t)=>{if(!e)return"";if(isBunkerUrl(e))return e;if(e.includes("@")){const[n,r]=e.toLocaleLowerCase().split("@"),o=t.devOverrideBunkerOrigin||`https://${r}`,s=`${o}/.well-known/nostr.json?name=_`,i=`${o}/.well-known/nostr.json?name=${n}`,a=await fetch(s),l=await a.json(),c=l.names._,d=l.nip46[c],h=await fetch(i),u=(await h.json()).names[n];if(!d||0===d.length)throw new Error("Bunker relay not provided");return`bunker://${u}?${d.map((e=>`relay=${encodeURIComponent(e)}`)).join("&")}`}throw new Error("Invalid user name or bunker url")},checkNip05=async e=>{let t=!1,n="",r="";return await(async()=>{if(!e||!e.includes("@"))return;const[o,s]=e.toLocaleLowerCase().split("@");if(!o)return;if(!new RegExp(/^[\w-.]+@([\w-]+\.)+[\w-]{2,8}$/g).test(e))return void(n="Invalid name");if(!s)return void(n="Select service");const i=`https://${s}/.well-known/nostr.json?name=${o.toLowerCase()}`;try{const e=await fetch(i),t=await e.json();if(t.names[o])return void(r=t.names[o])}catch{}t=!0})(),{available:t,taken:""!=r,error:n,pubkey:r}},upgradeInfo=e=>{"typeAuthMethod"in e&&delete e.typeAuthMethod,e.authMethod||("extension"in e&&e.extension?e.authMethod="extension":"readOnly"in e&&e.readOnly?e.authMethod="readOnly":e.authMethod="connect"),e.nip05&&isBunkerUrl(e.nip05)&&(e.bunkerUrl=e.nip05,e.nip05=""),"connect"!==e.authMethod||e.signerPubkey||(e.signerPubkey=e.pubkey)},localStorageAddAccount=e=>{localStorageSetItem(LOCAL_STORE_KEY,JSON.stringify(e));const t=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[],n=localStorageGetItem(RECENT_ACCOUNTS)||[];t.forEach((e=>upgradeInfo(e))),n.forEach((e=>upgradeInfo(e)));const r=t,o=t.findIndex((t=>t.pubkey===e.pubkey&&t.authMethod===e.authMethod));-1!==o?r[o]=e:r.push(e);const s=n.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(s)),localStorageSetItem(LOGGED_IN_ACCOUNTS,JSON.stringify(r))},localStorageRemoveCurrentAccount=()=>{const e=localStorageGetItem(LOCAL_STORE_KEY);if(!e)return;upgradeInfo(e);const t={...e};delete t.sk,delete t.otpData;const n=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[],r=localStorageGetItem(RECENT_ACCOUNTS)||[];n.forEach((e=>upgradeInfo(e))),r.forEach((e=>upgradeInfo(e)));const o=r;if("connect"===t.authMethod&&t.bunkerUrl&&t.bunkerUrl.includes("secret="))console.log("nostr login bunker conn with a secret not saved to recent");else if("local"===t.authMethod)console.log("nostr login temporary local keys not save to recent");else{const e=r.findIndex((e=>e.pubkey===t.pubkey&&e.authMethod===t.authMethod));-1!==e?o[e]=t:o.push(t)}const s=n.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(o)),localStorageSetItem(LOGGED_IN_ACCOUNTS,JSON.stringify(s)),localStorageRemoveItem(LOCAL_STORE_KEY)},localStorageRemoveRecent=e=>{const t=localStorageGetItem(RECENT_ACCOUNTS)||[];t.forEach((e=>upgradeInfo(e)));const n=t.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(n))},localStorageGetRecents=()=>{const e=localStorageGetItem(RECENT_ACCOUNTS)||[];return e.forEach((e=>upgradeInfo(e))),e},localStorageGetAccounts=()=>{const e=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[];return e.forEach((e=>upgradeInfo(e))),e},localStorageGetCurrent=()=>{const e=localStorageGetItem(LOCAL_STORE_KEY);return e&&upgradeInfo(e),e},getDarkMode=e=>{const t=localStorage.getItem("nl-dark-mode");return t?Boolean(JSON.parse(t)):void 0!==e.darkMode?e.darkMode:!(!window.matchMedia||!window.matchMedia("(prefers-color-scheme: dark)").matches)},getIcon=async()=>document.location.origin+"/favicon.ico";class NostrRpc extends NDKNostrRpc{_ndk;_signer;requests=new Set;sub;_useNip44=!1;constructor(e,t){super(e,t,e.debug.extend("nip46:signer:rpc")),this._ndk=e,this._signer=t}async subscribe(e){return e.kinds=e.kinds?.filter((e=>24133===e)),this.sub=await super.subscribe(e),this.sub}stop(){this.sub&&(this.sub.stop(),this.sub=void 0)}setUseNip44(e){this._useNip44=e}isNip04(e){const t=e.length;return!(t<28)&&("?"===e[t-28]&&"i"===e[t-27]&&"v"===e[t-26]&&"="===e[t-25])}async parseEvent(e){const t=this._ndk.getUser({pubkey:e.pubkey});t.ndk=this._ndk;const n=this.isNip04(e.content)?this._signer.decrypt:this._signer.decryptNip44,r=await n.call(this._signer,t,e.content),o=JSON.parse(r),{id:s,method:i,params:a,result:l,error:c}=o;return i?{id:s,pubkey:e.pubkey,method:i,params:a,event:e}:{id:s,result:l,error:c,event:e}}async parseNostrConnectReply(e,t){const n=new NDKEvent(this._ndk,e),r=await this.parseEvent(n);if(console.log("nostr connect parsedEvent",r),r.method)throw new Error("Bad nostr connect reply");{const e=r;if(e.result!==t)throw new Error(e.error);return n.pubkey}}async listen(e){const t=this._signer.pubkey;console.log("nostr-login listening for conn to",t);const n=await this.subscribe({kinds:[24133],"#p":[t]});return new Promise(((t,r)=>{n.on("event",(async n=>{try{const o=await this.parseEvent(n);if(!o.method){const s=o;if("auth_url"===s.result)return;"ack"===s.result||s.result===e?t(n.pubkey):r(s.error)}}catch(e){console.log("error parsing event",e,n.rawEvent())}this.stop()}))}))}async connect(e,t,n){return new Promise(((r,o)=>{const s=[e,t||"",n||""];this.sendRequest(e,"connect",s,24133,(e=>{"ack"===e.result?r():o(e.error)}))}))}getId(){return Math.random().toString(36).substring(7)}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId();this.setResponseHandler(s,o);const i=await this.createRequestEvent(s,e,t,n,r);console.log("sendRequest",{event:i,method:t,remotePubkey:e,params:n}),await i.publish()}setResponseHandler(e,t){let n=!1;const r=Date.now();return new Promise((()=>{const o=s=>{"auth_url"===s.result?(this.once(`response-${e}`,o),n||(n=!0,this.emit("authUrl",s.error))):t&&this.requests.has(e)&&(this.requests.delete(e),console.log("nostr-login processed nip46 request in",Date.now()-r,"ms"),t(s))};this.once(`response-${e}`,o)}))}async createRequestEvent(e,t,n,r=[],o=24133){this.requests.add(e);const s=await this._signer.user(),i=this._ndk.getUser({pubkey:t}),a={id:e,method:n,params:r},l=new NDKEvent(this._ndk,{kind:o,content:JSON.stringify(a),tags:[["p",t]],pubkey:s.pubkey}),c=this._useNip44&&"create_account"!==n?this._signer.encryptNip44:this._signer.encrypt;return l.content=await c.call(this._signer,i,l.content),await l.sign(this._signer),l}}class IframeNostrRpc extends NostrRpc{peerOrigin;iframePort;iframeRequests=new Map;constructor(e,t,n){super(e,t),this._ndk=e,this.peerOrigin=n}async subscribe(e){return this.peerOrigin?new NDKSubscription(this._ndk,{},{closeOnEose:!0,cacheUsage:NDKSubscriptionCacheUsage.ONLY_CACHE}):super.subscribe(e)}setWorkerIframePort(e){if(!this.peerOrigin)throw new Error("Unexpected iframe port");this.iframePort=e,setInterval((()=>{console.log("iframe-nip46 ping"),this.iframePort.postMessage("ping")}),5e3),e.onmessage=async e=>{if(console.log("iframe-nip46 got response",e.data),"string"==typeof e.data&&e.data.startsWith("errorNoKey")){const t=e.data.split(":")[1],{id:n="",pubkey:r=""}=this.iframeRequests.get(t)||{};n&&r&&this.requests.has(n)&&this.emit(`iframeRestart-${r}`)}else try{const t=e.data;if(!validateEvent(t))throw new Error("Invalid event from iframe");if(!verifySignature(t))throw new Error("Invalid event signature from iframe");const n=new NDKEvent(this._ndk,t),r=await this.parseEvent(n);r.method||(console.log("parsed response",r),this.emit(`response-${r.id}`,r))}catch(t){console.log("error parsing event",t,e.data)}}}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId(),i=await this.createRequestEvent(s,e,t,n,r);this.setResponseHandler(s,o),this.iframePort?(this.iframeRequests.set(i.id,{id:s,pubkey:e}),console.log("iframe-nip46 sending request to",this.peerOrigin,i.rawEvent()),this.iframePort.postMessage(i.rawEvent())):await i.publish()}}class ReadyListener{origin;messages;promise;constructor(e,t){this.origin=t,this.messages=e,this.promise=new Promise((e=>{console.log(new Date,"started listener for",this.messages);const n=async r=>{const o=new URL(t).hostname,s=new URL(r.origin).hostname;(s===o||s.endsWith("."+o))&&Array.isArray(r.data)&&r.data.length&&this.messages.includes(r.data[0])&&(console.log(new Date,"got ready message from",r.origin,r.data),window.removeEventListener("message",n),e(r.data))};window.addEventListener("message",n)}))}async wait(){console.log(new Date,"waiting for",this.messages);const e=await this.promise;return console.log(new Date,"finished waiting for",this.messages,e),e}}class Nip46Signer extends NDKNip46Signer{_userPubkey="";_rpc;constructor(e,t,n,r){super(e,n,t),this._rpc=new IframeNostrRpc(e,t,r),this._rpc.setUseNip44(!0),this._rpc.on("authUrl",(e=>{this.emit("authUrl",e)})),this.rpc=this._rpc}get userPubkey(){return this._userPubkey}async setSignerPubkey(e,t=!1){console.log("setSignerPubkey",e),this.remotePubkey=e,this._rpc.on(`iframeRestart-${e}`,(()=>{this.emit("iframeRestart")})),await this.initUserPubkey(t?e:"")}async initUserPubkey(e){if(this._userPubkey)throw new Error("Already called initUserPubkey");this._userPubkey=e||await new Promise(((e,t)=>{if(!this.remotePubkey)throw new Error("Signer pubkey not set");console.log("get_public_key",this.remotePubkey),this._rpc.sendRequest(this.remotePubkey,"get_public_key",[],24133,(t=>{e(t.result)}))}))}async listen(e){const t=await this.rpc.listen(e);await this.setSignerPubkey(t)}async connect(e,t){if(!this.remotePubkey)throw new Error("No signer pubkey");await this._rpc.connect(this.remotePubkey,e,t),await this.setSignerPubkey(this.remotePubkey)}async setListenReply(e,t){const n=await this._rpc.parseNostrConnectReply(e,t);await this.setSignerPubkey(n,!0)}async createAccount2({bunkerPubkey:e,name:t,domain:n,perms:r=""}){const o=[t,n,"",r],s=await new Promise((t=>{this.rpc.sendRequest(e,"create_account",o,void 0,t)}));if(console.log("create_account pubkey",s),"error"===s.result)throw new Error(s.error);return s.result}}class BannerManager extends lib$1.EventEmitter{banner=null;iframeReady;params;constructor(e){super(),this.params=e}onAuthUrl(e,t){this.banner&&(this.banner.notify=e?{mode:t?"iframeAuthUrl":"authUrl",url:e}:{mode:""})}onIframeRestart(e){this.banner&&(this.iframeReady=new ReadyListener(["rebinderDone","rebinderError"],new URL(e).origin),this.banner.notify={mode:"rebind",url:e})}onUserInfo(e){this.banner&&(this.banner.userInfo=e)}onCallTimeout(){this.banner&&(this.banner.notify={mode:"timeout"})}onCallStart(){this.banner&&(this.banner.isLoading=!0)}async onCallEnd(){this.banner&&(this.iframeReady&&(await this.iframeReady.wait(),this.iframeReady=void 0),this.banner.isLoading=!1,this.banner.notify={mode:""})}onUpdateAccounts(e){this.banner&&(this.banner.accounts=e)}onDarkMode(e){this.banner&&(this.banner.darkMode=e)}launchAuthBanner(e){this.banner=document.createElement("nl-banner"),this.banner.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.banner.setAttribute("theme",e.theme),e.noBanner&&this.banner.setAttribute("hidden-mode","true"),this.banner.addEventListener("handleLoginBanner",(e=>{this.emit("launch",e.detail)})),this.banner.addEventListener("handleConfirmLogout",(()=>{this.emit("onConfirmLogout")})),this.banner.addEventListener("handleLogoutBanner",(async()=>{this.emit("logout")})),this.banner.addEventListener("handleImportModal",(e=>{this.emit("import")})),this.banner.addEventListener("handleNotifyConfirmBanner",(e=>{this.emit("onAuthUrlClick",e.detail)})),this.banner.addEventListener("handleNotifyConfirmBannerIframe",(e=>{this.emit("onIframeAuthUrlClick",e.detail)})),this.banner.addEventListener("handleSwitchAccount",(e=>{this.emit("onSwitchAccount",e.detail)})),this.banner.addEventListener("handleOpenWelcomeModal",(()=>{this.emit("launch"),this.banner&&(this.banner.isOpen=!1)})),document.body.appendChild(this.banner)}}function extract(e,t,n){return hash$1(e),hmac$1(e,toBytes$1(n),toBytes$1(t))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,n,r=32){if(hash$1(e),number$1(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/e.outputLen);void 0===n&&(n=EMPTY_BUFFER);const s=new Uint8Array(o*e.outputLen),i=hmac$1.create(e,t),a=i._cloneInto(),l=new Uint8Array(i.outputLen);for(let t=0;t<o;t++)HKDF_COUNTER[0]=t+1,a.update(0===t?EMPTY_BUFFER:l).update(n).update(HKDF_COUNTER).digestInto(l),s.set(l,e.outputLen*t),i._cloneInto(a);return i.destroy(),a.destroy(),l.fill(0),HKDF_COUNTER.fill(0),s.slice(0,r)}const decoder=new TextDecoder,u={minPlaintextSize:1,maxPlaintextSize:65535,utf8Encode:utf8ToBytes$1,utf8Decode:e=>decoder.decode(e),getConversationKey(e,t){const n=secp256k1.getSharedSecret(e,"02"+t).subarray(1,33);return extract(sha256,n,"nip44-v2")},getMessageKeys(e,t){const n=expand(sha256,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}},calcPaddedLen(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)},writeU16BE(e){if(!Number.isSafeInteger(e)||e<u.minPlaintextSize||e>u.maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t},pad(e){const t=u.utf8Encode(e),n=t.length;return concatBytes(u.writeU16BE(n),t,new Uint8Array(u.calcPaddedLen(n)-n))},unpad(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<u.minPlaintextSize||t>u.maxPlaintextSize||n.length!==t||e.length!==2+u.calcPaddedLen(t))throw new Error("invalid padding");return u.utf8Decode(n)},hmacAad(e,t,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const r=concatBytes(n,t);return hmac$1(sha256,e,r)},decodePayload(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let n;try{n=base64.decode(e)}catch(e){throw new Error("invalid base64: "+e.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const o=n[0];if(2!==o)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}};function encryptNip44(e,t,n=randomBytes(32)){const{chacha_key:r,chacha_nonce:o,hmac_key:s}=u.getMessageKeys(t,n),i=u.pad(e),a=chacha20(r,o,i),l=u.hmacAad(s,a,n);return base64.encode(concatBytes(new Uint8Array([2]),n,a,l))}function decryptNip44(e,t){const{nonce:n,ciphertext:r,mac:o}=u.decodePayload(e),{chacha_key:s,chacha_nonce:i,hmac_key:a}=u.getMessageKeys(t,n);if(!equalBytes(u.hmacAad(a,r,n),o))throw new Error("invalid MAC");const l=chacha20(s,i,r);return u.unpad(l)}class Nip44{cache=new Map;createKey(e,t){return u.getConversationKey(e,t)}getKey(e,t,n){const r=getPublicKey(e)+t;let o=this.cache.get(r);if(o)return o;const s=this.createKey(e,t);return this.cache.set(r,s),s}encrypt(e,t,n){return encryptNip44(n,this.getKey(e,t))}decrypt(e,t,n){return decryptNip44(n,this.getKey(e,t))}}class PrivateKeySigner extends NDKPrivateKeySigner{nip44=new Nip44;_pubkey;constructor(e){super(e),this._pubkey=getPublicKey(e)}get pubkey(){return this._pubkey}encryptNip44(e,t){return Promise.resolve(this.nip44.encrypt(this.privateKey,e.pubkey,t))}decryptNip44(e,t){return Promise.resolve(this.nip44.decrypt(this.privateKey,e.pubkey,t))}}const OUTBOX_RELAYS=["wss://user.kindpag.es","wss://purplepag.es","wss://relay.nos.social"],DEFAULT_NOSTRCONNECT_RELAYS=["wss://relay.nsec.app/","wss://ephemeral.snowflare.cc/"],CONNECT_TIMEOUT=5e3,NOSTRCONNECT_APPS=[{name:"Nsec.app",domain:"nsec.app",canImport:!0,img:"https://nsec.app/assets/favicon.ico",link:"https://use.nsec.app/<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS},{name:"Amber",img:"https://raw.githubusercontent.com/greenart7c3/Amber/refs/heads/master/assets/android-icon.svg",link:"<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS},{name:"Other key stores",img:"",link:"<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS}];class AuthNostrService extends lib$1.EventEmitter{ndk;profileNdk;signer=null;localSigner=null;params;signerPromise;signerErrCallback;readyPromise;readyCallback;nip44Codec=new Nip44;nostrConnectKey="";nostrConnectSecret="";iframe;starterReady;nip04;nip44;constructor(e){super(),this.params=e,this.ndk=new NDK({enableOutboxModel:!1}),this.profileNdk=new NDK({enableOutboxModel:!0,explicitRelayUrls:OUTBOX_RELAYS}),this.profileNdk.connect(CONNECT_TIMEOUT),this.nip04={encrypt:this.encrypt04.bind(this),decrypt:this.decrypt04.bind(this)},this.nip44={encrypt:this.encrypt44.bind(this),decrypt:this.decrypt44.bind(this)}}isIframe(){return!!this.iframe}async waitReady(){if(this.signerPromise)try{await this.signerPromise}catch{}if(this.readyPromise)try{await this.readyPromise}catch{}}cancelNostrConnect(){this.releaseSigner(),this.resetAuth()}async nostrConnect(e,{domain:t="",link:n="",iframeUrl:r="",importConnect:o=!1}={}){e=e&&e.length>0?e:DEFAULT_NOSTRCONNECT_RELAYS;const s={authMethod:"connect",pubkey:"",signerPubkey:"",sk:this.nostrConnectKey,domain:t,relays:e,iframeUrl:r};if(console.log("nostrconnect info",s,n),n&&!r&&window.open(n,"_blank","width=400,height=700"),await this.initSigner(s,{listen:!0}),!s.pubkey||!s.signerPubkey)throw new Error("Bad remote pubkey");return s.bunkerUrl=`bunker://${s.signerPubkey}?${e.map(((e,t)=>`${0!==t?"&":""}relay=${e}`))}`,o||this.onAuth("login",s),s}async createNostrConnect(e){this.nostrConnectKey=generatePrivateKey(),this.nostrConnectSecret=Math.random().toString(36).substring(7);const t=getPublicKey(this.nostrConnectKey),n=encodeURIComponent(document.location.host),r=encodeURIComponent(document.location.origin);return`nostrconnect://${t}?image=${encodeURIComponent(await getIcon())}&url=${r}&name=${n}&perms=${encodeURIComponent(this.params.optionsModal.perms||"")}&secret=${this.nostrConnectSecret}${(e||[]).length>0?(e||[]).map(((e,t)=>`&relay=${e}`)):""}`}async getNostrConnectServices(){const e=await this.createNostrConnect(),t=NOSTRCONNECT_APPS.map((e=>({...e})));for(const n of t){let t=[...DEFAULT_NOSTRCONNECT_RELAYS];if(n.link.startsWith("https://")){const e=n.domain||new URL(n.link).hostname;try{const r=await(await fetch(`https://${e}/.well-known/nostr.json`)).json(),o=r.names._,s=r.nip46?.[o];Array.isArray(s)&&s.length>0&&(t=s),n.iframeUrl=r.nip46?.iframe_url||""}catch(e){console.log("Bad app info",e,n)}}const r=e+t.map((e=>e.replace(/['"]/g,""))).map((e=>`&relay=${encodeURIComponent(e)}`)).join("");n.iframeUrl?n.link=r:n.link=n.link.replace("<nostrconnect>",r)}return[e,t]}async localSignup(e,t){const n=!t,r={pubkey:getPublicKey(t=t||generatePrivateKey()),sk:t,name:e,authMethod:"local"};console.log(`localSignup name: ${e}`),await this.setLocal(r,n)}async setLocal(e,t){this.releaseSigner(),this.localSigner=new PrivateKeySigner(e.sk),t&&await createProfile(e,this.profileNdk,this.localSigner,this.params.optionsModal.signupRelays,this.params.optionsModal.outboxRelays),this.onAuth(t?"signup":"login",e)}prepareImportUrl(e){if("otp"===this.params.userInfo?.authMethod)return e+"&import=true";if(!this.localSigner||"local"!==this.params.userInfo?.authMethod)throw new Error("Most be local keys");return e+"#import="+nip19_exports.nsecEncode(this.localSigner.privateKey)}async importAndConnect(e){const{relays:t,domain:n,link:r,iframeUrl:o}=e;if(!n)throw new Error("Domain required");const s=await this.nostrConnect(t,{domain:n,link:r,importConnect:!0,iframeUrl:o});await this.logout(!0),this.localSigner=null,this.onAuth("login",s)}setReadOnly(e){const t={pubkey:e,authMethod:"readOnly"};this.onAuth("login",t)}setExtension(e){const t={pubkey:e,authMethod:"extension"};this.onAuth("login",t)}setOTP(e,t){const n={pubkey:e,authMethod:"otp",otpData:t};this.onAuth("login",n)}async setConnect(e){this.releaseSigner(),await this.startAuth(),await this.initSigner(e),this.onAuth("login",e),await this.endAuth()}async createAccount(e){const[t,n]=e.split("@"),r=await getBunkerUrl(`_@${n}`,this.params.optionsModal);console.log("create account bunker's url",r);const o=bunkerUrlToInfo(r);if(!o.signerPubkey)throw new Error("Bad bunker url");const s=Boolean(this.params.userInfo);await this.initSigner(o,{eventToAddAccount:s});return{bunkerUrl:`bunker://${await this.signer.createAccount2({bunkerPubkey:o.signerPubkey,name:t,domain:n,perms:this.params.optionsModal.perms})}?`+(o.relays??[]).map((e=>`relay=${encodeURIComponent(e)}`)).join("&"),sk:o.sk}}releaseSigner(){this.signer=null,this.signerErrCallback?.("cancelled"),this.localSigner=null;for(const e of this.ndk.pool.relays.keys())this.ndk.pool.removeRelay(e)}async logout(e=!1){e||this.releaseSigner(),localStorageRemoveCurrentAccount(),this.onAuth("logout"),this.emit("updateAccounts")}setUserInfo(e){this.params.userInfo=e,this.emit("onUserInfo",e),e&&(localStorageAddAccount(e),this.emit("updateAccounts"))}exportKeys(){return this.params.userInfo?"local"!==this.params.userInfo.authMethod?"":nip19_exports.nsecEncode(this.params.userInfo.sk):""}onAuth(e,t=null){if("logout"!==e&&!t)throw new Error("No user info in onAuth");if(t&&this.params.userInfo&&(t.pubkey!==this.params.userInfo.pubkey||t.authMethod!==this.params.userInfo.authMethod)){const e=new CustomEvent("nlAuth",{detail:{type:"logout"}});console.log("nostr-login auth",e.detail),document.dispatchEvent(e)}this.setUserInfo(t),t&&fetchProfile(t,this.profileNdk).then((e=>{if(this.params.userInfo!==t)return;const n={...this.params.userInfo,picture:e?.image||e?.picture,name:e?.name||e?.displayName||e?.nip05||nip19_exports.npubEncode(t.pubkey)};this.setUserInfo(n)}));try{const n=t?nip19_exports.npubEncode(t.pubkey):"",r={type:e};"logout"===e?(this.iframe&&this.iframe.remove(),this.iframe=void 0):(r.pubkey=t.pubkey,r.name=t.name,t.sk&&(r.localNsec=nip19_exports.nsecEncode(t.sk)),t.relays&&(r.relays=t.relays),t.otpData&&(r.otpData=t.otpData),r.method=t.authMethod||"connect");const o=new CustomEvent("nlAuth",{detail:r});console.log("nostr-login auth",r),document.dispatchEvent(o),this.params.optionsModal.onAuth&&this.params.optionsModal.onAuth(n,r)}catch(e){console.log("onAuth error",e)}}async createIframe(e){if(!e)return;const t=new URL(e);let n;const r="__nostr-login-worker-iframe-"+t.hostname.replaceAll(".","-");n=document.querySelector(`#${r}`),console.log("iframe",r,n),n||(n=document.createElement("iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.setAttribute("border","0"),n.style.display="none",n.id=r,document.body.append(n)),n.setAttribute("src",e);const o=new ReadyListener(["workerReady","workerError"],t.origin);await new Promise((e=>{n.addEventListener("load",e)}));const s=await o.wait();return console.log("nostr-login iframe ready",e,s),{iframe:n,port:s[1]}}async sendNeedAuth(){const[e]=await this.getNostrConnectServices(),t=new CustomEvent("nlNeedAuth",{detail:{nostrconnect:e}});console.log("nostr-login need auth",e),document.dispatchEvent(t)}isAuthing(){return!!this.readyCallback}async startAuth(){if(console.log("startAuth"),this.readyCallback)throw new Error("Already started");this.readyPromise=new Promise((e=>this.readyCallback=e))}async endAuth(){if(console.log("endAuth",this.params.userInfo),this.params.userInfo&&this.params.userInfo.iframeUrl){const{iframe:e,port:t}=await this.createIframe(this.params.userInfo.iframeUrl)||{};if(this.iframe=e,!this.iframe||!t)return;this.signer.rpc.setWorkerIframePort(t)}this.readyCallback(),this.readyCallback=void 0}resetAuth(){this.readyCallback&&this.readyCallback(),this.readyCallback=void 0}async listen(e){if(!e.iframeUrl)return this.signer.listen(this.nostrConnectSecret);const t=await this.starterReady.wait();if("starterError"===t[0])throw new Error(t[1]);return this.signer.setListenReply(t[1],this.nostrConnectSecret)}async connect(e,t){return this.signer.connect(e.token,t)}async initSigner(e,{listen:t=!1,connect:n=!1,eventToAddAccount:r=!1}={}){if(this.signerPromise)try{await this.signerPromise}catch{}console.log("initSigner info",e);const o=e.iframeUrl?new URL(e.iframeUrl).origin:void 0;return o&&(this.starterReady=new ReadyListener(["starterDone","starterError"],o)),this.emit("onIframeUrl",e.iframeUrl),this.signerPromise=new Promise((async(s,i)=>{this.signerErrCallback=i;try{if(e.relays&&!e.iframeUrl)for(const t of e.relays)this.ndk.addExplicitRelay(t,void 0);await this.ndk.connect(CONNECT_TIMEOUT);const i=new PrivateKeySigner(e.sk);this.signer=new Nip46Signer(this.ndk,i,e.signerPubkey,o),this.signer.on("iframeRestart",(async()=>{const t=e.iframeUrl+(e.iframeUrl.includes("?")?"&":"?")+"pubkey="+e.pubkey+"&rebind="+i.pubkey;this.emit("iframeRestart",{pubkey:e.pubkey,iframeUrl:t})})),this.signer.on("authUrl",(t=>{console.log("nostr login auth url",t),this.emit("onAuthUrl",{url:t,iframeUrl:e.iframeUrl,eventToAddAccount:r})})),t?await this.listen(e):n?await this.connect(e,this.params.optionsModal.perms):await this.signer.initUserPubkey(e.pubkey),e.pubkey=this.signer.userPubkey,e.signerPubkey=this.signer.remotePubkey,s()}catch(e){console.log("initSigner failure",e),this.signer=null,i(e)}})),this.signerPromise}async authNip46(e,{name:t,bunkerUrl:n,sk:r="",domain:o="",iframeUrl:s=""}){try{const i=bunkerUrlToInfo(n,r);if(isBunkerUrl(t)?i.bunkerUrl=t:(i.nip05=t,i.domain=t.split("@")[1]),o&&(i.domain=o),s&&(i.iframeUrl=s),!i.signerPubkey||!i.sk||!i.relays||0===i.relays.length)throw new Error(`Bad bunker url ${n}`);const a=Boolean(this.params.userInfo);console.log("authNip46",e,i),await this.initSigner(i,{connect:!0,eventToAddAccount:a}),this.onAuth(e,i)}catch(e){throw console.log("nostr login auth failed",e),e}}async signEvent(e){const t=(async()=>(this.localSigner?(e.pubkey=getPublicKey(this.localSigner.privateKey),e.id=getEventHash(e),e.sig=await this.localSigner.sign(e)):(e.pubkey=this.signer?.remotePubkey,e.id=getEventHash(e),e.sig=await(this.signer?.sign(e))),e))(),n=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Sign timeout"))),2e4)})),r=await Promise.race([t,n]);return console.log("signed",{event:r}),r}async codec_call(e,t,n){return new Promise(((r,o)=>{this.signer.rpc.sendRequest(this.signer.remotePubkey,e,[t,n],24133,(e=>{e.error?o(e.error):r(e.result)}))}))}async encrypt04(e,t){return this.localSigner?this.localSigner.encrypt(new NDKUser({pubkey:e}),t):this.signer.encrypt(new NDKUser({pubkey:e}),t)}async decrypt04(e,t){return this.localSigner?this.localSigner.decrypt(new NDKUser({pubkey:e}),t):this.codec_call("nip04_decrypt",e,t)}async encrypt44(e,t){return this.localSigner?this.nip44Codec.encrypt(this.localSigner.privateKey,e,t):this.codec_call("nip44_encrypt",e,t)}async decrypt44(e,t){return this.localSigner?this.nip44Codec.decrypt(this.localSigner.privateKey,e,t):this.codec_call("nip44_decrypt",e,t)}}class ModalManager extends lib$1.EventEmitter{modal=null;params;extensionService;authNostrService;launcherPromise;accounts=[];recents=[];opt;constructor(e,t,n){super(),this.params=e,this.extensionService=n,this.authNostrService=t}async waitReady(){if(this.launcherPromise){try{await this.launcherPromise}catch{}this.launcherPromise=void 0}}async launch(e){console.log("nostr-login launch",e),this.launcherPromise&&await this.waitReady(),this.authNostrService.isAuthing()&&this.authNostrService.resetAuth(),this.opt=e;const t=document.createElement("dialog");if(this.modal=document.createElement("nl-auth"),this.modal.accounts=this.accounts,this.modal.recents=this.recents,this.modal.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.modal.setAttribute("theme",e.theme),e.startScreen&&this.modal.setAttribute("start-screen",e.startScreen),e.bunkers)this.modal.setAttribute("bunkers",e.bunkers);else{let e="nsec.app,highlighter.com";this.modal.setAttribute("bunkers",e)}void 0!==e.methods&&(this.modal.authMethods=e.methods),void 0!==e.localSignup&&(this.modal.localSignup=e.localSignup),void 0!==e.signupNstart&&(this.modal.signupNjump=e.signupNstart),e.title&&(this.modal.welcomeTitle=e.title),e.description&&(this.modal.welcomeDescription=e.description),this.modal.hasExtension=this.extensionService.hasExtension(),this.modal.hasOTP=!!e.otpRequestUrl&&!!e.otpReplyUrl,this.modal.isLoadingExtension=!1,this.modal.isLoading=!1,[this.modal.connectionString,this.modal.connectionStringServices]=await this.authNostrService.getNostrConnectServices(),t.appendChild(this.modal),document.body.appendChild(t);let n="";return this.launcherPromise=new Promise(((e,r)=>{t.addEventListener("close",(()=>{r(new Error("Closed")),this.authNostrService.resetAuth(),this.modal&&(document.body.removeChild(this.modal.parentNode),this.modal=null)}));const o=async e=>{this.modal&&(this.modal.isLoading=!1),await this.authNostrService.endAuth(),t.close(),this.modal=null,e()},s=async(t,n)=>{this.modal&&(this.modal.isLoading=!0);try{n&&!n.start||await this.authNostrService.startAuth(),await t(),n&&!n.end||await o(e)}catch(e){console.log("error",e),this.modal&&(this.modal.isLoading=!1,this.modal.authUrl="",this.modal.iframeUrl="","cancelled"!==e&&(this.modal.error=e.toString()))}},i=async(e,t)=>{await s((async()=>{const n=await getBunkerUrl(e,this.params.optionsModal);await this.authNostrService.authNip46("login",{name:e,bunkerUrl:n,domain:t})}))},a=async e=>{await s((async()=>{const{bunkerUrl:t,sk:n}=await this.authNostrService.createAccount(e);await this.authNostrService.authNip46("signup",{name:e,bunkerUrl:t,sk:n})}))},l=async()=>{try{await navigator.clipboard.writeText(this.authNostrService.exportKeys()),localStorageSetItem("backupKey","true")}catch(e){console.error("Failed to copy to clipboard: ",e)}},c=async e=>{await s((async()=>{const{iframeUrl:t}=e;e.link=this.authNostrService.prepareImportUrl(e.link),this.modal&&t&&(this.modal.authUrl=e.link,this.modal.iframeUrl=t,this.modal.isLoading=!1,console.log("nostrconnect authUrl",this.modal.authUrl,this.modal.iframeUrl)),await this.authNostrService.importAndConnect(e)}))},d=async e=>{await s((async()=>{const{relays:t,domain:n,link:r,iframeUrl:o}=e||{};console.log("nostrConnect",e,t,n,r,o),this.modal&&(o&&(this.modal.authUrl=r,this.modal.iframeUrl=o,this.modal.isLoading=!1,console.log("nostrconnect authUrl",this.modal.authUrl,this.modal.iframeUrl)),e||(this.modal.isLoading=!1)),await this.authNostrService.nostrConnect(t,{domain:n,link:r,iframeUrl:o})}))},h=async e=>{await s((async()=>{if(!e)throw new Error("Please enter some nickname");await this.authNostrService.localSignup(e)}))},u=async()=>{await s((async()=>{const e=new URL(window.location.href),t=e.hostname.toLocaleLowerCase().replace(/^www\./i,"").charAt(0).toUpperCase()+e.hostname.slice(1),n=prepareSignupRelays(this.params.optionsModal.signupRelays);return this.modal.njumpIframe=`\n <html><body>\n <script src='https://start.njump.me/modal.js'><\/script>\n <script>\n new NstartModal({\n baseUrl: 'https://start.njump.me',\n // Required parameters\n an: '${t}',\n // Optional parameters\n s: [${this.opt.followNpubs?`'${this.opt.followNpubs}'`:""}],\n afb: false, // forceBunker\n asb: false, // skipBunker\n aan: false, // avoidNsec\n aac: true, // avoidNcryptsec\n ahc: true, // hide close button\n arr: ${JSON.stringify(n)}, //readRelays\n awr: ${JSON.stringify(n)}, //writeRelays\n // Callbacks\n onComplete: (result) => {\n console.log('Login token:', result.nostrLogin);\n window.parent.location.href='${window.location.href}#nostr-login='+result.nostrLogin;\n },\n onCancel: () => {\n window.parent.location.href='${window.location.href}#nostr-login=null';\n },\n }).open();\n <\/script>\n </body></html>\n `.replaceAll("&","&"),new Promise(((e,t)=>{const n=async n=>{if(console.log("nsecOrBunker",n),n.startsWith("nsec1")){let t;try{t=nip19_exports.decode(n)}catch(e){throw new Error("Bad nsec value")}if("nsec"!==t.type)throw new Error("Bad bech32 type");await this.authNostrService.localSignup("",t.data),e()}else n.startsWith("bunker:")?(await this.authNostrService.authNip46("login",{name:"",bunkerUrl:n}),e()):t("null"===n?"Cancelled":"Unknown return value")};window.addEventListener("hashchange",(async()=>{if(window.location.hash.startsWith("#nostr-login=")){const e=window.location.hash.split("#nostr-login=")[1],t=new URL(window.location.toString());t.hash="",window.history.replaceState({},"",t.toString()),n(e)}}))}))}))};if(!this.modal)throw new Error("WTH?");this.modal.addEventListener("handleContinue",(()=>{this.modal&&(this.modal.isLoading=!0,this.emit("onAuthUrlClick",this.modal.authUrl))})),this.modal.addEventListener("nlLogin",(e=>{i(e.detail)})),this.modal.addEventListener("nlSignup",(e=>{a(e.detail)})),this.modal.addEventListener("nlLocalSignup",(e=>{h(e.detail)})),this.modal.addEventListener("nlSignupNjump",(e=>{u()})),this.modal.addEventListener("nlImportAccount",(e=>{c(e.detail)})),this.modal.addEventListener("nlExportKeys",(e=>{l()})),this.modal.addEventListener("handleLogoutBanner",(()=>{this.emit("onLogoutBanner")})),this.modal.addEventListener("nlNostrConnect",(e=>{d(e.detail)})),this.modal.addEventListener("nlNostrConnectDefault",(()=>{this.authNostrService.isAuthing()||d()})),this.modal.addEventListener("nlNostrConnectDefaultCancel",(()=>{console.log("nlNostrConnectDefaultCancel"),this.authNostrService.cancelNostrConnect()})),this.modal.addEventListener("nlSwitchAccount",(e=>{const n=e.detail;this.emit("onSwitchAccount",n),setTimeout((()=>t.close()),300)})),this.modal.addEventListener("nlLoginRecentAccount",(async e=>{const n=e.detail;if("readOnly"===n.authMethod)this.authNostrService.setReadOnly(n.pubkey),t.close();else if("otp"===n.authMethod)try{this.modal.dispatchEvent(new CustomEvent("nlLoginOTPUser",{detail:n.nip05||n.pubkey}))}catch(e){console.error(e)}else if("extension"===n.authMethod)await this.extensionService.trySetExtensionForPubkey(n.pubkey),t.close();else{const e=n.bunkerUrl||n.nip05;if(!e)throw new Error("Bad connect info");i(e,n.domain)}})),this.modal.addEventListener("nlRemoveRecent",(e=>{localStorageRemoveRecent(e.detail),this.emit("updateAccounts")}));const p=async e=>{let t="";if(e.includes("@")){const{error:n,pubkey:r}=await checkNip05(e);if(!r)throw new Error(n);t=r}else if(e.startsWith("npub")){const{type:n,data:r}=nip19_exports.decode(e);if("npub"!==n)throw new Error("Bad npub");t=r}else 64===e.trim().length&&(t=e.trim(),nip19_exports.npubEncode(t));return t};this.modal.addEventListener("nlLoginReadOnly",(async e=>{await s((async()=>{const t=e.detail,n=await p(t);this.authNostrService.setReadOnly(n)}))})),this.modal.addEventListener("nlLoginExtension",(async()=>{if(!this.extensionService.hasExtension())throw new Error("No extension");await s((async()=>{this.modal&&(this.modal.isLoadingExtension=!0,await this.extensionService.setExtension(),this.modal.isLoadingExtension=!1)}))})),this.modal.addEventListener("nlLoginOTPUser",(async e=>{await s((async()=>{if(!this.modal)return;const t=e.detail,r=await p(t),o=this.opt.otpRequestUrl+(this.opt.otpRequestUrl.includes("?")?"&":"?")+"pubkey="+r,s=await fetch(o);if(200!==s.status)throw console.warn("nostr-login: bad otp reply",s),new Error("Failed to send DM");this.modal.isOTP=!0,n=r,this.modal.isLoading=!1}),{start:!0})})),this.modal.addEventListener("nlLoginOTPCode",(async e=>{await s((async()=>{if(!this.modal)return;const t=e.detail,r=this.opt.otpReplyUrl+(this.opt.otpRequestUrl.includes("?")?"&":"?")+"pubkey="+n+"&code="+t,o=await fetch(r);if(200!==o.status)throw console.warn("nostr-login: bad otp reply",o),new Error("Invalid code");const s=await o.text();this.authNostrService.setOTP(n,s),this.modal.isOTP=!1}),{end:!0})})),this.modal.addEventListener("nlCheckSignup",(async e=>{const{available:t,taken:n,error:r}=await checkNip05(e.detail);this.modal&&(this.modal.error=String(r),!r&&n&&(this.modal.error="Already taken"),this.modal.signupNameIsAvailable=t)})),this.modal.addEventListener("nlCheckLogin",(async e=>{const{available:t,taken:n,error:r}=await checkNip05(e.detail);this.modal&&(this.modal.error=String(r),t&&(this.modal.error="Name not found"),this.modal.loginIsGood=n)}));const f=()=>{this.modal&&(this.modal.isLoading=!1),t.close(),r(new Error("Cancelled"))};this.modal.addEventListener("stopFetchHandler",f),this.modal.addEventListener("nlCloseModal",f),this.modal.addEventListener("nlChangeDarkMode",(e=>{setDarkMode(e.detail),document.dispatchEvent(new CustomEvent("nlDarkMode",{detail:e.detail}))})),this.on("onIframeAuthUrlCallEnd",(()=>{t.close(),this.modal=null,e()})),t.showModal()})),this.launcherPromise}async showIframeUrl(e){await this.waitReady(),this.launch({startScreen:"iframe"}).catch((()=>console.log("closed auth iframe"))),this.modal.authUrl=e}connectModals(e){const t=async e=>{await this.launch(e)},n=document.getElementsByTagName("nl-button");for(let r=0;r<n.length;r++){const o=n[r].getAttribute("nl-theme"),s=n[r].getAttribute("start-screen"),i={...e};switch(o&&(i.theme=o),s){case"login":case"login-bunker-url":case"login-read-only":case"signup":case"switch-account":case"welcome":i.startScreen=s}n[r].addEventListener("click",(function(){t(i)}))}}onAuthUrl(e){this.modal&&(this.modal.authUrl=e,this.modal.isLoading=!1)}onIframeUrl(e){this.modal&&(console.log("modal iframe url",e),this.modal.iframeUrl=e)}onCallEnd(){this.modal&&this.modal.authUrl&&this.params.userInfo?.iframeUrl&&this.emit("onIframeAuthUrlCallEnd")}onUpdateAccounts(e,t){this.accounts=e,this.recents=t,this.modal&&(this.modal.accounts=e,this.modal.recents=t)}onDarkMode(e){this.modal&&(this.modal.darkMode=e)}}class Nostr{#e;nip04;nip44;constructor(e){this.#e=e,this.getPublicKey=this.getPublicKey.bind(this),this.signEvent=this.signEvent.bind(this),this.getRelays=this.getRelays.bind(this),this.nip04={encrypt:this.encrypt04.bind(this),decrypt:this.decrypt04.bind(this)},this.nip44={encrypt:this.encrypt44.bind(this),decrypt:this.decrypt44.bind(this)}}async ensureAuth(){if(await this.#e.waitReady(),!this.#e.getUserInfo()&&(await this.#e.launch(),!this.#e.getUserInfo()))throw new Error("Rejected by user")}async getPublicKey(){await this.ensureAuth();const e=this.#e.getUserInfo();if(e)return e.pubkey;throw new Error("No user")}async signEvent(e){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().signEvent(e)))}async getRelays(){return{}}async encrypt04(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip04.encrypt(e,t)))}async decrypt04(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip04.decrypt(e,t)))}async encrypt44(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip44.encrypt(e,t)))}async decrypt44(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip44.decrypt(e,t)))}}class NostrExtensionService extends lib$1.EventEmitter{params;nostrExtension;constructor(e){super(),this.params=e}startCheckingExtension(e){if(this.checkExtension(e))return;const t=setInterval((()=>{this.checkExtension(e)&&clearTimeout(t)}),100)}checkExtension(e){return!(this.nostrExtension||!window.nostr||window.nostr===e)&&(this.initExtension(e),!0)}async initExtension(e,t){this.nostrExtension=window.nostr,window.nostr=e,"extension"===this.params.userInfo?.authMethod&&await this.trySetExtensionForPubkey(this.params.userInfo.pubkey),t||setTimeout((()=>{window.nostr!==e&&this.nostrExtension!==window.nostr&&this.initExtension(e,!0)}),300)}async setExtensionReadPubkey(e){window.nostr=this.nostrExtension;const t=await window.nostr.getPublicKey();e&&e!==t?this.emit("extensionLogout"):this.emit("extensionLogin",t)}async trySetExtensionForPubkey(e){if(this.nostrExtension)return this.setExtensionReadPubkey(e)}async setExtension(){return this.setExtensionReadPubkey()}unsetExtension(e){window.nostr===this.nostrExtension&&(window.nostr=e)}getExtension(){return this.nostrExtension}hasExtension(){return!!this.nostrExtension}}class NostrParams{userInfo;optionsModal;constructor(){this.userInfo=null,this.optionsModal={theme:"default",startScreen:"welcome",devOverrideBunkerOrigin:""}}}class Popup{popup=null;constructor(){}openPopup(e){if((!this.popup||this.popup.closed)&&(this.popup=window.open(e,"_blank","width=400,height=700"),console.log("popup",this.popup),!this.popup))throw new Error("Popup blocked. Try again, please!")}closePopup(){try{this.popup?.close(),this.popup=null}catch{}}}const CALL_TIMEOUT=5e3;class ProcessManager extends lib$1.EventEmitter{callCount=0;callTimer;constructor(){super()}onAuthUrl(){Boolean(this.callTimer)&&clearTimeout(this.callTimer)}onIframeUrl(){Boolean(this.callTimer)&&clearTimeout(this.callTimer)}async wait(e){let t,n;this.callTimer||(this.callTimer=setTimeout((()=>this.emit("onCallTimeout")),CALL_TIMEOUT)),this.callCount||this.emit("onCallStart"),this.callCount++;try{n=await e()}catch(e){t=e}if(this.callCount--,this.emit("onCallEnd"),this.callTimer&&clearTimeout(this.callTimer),this.callTimer=void 0,t)throw t;return n}}class NostrLoginInitializer{extensionService;params;authNostrService;nostr;processManager;popupManager;bannerManager;modalManager;customLaunchCallback;constructor(){this.params=new NostrParams,this.processManager=new ProcessManager,this.popupManager=new Popup,this.bannerManager=new BannerManager(this.params),this.authNostrService=new AuthNostrService(this.params),this.extensionService=new NostrExtensionService(this.params),this.modalManager=new ModalManager(this.params,this.authNostrService,this.extensionService);const e={waitReady:async()=>{await this.authNostrService.waitReady(),await this.modalManager.waitReady()},getUserInfo:()=>this.params.userInfo,getSigner:()=>{if("readOnly"===this.params.userInfo.authMethod)throw new Error("Read only");return"extension"===this.params.userInfo.authMethod?this.extensionService.getExtension():this.authNostrService},launch:()=>this.launch(),wait:e=>this.processManager.wait(e)};this.nostr=new Nostr(e),this.processManager.on("onCallTimeout",(()=>{this.bannerManager.onCallTimeout()})),this.processManager.on("onCallEnd",(()=>{this.bannerManager.onCallEnd(),this.modalManager.onCallEnd()})),this.processManager.on("onCallStart",(()=>{this.bannerManager.onCallStart()})),this.authNostrService.on("onIframeUrl",(e=>{this.modalManager.onIframeUrl(e)})),this.authNostrService.on("iframeRestart",(({iframeUrl:e})=>{this.processManager.onIframeUrl(),this.bannerManager.onIframeRestart(e)})),this.authNostrService.on("onAuthUrl",(({url:e,iframeUrl:t,eventToAddAccount:n})=>{this.processManager.onAuthUrl(),n?this.modalManager.onAuthUrl(e):this.params.userInfo?this.bannerManager.onAuthUrl(e,t):this.modalManager.onAuthUrl(e)})),this.authNostrService.on("updateAccounts",(()=>{this.updateAccounts()})),this.authNostrService.on("onUserInfo",(e=>{this.bannerManager.onUserInfo(e)})),this.modalManager.on("onAuthUrlClick",(e=>{this.openPopup(e)})),this.bannerManager.on("onIframeAuthUrlClick",(e=>{this.modalManager.showIframeUrl(e)})),this.modalManager.on("onSwitchAccount",(async e=>{this.switchAccount(e)})),this.modalManager.on("onLogoutBanner",(async e=>{logout()})),this.bannerManager.on("onConfirmLogout",(async()=>{this.launch("confirm-logout")})),this.modalManager.on("updateAccounts",(()=>{this.updateAccounts()})),this.bannerManager.on("logout",(()=>{logout()})),this.bannerManager.on("onAuthUrlClick",(e=>{this.openPopup(e)})),this.bannerManager.on("onSwitchAccount",(async e=>{this.switchAccount(e)})),this.bannerManager.on("import",(()=>{this.launch("import")})),this.extensionService.on("extensionLogin",(e=>{this.authNostrService.setExtension(e)})),this.extensionService.on("extensionLogout",(()=>{logout()})),this.bannerManager.on("launch",(e=>{this.launch(e)}))}openPopup(e){this.popupManager.openPopup(e)}async switchAccount(e,t=!1){if(console.log("nostr login switch to info",e),this.extensionService.unsetExtension(this.nostr),"readOnly"===e.authMethod)this.authNostrService.setReadOnly(e.pubkey);else if("otp"===e.authMethod)this.authNostrService.setOTP(e.pubkey,e.otpData||"");else if("local"===e.authMethod&&e.sk)this.authNostrService.setLocal(e,t);else if("extension"===e.authMethod)await this.extensionService.trySetExtensionForPubkey(e.pubkey);else{if(!("connect"===e.authMethod&&e.sk&&e.relays&&e.relays[0]))throw new Error("Bad auth info");this.authNostrService.setConnect(e)}}updateAccounts(){const e=localStorageGetAccounts(),t=localStorageGetRecents();this.bannerManager.onUpdateAccounts(e),this.modalManager.onUpdateAccounts(e,t)}async launchCustomNostrConnect(){try{this.authNostrService.isAuthing()&&this.authNostrService.cancelNostrConnect();const e=new Promise((e=>this.customLaunchCallback=e));await this.authNostrService.startAuth(),await this.authNostrService.sendNeedAuth();try{await this.authNostrService.nostrConnect(),await this.authNostrService.endAuth()}catch(t){"cancelled"===t&&await e}}catch(e){console.error("launchCustomNostrConnect",e)}}fulfillCustomLaunchPromise(){if(this.customLaunchCallback){const e=this.customLaunchCallback;this.customLaunchCallback=void 0,e()}}launch=async e=>{if(!e&&this.params.optionsModal.customNostrConnect)return this.launchCustomNostrConnect();const t=localStorageGetRecents(),n=localStorageGetAccounts(),r={...this.params.optionsModal};e&&"default"!==e?r.startScreen=e:(Boolean(t?.length)||Boolean(n?.length))&&(r.startScreen="switch-account"),this.customLaunchCallback&&this.authNostrService.cancelNostrConnect();try{await this.modalManager.launch(r),this.fulfillCustomLaunchPromise()}catch(e){console.log("nostr-login failed",e)}};init=async e=>{this.extensionService.startCheckingExtension(this.nostr),window.nostr=this.nostr,this.modalManager.connectModals(e),this.bannerManager.launchAuthBanner(e),e&&(this.params.optionsModal={...e});try{const e=localStorageGetCurrent();if(e){if(!e.pubkey)throw new Error("Bad stored info");await this.switchAccount(e)}}catch(e){console.log("nostr login init error",e),await logout()}this.updateAccounts()};logout=async()=>{this.extensionService.unsetExtension(this.nostr),await this.authNostrService.logout()};setDarkMode=e=>{localStorageSetItem("nl-dark-mode",`${e}`),this.bannerManager.onDarkMode(e),this.modalManager.onDarkMode(e)};setAuth=async e=>{if(!e.type)throw new Error("Invalid auth event");if("login"!==e.type&&"logout"!==e.type&&"signup"!==e.type)throw new Error("Invalid auth event");if(e.method&&"connect"!==e.method&&"extension"!==e.method&&"local"!==e.method&&"otp"!==e.method&&"readOnly"!==e.method)throw new Error("Invalid auth event");if("logout"===e.type)return this.logout();if(!e.method||!e.pubkey)throw new Error("Invalid pubkey");const t={authMethod:e.method,pubkey:e.pubkey,relays:e.relays,sk:e.localNsec,otpData:e.otpData,name:e.name};await this.switchAccount(t,"signup"===e.type)};cancelNeedAuth=()=>{console.log("cancelNeedAuth"),this.fulfillCustomLaunchPromise(),this.authNostrService.cancelNostrConnect()}}const initializer=new NostrLoginInitializer,{init:init,launch:launch,logout:logout,setDarkMode:setDarkMode,setAuth:setAuth,cancelNeedAuth:cancelNeedAuth}=initializer;document.addEventListener("nlLogout",logout),document.addEventListener("nlLaunch",(e=>{launch(e.detail||"")})),document.addEventListener("nlNeedAuthCancel",(()=>{cancelNeedAuth()})),document.addEventListener("nlDarkMode",(e=>{setDarkMode(!!e.detail)})),document.addEventListener("nlSetAuth",(e=>{setAuth(e.detail)}));export{NostrLoginInitializer,cancelNeedAuth,init,launch,logout,setAuth,setDarkMode};
|
|
17
|
+
Object.defineProperty(e,"__esModule",{value:!0}),e.bytes=e.stringToBytes=e.str=e.bytesToString=e.hex=e.utf8=e.bech32m=e.bech32=e.base58check=e.base58xmr=e.base58xrp=e.base58flickr=e.base58=e.base64url=e.base64=e.base32crockford=e.base32hex=e.base32=e.base16=e.utils=e.assertNumber=void 0,e.assertNumber=t;const l=(e,t)=>t?l(t,e%t):e,c=(e,t)=>e+(t-l(e,t));function d(e,n,r,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(c(n,r)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${r} carryBits=${c(n,r)}`);let s=0,i=0;const a=2**r-1,l=[];for(const o of e){if(t(o),o>=2**n)throw new Error(`convertRadix2: invalid data word=${o} from=${n}`);if(s=s<<n|o,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=r;i-=r)l.push((s>>i-r&a)>>>0);s&=2**i-1}if(s=s<<r-i&a,!o&&i>=n)throw new Error("Excess padding");if(!o&&s)throw new Error(`Non-zero padding: ${s}`);return o&&i>0&&l.push(s>>>0),l}function h(e){return t(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return a(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(a(t,e,256))}}}function u(e,n=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(c(8,e)>32||c(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return d(Array.from(t),8,e,!n)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(d(t,e,8,n))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function f(e,n){if(t(e),"function"!=typeof n)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const r=n(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(r,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const r=t.slice(0,-e),o=n(r).slice(0,e),s=t.slice(-e);for(let t=0;t<e;t++)if(o[t]!==s[t])throw new Error("Invalid checksum");return r}}}e.utils={alphabet:r,chain:n,checksum:f,radix:h,radix2:u,join:o,padding:s},e.base16=n(u(4),r("0123456789ABCDEF"),o("")),e.base32=n(u(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),o("")),e.base32hex=n(u(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),o("")),e.base32crockford=n(u(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),o(""),i((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),e.base64=n(u(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),o("")),e.base64url=n(u(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),o(""));const g=e=>n(h(58),r(e),o(""));e.base58=g("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.base58flickr=g("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),e.base58xrp=g("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const m=[0,2,3,5,6,7,9,10,11];e.base58xmr={encode(t){let n="";for(let r=0;r<t.length;r+=8){const o=t.subarray(r,r+8);n+=e.base58.encode(o).padStart(m[o.length],"1")}return n},decode(t){let n=[];for(let r=0;r<t.length;r+=11){const o=t.slice(r,r+11),s=m.indexOf(o.length),i=e.base58.decode(o);for(let e=0;e<i.length-s;e++)if(0!==i[e])throw new Error("base58xmr: wrong padding");n=n.concat(Array.from(i.slice(i.length-s)))}return Uint8Array.from(n)}};e.base58check=t=>n(f(4,(e=>t(t(e)))),e.base58);const b=n(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),o("")),y=[996825010,642813549,513874426,1027748829,705979059];function w(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<y.length;e++)1==(t>>e&1)&&(n^=y[e]);return n}function v(e,t,n=1){const r=e.length;let o=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);o=w(o)^n>>5}o=w(o);for(let t=0;t<r;t++)o=w(o)^31&e.charCodeAt(t);for(let e of t)o=w(o)^e;for(let e=0;e<6;e++)o=w(o);return o^=n,b.encode(d([o%2**30],30,5,!1))}function k(e){const t="bech32"===e?1:734539939,n=u(5),r=n.decode,o=n.encode,s=p(r);function i(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=r).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const s=e.slice(0,o),i=e.slice(o+1);if(i.length<6)throw new Error("Data must be at least 6 characters long");const a=b.decode(i).slice(0,-6),l=v(s,a,t);if(!i.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:s,words:a}}return{encode:function(e,n,r=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const o=e.length+7+n.length;if(!1!==r&&o>r)throw new TypeError(`Length ${o} exceeds limit ${r}`);return`${e=e.toLowerCase()}1${b.encode(n)}${v(e,n,t)}`},decode:i,decodeToBytes:function(e){const{prefix:t,words:n}=i(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:p(i),fromWords:r,fromWordsUnsafe:s,toWords:o}}e.bech32=k("bech32"),e.bech32m=k("bech32m"),e.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},e.hex=n(u(4),r("0123456789abcdef"),o(""),i((e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));const x={utf8:e.utf8,hex:e.hex,base16:e.base16,base32:e.base32,base64:e.base64,base64url:e.base64url,base58:e.base58,base58xmr:e.base58xmr},E=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;e.bytesToString=(e,t)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(E);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(t)},e.str=e.bytesToString;e.stringToBytes=(e,t)=>{if(!x.hasOwnProperty(e))throw new TypeError(E);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return x[e].decode(t)},e.bytes=e.stringToBytes}(lib);const{bech32:bech32,hex:hex,utf8:utf8}=lib;BigInt(1e3),BigInt(1e6),BigInt(1e9),BigInt(1e12),BigInt("2100000000000000000"),BigInt(1e11);const TAGCODES={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27};for(let e=0,t=Object.keys(TAGCODES);e<t.length;e++)t[e],TAGCODES[t[e]].toString();var NDKRelayConnectivity=class{ndkRelay;_status;relay;connectedAt;_connectionStats={attempts:0,success:0,durations:[]};debug;constructor(e){this.ndkRelay=e,this._status=3,this.relay=relayInit(this.ndkRelay.url),this.debug=this.ndkRelay.debug.extend("connectivity"),this.relay.on("notice",(e=>this.handleNotice(e)))}async initiateAuth(e={limit:1}){this.debug("Initiating authentication");const t=this.relay.sub([e],{id:"auth-test"});t.on("eose",(()=>{t.unsub(),this._status=1,this.ndkRelay.emit("ready"),this.debug("Authentication not required"),t.unsub()})),this.debug("Authentication request started")}async connect(){const e=()=>{this.updateConnectionStats.connected(),this.ndkRelay.authRequired?(this._status=6,this.ndkRelay.emit("connect"),this.initiateAuth()):(this._status=1,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready"))},t=()=>{this.updateConnectionStats.disconnected(),1===this._status&&(this._status=3,this.handleReconnection()),this.ndkRelay.emit("disconnect")},n=async e=>{this.debug("Relay requested authentication",{havePolicy:!!this.ndkRelay.authPolicy}),this.ndkRelay.authPolicy?7!==this._status&&(this._status=7,await this.ndkRelay.authPolicy(this.ndkRelay,e),7===this._status&&(this.debug("Authentication policy finished"),this._status=1,this.ndkRelay.emit("ready"))):await this.ndkRelay.emit("auth",e)};try{this.updateConnectionStats.attempt(),this._status=0,this.relay.off("connect",e),this.relay.off("disconnect",t),this.relay.on("connect",e),this.relay.on("disconnect",t),this.relay.on("auth",n),await this.relay.connect()}catch(e){throw this.debug("Failed to connect",e),this._status=3,e}}disconnect(){this._status=2,this.relay.close()}get status(){return this._status}isAvailable(){return 1===this._status}isFlapping(){const e=this._connectionStats.durations;if(e.length%3!=0)return!1;const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.map((e=>Math.pow(e-t,2))).reduce(((e,t)=>e+t),0)/e.length;return Math.sqrt(n)<1e3}async handleNotice(e){(e.includes("oo many")||e.includes("aximum"))&&(this.disconnect(),setTimeout((()=>this.connect()),2e3),this.debug(this.relay.url,"Relay complaining?",e)),this.ndkRelay.emit("notice",this,e)}handleReconnection(e=0){if(this.isFlapping())return this.ndkRelay.emit("flapping",this,this._connectionStats),void(this._status=5);const t=this.connectedAt?Math.max(0,6e4-(Date.now()-this.connectedAt)):0;setTimeout((()=>{this._status=4,this.connect().then((()=>{this.debug("Reconnected")})).catch((t=>{this.debug("Reconnect failed",t),e<5?setTimeout((()=>{this.handleReconnection(e+1)}),6e4):this.debug("Reconnect failed after 5 attempts")}))}),t)}updateConnectionStats={connected:()=>{this._connectionStats.success++,this._connectionStats.connectedAt=Date.now()},disconnected:()=>{this._connectionStats.connectedAt&&(this._connectionStats.durations.push(Date.now()-this._connectionStats.connectedAt),this._connectionStats.durations.length>100&&this._connectionStats.durations.shift()),this._connectionStats.connectedAt=void 0},attempt:()=>{this._connectionStats.attempts++}};get connectionStats(){return this._connectionStats}},NDKRelayPublisher=class{ndkRelay;constructor(e){this.ndkRelay=e}async publish(e,t=2500){const n=()=>new Promise(((n,r)=>{try{this.publishEvent(e,t).then((e=>n(e))).catch((e=>r(e)))}catch(e){r(e)}})),r=new Promise(((e,n)=>{setTimeout((()=>n(new Error("Timeout"))),t)})),o=()=>{n().then((e=>s(e))).catch((e=>i(e)))};let s,i;return 1===this.ndkRelay.status?Promise.race([n(),r]):Promise.race([new Promise(((e,t)=>{s=e,i=t,this.ndkRelay.once("connect",o)})),r]).finally((()=>{this.ndkRelay.removeListener("connect",o)}))}async publishEvent(e,t){const n=await e.toNostrEvent(),r=this.ndkRelay.connectivity.relay.publish(n);let o;const s=new Promise(((t,n)=>{r.then((()=>{clearTimeout(o),this.ndkRelay.emit("published",e),t(!0)})).catch((t=>{clearTimeout(o),this.ndkRelay.debug("Publish failed",t,e.id),this.ndkRelay.emit("publish:failed",e,t),n(t)}))}));if(!t||e.isEphemeral())return s;const i=new Promise(((n,r)=>{o=setTimeout((()=>{this.ndkRelay.debug("Publish timed out",e.rawEvent()),this.ndkRelay.emit("publish:failed",e,"Timeout"),r(new Error("Publish operation timed out"))}),t)}));return Promise.race([s,i])}async auth(e){return this.ndkRelay.connectivity.relay.auth(e.rawEvent())}};function calculateGroupableId(e){const t=[];for(const n of e){if(n.since||n.until)return null;const e=Object.keys(n||{}).sort().join("-");t.push(e)}return t.join("|")}function mergeFilters(e){const t={};return e.forEach((e=>{Object.entries(e).forEach((([e,n])=>{Array.isArray(n)?void 0===t[e]?t[e]=[...n]:t[e]=Array.from(new Set([...t[e],...n])):t[e]=n}))})),t}var MAX_SUBID_LENGTH=20;function queryFullyFilled(e){return!(!filterIncludesIds(e.filter)||!resultHasAllRequestedIds(e))}function compareFilter(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const[n,r]of Object.entries(e)){const e=t[n];if(!e)return!1;if(Array.isArray(r)&&Array.isArray(e)){const t=r;for(const n of e){const e=n;if(!t.includes(e))return!1}}else if(e!==r)return!1}return!0}function filterIncludesIds(e){return!!e.ids}function resultHasAllRequestedIds(e){const t=e.filter.ids;return!!t&&t.length===e.eventFirstSeen.size}function generateSubId(e,t){const n=e.map((e=>e.subId)).filter(Boolean),r=[],o=new Set,s=new Set;if(n.length>0)r.push(Array.from(new Set(n)).join(","));else{for(const e of t)for(const t of Object.keys(e))"kinds"===t?e.kinds?.forEach((e=>s.add(e))):o.add(t);s.size>0&&r.push("kinds:"+Array.from(s).join(",")),o.size>0&&r.push(Array.from(o).join(","))}let i=r.join("-");return i.length>MAX_SUBID_LENGTH&&(i=i.substring(0,MAX_SUBID_LENGTH)),1!==n.length&&(i+="-"+Math.floor(999*Math.random()).toString()),i}function filterFromId(e){let t;if(e.match(NIP33_A_REGEX)){const[t,n,r]=e.split(":"),o={authors:[n],kinds:[parseInt(t)]};return r&&(o["#d"]=[r]),o}try{switch(t=nip19_exports.decode(e),t.type){case"nevent":return{ids:[t.data.id]};case"note":return{ids:[t.data]};case"naddr":return{authors:[t.data.pubkey],"#d":[t.data.identifier],kinds:[t.data.kind]}}}catch(e){}return{ids:[e]}}function isNip33AValue(e){return null!==e.match(NIP33_A_REGEX)}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/;function relaysFromBech32(e){try{const t=nip19_exports.decode(e);if(["naddr","nevent"].includes(t?.type)){const e=t.data;if(e?.relays)return e.relays.map((e=>new NDKRelay(e)))}}catch(e){}return[]}var NDKGroupedSubscriptions=class extends lib$1.EventEmitter{subscriptions;req;debug;constructor(e,t){super(),this.subscriptions=e,this.debug=t||this.subscriptions[0].subscription.debug.extend("grouped");for(const t of e)this.handleSubscriptionClosure(t)}addSubscription(e){this.subscriptions.push(e),this.handleSubscriptionClosure(e)}eventReceived(e){for(const t of this.subscriptions)t.eventReceived(e)}eoseReceived(e){Array.from(this.subscriptions).forEach((async t=>{t.subscription.eoseReceived(e)}))}handleSubscriptionClosure(e){e.subscription.on("close",(()=>{const t=this.subscriptions.findIndex((t=>t.subscription===e.subscription));this.subscriptions.splice(t,1),this.subscriptions.length<=0&&this.emit("close")}))}map(e){return this.subscriptions.map(e)}[Symbol.iterator](){let e=0;const t=this.subscriptions;return{next:()=>e<t.length?{value:t[e++],done:!1}:{value:null,done:!0}}}},NDKSubscriptionFilters=class{subscription;filters=[];ndkRelay;constructor(e,t,n){this.subscription=e,this.filters=t,this.ndkRelay=n}eventReceived(e){this.eventMatchesLocalFilter(e)&&this.subscription.eventReceived(e,this.ndkRelay,!1)}eventMatchesLocalFilter(e){const t=e.rawEvent();return this.filters.some((e=>matchFilter(e,t)))}};function findMatchingActiveSubscriptions(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length&&compareFilter(e[n],t[n]);n++)return e[n]}var NDKRelaySubscriptions=class{ndkRelay;delayedItems=new Map;delayedTimers=new Map;activeSubscriptions=new Map;activeSubscriptionsByGroupId=new Map;executionTimeoutsByGroupId=new Map;debug;groupingDebug;conn;constructor(e){this.ndkRelay=e,this.conn=e.connectivity,this.debug=e.debug.extend("subscriptions"),this.groupingDebug=e.debug.extend("grouping")}subscribe(e,t){const n=calculateGroupableId(t),r=new NDKSubscriptionFilters(e,t,this.ndkRelay);if(!n||!e.isGroupable())return void this.executeSubscriptions(n,new NDKGroupedSubscriptions([r]),t);const o=this.activeSubscriptionsByGroupId.get(n);if(o){if(findMatchingActiveSubscriptions(o.filters,t)){const n=this.activeSubscriptions.get(o.sub);return void n?.addSubscription(new NDKSubscriptionFilters(e,t,this.ndkRelay))}}let s=this.delayedItems.get(n);s?s.addSubscription(r):(s=new NDKGroupedSubscriptions([r]),this.delayedItems.set(n,s),s.once("close",(()=>{this.delayedItems.get(n)&&this.delayedItems.delete(n)})));let i=this.executionTimeoutsByGroupId.get(n);i&&"at-most"!==e.opts.groupableDelayType||(i=setTimeout((()=>{this.executeGroup(n,e)}),e.opts.groupableDelay),this.executionTimeoutsByGroupId.set(n,i)),this.delayedTimers.has(n)?this.delayedTimers.get(n).push(i):this.delayedTimers.set(n,[i])}executeGroup(e,t){const n=this.delayedItems.get(e);this.delayedItems.delete(e);const r=this.delayedTimers.get(e);if(this.delayedTimers.delete(e),r)for(const e of r)clearTimeout(e);if(n){const t=n.subscriptions[0].filters.length,r=[];for(let e=0;e<t;e++){const t=n.map((t=>t.filters[e]));r.push(mergeFilters(t))}this.executeSubscriptions(e,n,r)}}executeSubscriptionsWhenConnected(e,t,n){const r=()=>{this.debug("new relay coming online for active subscription",{relay:this.ndkRelay.url,mergeFilters:mergeFilters}),this.executeSubscriptionsConnected(e,t,n)};this.ndkRelay.once("ready",r),t.once("close",(()=>{this.ndkRelay.removeListener("ready",r)}))}executeSubscriptions(e,t,n){this.conn.isAvailable()?this.executeSubscriptionsConnected(e,t,n):this.executeSubscriptionsWhenConnected(e,t,n)}executeSubscriptionsConnected(e,t,n){const r=[];for(const{subscription:e}of t)r.push(e);const o=generateSubId(r,n);t.req=n;const s={id:o};(this.ndkRelay.trusted||r.every((e=>e.opts.skipVerification)))&&(s.skipVerification=!0);const i=this.conn.relay.sub(n,s);return this.activeSubscriptions.set(i,t),e&&this.activeSubscriptionsByGroupId.set(e,{filters:n,sub:i}),i.on("event",(e=>{const t=new NDKEvent(void 0,e);t.relay=this.ndkRelay;const n=this.activeSubscriptions.get(i);n?.eventReceived(t)})),i.on("eose",(()=>{const e=this.activeSubscriptions.get(i);e?.eoseReceived(this.ndkRelay)})),t.once("close",(()=>{i.unsub(),this.activeSubscriptions.delete(i),e&&this.activeSubscriptionsByGroupId.delete(e)})),this.executeSubscriptionsWhenConnected(e,t,n),i}executedFilters(){const e=new Map;for(const[,t]of this.activeSubscriptions)e.set(t.req,t.map((e=>e.subscription)));return e}},NDKRelay=class extends lib$1.EventEmitter{url;scores;connectivity;subs;publisher;authPolicy;authRequired=!1;trusted=!1;complaining=!1;debug;constructor(e,t){super(),this.url=e,this.scores=new Map,this.debug=debug3(`ndk:relay:${e}`),this.connectivity=new NDKRelayConnectivity(this),this.subs=new NDKRelaySubscriptions(this),this.publisher=new NDKRelayPublisher(this),this.authPolicy=t}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(){return this.connectivity.connect()}disconnect(){3!==this.status&&this.connectivity.disconnect()}subscribe(e,t){this.subs.subscribe(e,t)}async publish(e,t=2500){return this.publisher.publish(e,t)}async auth(e){return this.publisher.auth(e)}scoreSlowerEvent(e){}tagReference(e){const t=["r",this.url];return e&&t.push(e),t}referenceTags(){return[["r",this.url]]}activeSubscriptions(){return this.subs.executedFilters()}},PublishError=class extends Error{errors;constructor(e,t){super(e),this.errors=t}},NDKRelaySet=class e{relays;debug;ndk;constructor(e,t){this.relays=e,this.ndk=t,this.debug=t.debug.extend("relayset")}addRelay(e){this.relays.add(e)}static fromRelayUrls(t,n){const r=new Set;for(const e of t){const t=n.pool.relays.get(e);if(t)r.add(t);else{const t=new NDKRelay(e);n.pool.useTemporaryRelay(t),r.add(t)}}return new e(new Set(r),n)}async publish(e,t){const n=new Set,r=new Map,o=e.isEphemeral(),s=Array.from(this.relays).map((s=>new Promise((i=>{s.publish(e,t).then((()=>{n.add(s),i()})).catch((e=>{o||(r.set(s,e),this.debug("error publishing to relay",{relay:s.url,err:e})),i()}))}))));if(await Promise.all(s),0===n.size&&!o)throw new PublishError("No relay was able to receive the event",r);return n}size(){return this.relays.size}};function calculateRelaySetFromEvent(e,t){const n=new Set;return e.pool?.relays.forEach((e=>n.add(e))),new NDKRelaySet(n,e)}function getWriteRelaysFor(e,t){if(e.outboxTracker)return e.outboxTracker.data.get(t)?.writeRelays}function calculateRelaySetsFromFilter(e,t){const n=new Map,r=new Set;if(t.forEach((e=>{e.authors&&e.authors.forEach((e=>r.add(e)))})),r.size>0){const o=new Map;for(const t of r){const n=getWriteRelaysFor(e,t);n&&n.size>0?(e.debug(`Adding ${n.size} relays for ${t}`),n.forEach((e=>{const n=o.get(e)||[];n.push(t),o.set(e,n)}))):e.explicitRelayUrls?.forEach((e=>{const n=o.get(e)||[];n.push(t),o.set(e,n)}))}for(const e of o.keys())n.set(e,[]);for(const e of t)if(e.authors)for(const[t,r]of o.entries()){const o=e.authors.filter((e=>r.includes(e)));n.set(t,[...n.get(t),{...e,authors:o}])}else for(const t of o.keys())n.set(t,[...n.get(t),e])}else e.explicitRelayUrls?.forEach((e=>{n.set(e,t)}));return n}function calculateRelaySetsFromFilters(e,t){return calculateRelaySetsFromFilter(e,t)}var DEFAULT_RELAYS=["wss://nos.lol","wss://relay.nostr.band","wss://relay.f7z.io","wss://relay.damus.io","wss://nostr.mom","wss://no.str.cr"],Zap=class extends lib$1.EventEmitter{ndk;zappedEvent;zappedUser;constructor(e){super(),this.ndk=e.ndk,this.zappedEvent=e.zappedEvent,this.zappedUser=e.zappedUser||this.ndk.getUser({hexpubkey:this.zappedEvent?.pubkey})}async getZapEndpoint(){let e,t,n,r;if(this.zappedUser&&(this.zappedUser.profile||await this.zappedUser.fetchProfile({groupable:!1}),e=(this.zappedUser.profile||{}).lud06,t=(this.zappedUser.profile||{}).lud16),t&&!t.startsWith("LNURL")){const[e,r]=t.split("@");n=`https://${r}/.well-known/lnurlp/${e}`}else if(e){const{words:t}=bech32$1.decode(e,1e3),r=bech32$1.fromWords(t);n=new TextDecoder("utf-8").decode(r)}if(!n)throw new Error("No zap endpoint found");try{const e=this.ndk.httpFetch||fetch,t=await e(n);if(200!==t.status){const e=await t.text();throw new Error(`Unable to fetch zap endpoint ${n}: ${e}`)}const o=await t.json();return o?.allowsNostr&&(o?.nostrPubkey||o?.nostrPubKey)&&(r=o.callback),r}catch(e){throw new Error(`Unable to fetch zap endpoint ${n}: ${e}`)}}async createZapRequest(e,t,n,r,o){const s=await this.generateZapRequest(e,t,n,r);if(!s)return null;const{event:i,zapEndpoint:a}=s;if(!i)throw new Error("No zap request event found");let l;await i.sign(o);try{l=await this.getInvoice(i,e,a)}catch(e){throw new Error("Failed to get invoice: "+e)}return l}async getInvoice(e,t,n){const r=await fetch(`${n}?`+new URLSearchParams({amount:t.toString(),nostr:JSON.stringify(e.rawEvent())}));return(await r.json()).pr}async generateZapRequest(e,t,n,r,o){const s=await this.getZapEndpoint();if(!s)throw new Error("No zap endpoint found");if(!this.zappedEvent&&!this.zappedUser)throw new Error("No zapped event or user found");const i=nip57_exports.makeZapRequest({profile:this.zappedUser.pubkey,event:null,amount:e,comment:t||"",relays:r??this.relays()});if(this.zappedEvent){const e=this.zappedEvent.referenceTags();i.tags.push(...e)}i.tags.push(["lnurl",s]);const a=new NDKEvent(this.ndk,i);return n&&(a.tags=a.tags.concat(n)),{event:a,zapEndpoint:s}}relays(){let e=[];return this.ndk?.pool?.relays&&(e=this.ndk.pool.urls()),e.length||(e=DEFAULT_RELAYS),e}};function mergeTags(e,t){const n=new Map,r=(e,t)=>e.every(((e,n)=>e===t[n]));return e.concat(t).forEach((e=>{for(let[t,o]of n)if(r(o,e)||r(e,o))return void(e.length>=o.length&&n.set(t,e));n.set((e=>e.join(","))(e),e)})),Array.from(n.values())}async function generateContentTags(e,t=[]){let n=[];const r=e=>{t.find((t=>t[0]===e[0]&&t[1]===e[1]))||t.push(e)};return e=e.replace(/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,(e=>{try{const t=e.split(/(@|nostr:)/)[2],{type:o,data:s}=nip19_exports.decode(t);let i;switch(o){case"npub":i=["p",s];break;case"nprofile":i=["p",s.pubkey];break;case"note":n.push(new Promise((async e=>{r(["e",s,await maybeGetEventRelayUrl(t),"mention"]),e()})));break;case"nevent":n.push(new Promise((async e=>{let{id:n,relays:o,author:i}=s;o&&0!==o.length||(o=[await maybeGetEventRelayUrl(t)]),r(["e",n,o[0],"mention"]),i&&r(["p",i]),e()})));break;case"naddr":n.push(new Promise((async e=>{const n=[s.kind,s.pubkey,s.identifier].join(":");let o=s.relays??[];0===o.length&&(o=[await maybeGetEventRelayUrl(t)]),r(["a",n,o[0],"mention"]),r(["p",s.pubkey]),e()})));break;default:return e}return i&&r(i),`nostr:${t}`}catch(t){return e}})),await Promise.all(n),{content:e=e.replace(/#(\w+)/g,((e,n)=>{const r=["t",n];return t.find((e=>e[0]===r[0]&&e[1]===r[1]))||t.push(r),e})),tags:t}}async function maybeGetEventRelayUrl(e){return""}function isReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=1e4&&this.kind<2e4}function isEphemeral(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}async function encrypt(e,t){if(!this.ndk)throw new Error("No NDK instance found!");if(t||(await this.ndk.assertSigner(),t=this.ndk.signer),!e){const t=this.getMatchingTags("p");if(1!==t.length)throw new Error("No recipient could be determined and no explicit recipient was provided");e=this.ndk.getUser({hexpubkey:t[0][1]})}this.content=await(t?.encrypt(e,this.content))}async function decrypt(e,t){if(!this.ndk)throw new Error("No NDK instance found!");t||(await this.ndk.assertSigner(),t=this.ndk.signer),e||(e=this.author),this.content=await(t?.decrypt(e,this.content))}function encode(){return this.isParamReplaceable()?nip19_exports.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:this.relay?[this.relay.url]:[]}):this.relay?nip19_exports.neventEncode({id:this.tagId(),relays:[this.relay.url],author:this.pubkey}):nip19_exports.noteEncode(this.tagId())}async function repost(e=!0,t){if(!t&&e){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t=this.ndk.signer}const n=new NDKEvent(this.ndk,{kind:getKind(this),content:""});return n.tag(this),16===n.kind&&n.tags.push(["k",`${this.kind}`]),t&&await n.sign(t),e&&await n.publish(),n}function getKind(e){return 1===e.kind?6:16}var NDKEvent=class e extends lib$1.EventEmitter{ndk;created_at;content="";tags=[];kind;id="";sig;pubkey="";_author=void 0;relay;constructor(e,t){super(),this.ndk=e,this.created_at=t?.created_at,this.content=t?.content||"",this.tags=t?.tags||[],this.id=t?.id||"",this.sig=t?.sig,this.pubkey=t?.pubkey||"",this.kind=t?.kind}rawEvent(){return{created_at:this.created_at,content:this.content,tags:this.tags,kind:this.kind,pubkey:this.pubkey,id:this.id,sig:this.sig}}set author(e){this.pubkey=e.hexpubkey,this._author=void 0}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const e=this.ndk.getUser({hexpubkey:this.pubkey});return this._author=e,e}tag(t,n){let r=[];if(t instanceof NDKUser){const e=["p",t.pubkey];n&&e.push(n),r.push(e)}else if(t instanceof e){const e=t,o=e?.pubkey===this.pubkey;r=e.referenceTags(n,o);for(const t of e.getMatchingTags("p"))t[1]!==this.pubkey&&(this.tags.find((e=>"p"===e[0]&&e[1]===t[1]))||this.tags.push(["p",t[1]]))}else r=[t];this.tags=mergeTags(this.tags,r)}async toNostrEvent(e){if(!e&&""===this.pubkey){const e=await(this.ndk?.signer?.user());this.pubkey=e?.hexpubkey||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const t=this.rawEvent(),{content:n,tags:r}=await this.generateTags();t.content=n||"",t.tags=r;try{this.id=getEventHash(t)}catch(e){}return this.id&&(t.id=this.id),this.sig&&(t.sig=this.sig),t}isReplaceable=isReplaceable.bind(this);isEphemeral=isEphemeral.bind(this);isParamReplaceable=isParamReplaceable.bind(this);encode=encode.bind(this);encrypt=encrypt.bind(this);decrypt=decrypt.bind(this);getMatchingTags(e){return this.tags.filter((t=>t[0]===e))}tagValue(e){const t=this.getMatchingTags(e);if(0!==t.length)return t[0][1]}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}removeTag(e){this.tags=this.tags.filter((t=>t[0]!==e))}async sign(e){e?this.author=await e.user():(this.ndk?.assertSigner(),e=this.ndk.signer),await this.generateTags(),this.isReplaceable()&&(this.created_at=Math.floor(Date.now()/1e3));const t=await this.toNostrEvent();return this.sig=await e.sign(t),this.sig}async publish(e,t){if(this.sig||await this.sign(),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");return e||(e=this.ndk.devWriteRelaySet||calculateRelaySetFromEvent(this.ndk)),e.publish(this,t)}async generateTags(){let e=[];const t=await generateContentTags(this.content,this.tags),n=t.content;if(e=t.tags,this.kind&&this.isParamReplaceable()){if(!this.getMatchingTags("d")[0]){const t=this.tagValue("title");let n=[...Array(t?6:16)].map((()=>Math.random().toString(36)[2])).join("");t&&t.length>0&&(n=t.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")+"-"+n),e.push(["d",n])}}if((this.ndk?.clientName||this.ndk?.clientNip89)&&!this.tagValue("client")){const t=["client",this.ndk.clientName??""];this.ndk.clientNip89&&t.push(this.ndk.clientNip89),e.push(t)}return{content:n||"",tags:e}}muted(){const e=this.ndk?.mutedIds.get(this.pubkey);if(e&&"p"===e)return"author";const t=this.tagReference(),n=this.ndk?.mutedIds.get(t[1]);return n&&n===t[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const e=this.getMatchingTags("d")[0];return e?e[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return 0===this.kind||3===this.kind||this.kind&&this.kind>=1e4&&this.kind<2e4?`${this.kind}:${this.pubkey}`:this.tagId()}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}tagAddress(){if(!this.isParamReplaceable())throw new Error("This must only be called on replaceable events");const e=this.replaceableDTag();return`${this.kind}:${this.pubkey}:${e}`}tagReference(e){let t;return t=this.isParamReplaceable()?["a",this.tagAddress()]:["e",this.tagId()],this.relay?t.push(this.relay.url):t.push(""),e&&t.push(e),t}referenceTags(e,t){let n=[];return n=this.isParamReplaceable()?[["a",this.tagAddress()],["e",this.id]]:[["e",this.id]],this.relay?.url?n=n.map((e=>(e.push(this.relay?.url),e))):e&&(n=n.map((e=>(e.push(""),e)))),e&&n.forEach((t=>t.push(e))),t||n.push(...this.author.referenceTags()),n}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}async zap(e,t,n,r,o){if(!this.ndk)throw new Error("No NDK instance found");o||this.ndk.assertSigner();const s=new Zap({ndk:this.ndk,zappedEvent:this,zappedUser:r}),i=Array.from(this.ndk.pool.relays.keys());return await s.createZapRequest(e,t,n,i,o)}async delete(t){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const n=new e(this.ndk,{kind:5,content:t||""});return n.tag(this),await n.publish(),n}repost=repost.bind(this);async react(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const r=new e(this.ndk,{kind:7,content:t});return r.tag(this),n?await r.publish():await r.sign(),r}get isValid(){return!0}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class e extends NDKEvent{constructor(e,t){super(e,t),this.kind??=10002}static from(t){return new e(t.ndk,t.rawEvent())}get readRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2]||e[2]&&e[2]===READ_MARKER)).map((e=>e[1]))}set readRelayUrls(e){for(const t of e)this.tags.push(["r",t,READ_MARKER])}get writeRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2]||e[2]&&e[2]===WRITE_MARKER)).map((e=>e[1]))}set writeRelayUrls(e){for(const t of e)this.tags.push(["r",t,WRITE_MARKER])}get bothRelayUrls(){return this.getMatchingTags("r").filter((e=>!e[2])).map((e=>e[1]))}set bothRelayUrls(e){for(const t of e)this.tags.push(["r",t])}get relays(){return this.getMatchingTags("r").map((e=>e[1]))}},NDKSubscriptionCacheUsage=(e=>(e.ONLY_CACHE="ONLY_CACHE",e.CACHE_FIRST="CACHE_FIRST",e.PARALLEL="PARALLEL",e.ONLY_RELAY="ONLY_RELAY",e))(NDKSubscriptionCacheUsage||{}),defaultOpts={closeOnEose:!1,cacheUsage:"CACHE_FIRST",groupable:!0,groupableDelay:100,groupableDelayType:"at-most"},NDKSubscription=class extends lib$1.EventEmitter{subId;filters;opts;pool;skipVerification=!1;skipValidation=!1;relayFilters;relaySet;ndk;debug;eoseDebug;eventFirstSeen=new Map;eosesSeen=new Set;eventsPerRelay=new Map;lastEventReceivedAt;internalId;constructor(e,t,n,r,o){if(super(),this.ndk=e,this.pool=n?.pool||e.pool,this.opts={...defaultOpts,...n||{}},this.filters=t instanceof Array?t:[t],this.subId=o||n?.subId,this.internalId=Math.random().toString(36).substring(7),this.relaySet=r,this.debug=e.debug.extend(`subscription[${n?.subId??this.internalId}]`),this.eoseDebug=this.debug.extend("eose"),this.skipVerification=n?.skipVerification||!1,this.skipValidation=n?.skipValidation||!1,this.opts.closeOnEose||this.debug("Creating a permanent subscription",this.opts,JSON.stringify(this.filters)),"ONLY_CACHE"===this.opts.cacheUsage&&!this.opts.closeOnEose)throw new Error("Cannot use cache-only options with a persistent subscription")}get filter(){return this.filters[0]}isGroupable(){return this.opts?.groupable||!1}shouldQueryCache(){return"ONLY_RELAY"!==this.opts?.cacheUsage}shouldQueryRelays(){return"ONLY_CACHE"!==this.opts?.cacheUsage}shouldWaitForCache(){return this.opts.closeOnEose&&!!this.ndk.cacheAdapter?.locking&&"PARALLEL"!==this.opts.cacheUsage}async start(){let e;this.shouldQueryCache()&&(e=this.startWithCache(),this.shouldWaitForCache()&&(await e,queryFullyFilled(this)))?this.emit("eose",this):this.shouldQueryRelays()?this.startWithRelays():this.emit("eose",this)}stop(){this.emit("close",this),this.removeAllListeners()}hasAuthorsFilter(){return this.filters.some((e=>e.authors?.length))}async startWithCache(){if(this.ndk.cacheAdapter?.query){const e=this.ndk.cacheAdapter.query(this);this.ndk.cacheAdapter.locking&&await e}}startWithRelays(){if(this.relaySet){this.relayFilters=new Map;for(const e of this.relaySet.relays)this.relayFilters.set(e.url,this.filters)}else this.relayFilters=calculateRelaySetsFromFilters(this.ndk,this.filters);if(this.relayFilters&&0!==this.relayFilters.size)for(const[e,t]of this.relayFilters){this.pool.getRelay(e).subscribe(this,t)}else this.debug("No relays to subscribe to",this.ndk.explicitRelayUrls)}eventReceived(e,t,n=!1){if(t&&(e.relay=t),t||(t=e.relay),this.skipValidation||e.isValid){if(!n&&t){let n=this.eventsPerRelay.get(t);n||(n=new Set,this.eventsPerRelay.set(t,n)),n.add(e.id);if(this.eventFirstSeen.has(e.id)){const n=Date.now()-(this.eventFirstSeen.get(e.id)||0);return t.scoreSlowerEvent(n),void this.emit("event:dup",e,t,n,this)}this.ndk.cacheAdapter&&this.ndk.cacheAdapter.setEvent(e,this.filters,t),this.eventFirstSeen.set(e.id,Date.now())}else this.eventFirstSeen.set(e.id,0);e.ndk||(e.ndk=this.ndk),this.emit("event",e,t,this),this.lastEventReceivedAt=Date.now()}else this.debug("Event failed validation",e)}eoseTimeout;eoseReceived(e){this.eosesSeen.add(e),this.eoseDebug(`received from ${e.url}`);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const n=this.eosesSeen.size===this.relayFilters?.size;if(queryFullyFilled(this))this.emit("eose"),this.eoseDebug("Query fully filled"),this.opts?.closeOnEose&&this.stop();else if(n)this.emit("eose"),this.eoseDebug("All EOSEs seen"),this.opts?.closeOnEose&&this.stop();else{let e=1e3;const n=this.eosesSeen.size/this.relayFilters.size;if(this.eosesSeen.size>=2&&n>=.5){e*=1-n,this.eoseTimeout&&clearTimeout(this.eoseTimeout);const r=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,void 0!==t&&t<20?this.eoseTimeout=setTimeout(r,e):(this.emit("eose"),this.opts?.closeOnEose&&this.stop())};this.eoseTimeout=setTimeout(r,e)}}}};async function follows(e,t,n=3){if(!this.ndk)throw new Error("NDK not set");const r=Array.from(await this.ndk.fetchEvents({kinds:[n],authors:[this.pubkey]},e||{groupable:!1}))[0];if(r){const e=new Set;return r.tags.forEach((n=>{if("p"===n[0])try{e.add(n[1]),t&&this.ndk?.outboxTracker?.trackUsers([n[1]])}catch(e){}})),[...e].reduce(((e,t)=>{const n=new NDKUser({pubkey:t});return n.ndk=this.ndk,e.add(n),e}),new Set)}return new Set}function profileFromEvent(e){const t={};let n;try{n=JSON.parse(e.content)}catch(e){throw new Error(`Failed to parse profile event: ${e}`)}return Object.keys(n).forEach((e=>{switch(e){case"name":t.name=n.name;break;case"display_name":t.displayName=n.display_name;break;case"image":case"picture":t.image=n.image||n.picture;break;case"banner":t.banner=n.banner;break;case"bio":t.bio=n.bio;break;case"nip05":t.nip05=n.nip05;break;case"lud06":t.lud06=n.lud06;break;case"lud16":t.lud16=n.lud16;break;case"about":t.about=n.about;break;case"zapService":t.zapService=n.zapService;break;case"website":t.website=n.website;break;default:t[e]=n[e]}})),t}function serializeProfile(e){const t={};for(const[n,r]of Object.entries(e))switch(n){case"username":case"name":t.name=r;break;case"displayName":t.display_name=r;break;case"image":case"picture":t.picture=r;break;case"bio":case"about":t.about=r;break;default:t[n]=r}return JSON.stringify(t)}var NDKList=class e extends NDKEvent{_encryptedTags;encryptedTagsLength;constructor(e,t){super(e,t),this.kind??=30001}static from(t){return new e(t.ndk,t.rawEvent())}get title(){const e=this.tagValue("title")||this.tagValue("name");return 3!==this.kind||e?1e4!==this.kind||e?10001!==this.kind||e?10002!==this.kind||e?10003!==this.kind||e?10004!==this.kind||e?10005!==this.kind||e?10006!==this.kind||e?10007!==this.kind||e?10015!==this.kind||e?10030!==this.kind||e?e??this.tagValue("d"):"Emojis":"Interests":"Search Relays":"Blocked Relays":"Public Chats":"Communities":"Bookmarks":"Relay Metadata":"Pinned Notes":"Mute":"Contacts"}set title(e){if(this.removeTag("title"),this.removeTag("name"),!e)throw new Error("Title cannot be empty");this.tags.push(["title",e])}get name(){const e=this.tagValue("name");return 3!==this.kind||e?1e4!==this.kind||e?10001!==this.kind||e?10002!==this.kind||e?10003!==this.kind||e?10004!==this.kind||e?10005!==this.kind||e?10006!==this.kind||e?10007!==this.kind||e?10015!==this.kind||e?10030!==this.kind||e?e??this.tagValue("d"):"Emojis":"Interests":"Search Relays":"Blocked Relays":"Public Chats":"Communities":"Bookmarks":"Relay Metadata":"Pinned Notes":"Mute":"Contacts"}set name(e){if(this.removeTag("name"),!e)throw new Error("Name cannot be empty");this.tags.push(["title",e])}get description(){return this.tagValue("description")}set description(e){e?this.tags.push(["description",e]):this.removeTag("description")}isEncryptedTagsCacheValid(){return!(!this._encryptedTags||this.encryptedTagsLength!==this.content.length)}async encryptedTags(e=!0){if(e&&this.isEncryptedTagsCacheValid())return this._encryptedTags;if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const t=await this.ndk.signer.user();try{if(this.content.length>0)try{const e=await this.ndk.signer.decrypt(t,this.content),n=JSON.parse(e);return n&&n[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=n):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch(e){console.log(`error decrypting ${this.content}`)}}catch(e){}return[]}validateTag(e){return!0}get items(){return this.tags.filter((e=>!["d","L","l","title","name","description","summary","image","thumb","alt","expiration","subject"].includes(e[0])))}async addItem(e,t=void 0,n=!1){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let r;if(e instanceof NDKEvent)r=e.referenceTags();else if(e instanceof NDKUser)r=e.referenceTags();else if(e instanceof NDKRelay)r=e.referenceTags();else{if(!Array.isArray(e))throw new Error("Invalid object type");r=[e]}if(t&&r[0].push(t),n){const e=await this.ndk.signer.user(),t=await this.encryptedTags();t.push(...r),this._encryptedTags=t,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(t),await this.encrypt(e)}else this.tags.push(...r);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(e,t){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(t){const t=await this.ndk.signer.user(),n=await this.encryptedTags();n.splice(e,1),this._encryptedTags=n,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(n),await this.encrypt(t)}else this.tags.splice(e,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}},lists_default=NDKList;async function pin(e,t,n){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),!t){const e=await this.ndk.fetchEvents({kinds:[10001],authors:[this.pubkey]},{cacheUsage:"ONLY_RELAY"});t=e.size>0?lists_default.from(Array.from(e)[0]):new NDKEvent(this.ndk,{kind:10001})}return t.tag(e),n&&await t.publish(),t}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(e,t=fetch,n={}){const r=e.match(NIP05_REGEX);if(!r)return null;const[o,s="_",i]=r;try{const e=await t(`https://${i}/.well-known/nostr.json?name=${s}`,n),{names:r,relays:o,nip46:a}=parseNIP05Result(await e.json()),l=r[s];return l?{pubkey:l,relays:o?.[l],nip46:a?.[l]}:null}catch(e){return null}}function parseNIP05Result(e){const t={names:{}};for(const[n,r]of Object.entries(e.names))"string"==typeof n&&"string"==typeof r&&(t.names[n]=r);if(e.relays){t.relays={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.relays[n]=r.filter((e=>"string"==typeof e)))}if(e.nip46){t.nip46={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.nip46[n]=r.filter((e=>"string"==typeof e)))}return t}var NDKUser=class e{ndk;profile;_npub;_pubkey;relayUrls=[];nip46Urls=[];constructor(e){e.npub&&(this._npub=e.npub),e.hexpubkey&&(this._pubkey=e.hexpubkey),e.pubkey&&(this._pubkey=e.pubkey),e.relayUrls&&(this.relayUrls=e.relayUrls),e.nip46Urls&&(this.nip46Urls=e.nip46Urls)}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("hexpubkey not set");this._npub=nip19_exports.npubEncode(this.pubkey)}return this._npub}set npub(e){this._npub=e}get hexpubkey(){return this.pubkey}set hexpubkey(e){this._pubkey=e}get pubkey(){if(!this._pubkey){if(!this._npub)throw new Error("npub not set");this._pubkey=nip19_exports.decode(this.npub).data}return this._pubkey}set pubkey(e){this._pubkey=e}static async fromNip05(t,n,r=!1){if(n?.cacheAdapter&&n.cacheAdapter.loadNip05){const r=await n.cacheAdapter.loadNip05(t);if(r){const t=new e({pubkey:r.pubkey,relayUrls:r.relays,nip46Urls:r.nip46});return t.ndk=n,t}}let o={};r&&(o.cache="no-cache");const s=await getNip05For(t,n?.httpFetch,o);if(s&&n?.cacheAdapter&&n.cacheAdapter.saveNip05&&n?.cacheAdapter.saveNip05(t,s),s){const t=new e({pubkey:s.pubkey,relayUrls:s.relays,nip46Urls:s.nip46});return t.ndk=n,t}}async fetchProfile(e){if(!this.ndk)throw new Error("NDK not set");this.profile||(this.profile={});let t=null;if(this.ndk.cacheAdapter&&this.ndk.cacheAdapter.fetchProfile&&"ONLY_RELAY"!==e?.cacheUsage){const e=await this.ndk.cacheAdapter.fetchProfile(this.pubkey);if(e)return this.profile=e,e}!e&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.locking&&(t=await this.ndk.fetchEvents({kinds:[0],authors:[this.pubkey]},{cacheUsage:"ONLY_CACHE",closeOnEose:!0,groupable:!1}),e={cacheUsage:"ONLY_RELAY",closeOnEose:!0,groupable:!0,groupableDelay:250}),t&&0!==t.size||(t=await this.ndk.fetchEvents({kinds:[0],authors:[this.pubkey]},e));const n=Array.from(t).sort(((e,t)=>e.created_at-t.created_at));return 0===n.length?null:(this.profile=profileFromEvent(n[0]),this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile)}follows=follows.bind(this);pin=pin.bind(this);async relayList(){if(!this.ndk)throw new Error("NDK not set");const e=this.ndk.outboxPool||this.ndk.pool,t=new Set;for(const n of e.relays.values())t.add(n);const n=new NDKRelaySet(t,this.ndk),r=await this.ndk.fetchEvent({kinds:[10002],authors:[this.pubkey]},{closeOnEose:!0,pool:e,groupable:!0,subId:`relay-list-${this.pubkey.slice(0,6)}`},n);return r?NDKRelayList.from(r):await this.relayListFromKind3()}async relayListFromKind3(){if(!this.ndk)throw new Error("NDK not set");const e=await this.ndk.fetchEvent({kinds:[3],authors:[this.pubkey]});if(e)try{const t=JSON.parse(e.content),n=new NDKRelayList(this.ndk),r=new Set,o=new Set;for(const[e,n]of Object.entries(t))if(n){const t=n;t.write&&o.add(e),t.read&&r.add(e)}else r.add(e),o.add(e);return n.readRelayUrls=Array.from(r),n.writeRelayUrls=Array.from(o),n}catch(e){}}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e?(t[0].push("",e),t):t}async publish(){if(!this.ndk)throw new Error("No NDK instance found");if(!this.profile)throw new Error("No profile available");this.ndk.assertSigner();const e=new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)});await e.publish()}async follow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n)),t.has(e))return!1;t.add(e);const r=new NDKEvent(this.ndk,{kind:n});for(const e of t)r.tag(e);return await r.publish(),!0}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(e);return null===t?null:t.pubkey===this.pubkey}async zap(e,t,n,r){if(!this.ndk)throw new Error("No NDK instance found");r||this.ndk.assertSigner();const o=new Zap({ndk:this.ndk,zappedUser:this}),s=Array.from(this.ndk.pool.relays.keys());return await o.createZapRequest(e,t,n,s,r)}},NDKPrivateKeySigner=class e{_user;privateKey;constructor(e){e&&(this.privateKey=e,this._user=new NDKUser({hexpubkey:getPublicKey(this.privateKey)}))}static generate(){const t=generatePrivateKey();return new e(t)}async blockUntilReady(){if(!this._user)throw new Error("NDKUser not initialized");return this._user}async user(){return await this.blockUntilReady(),this._user}async sign(e){if(!this.privateKey)throw Error("Attempted to sign without a private key");return getSignature(e,this.privateKey)}async encrypt(e,t){if(!this.privateKey)throw Error("Attempted to encrypt without a private key");const n=e.hexpubkey;return await nip04_exports.encrypt(this.privateKey,n,t)}async decrypt(e,t){if(!this.privateKey)throw Error("Attempted to decrypt without a private key");const n=e.hexpubkey;return await nip04_exports.decrypt(this.privateKey,n,t)}},NDKNostrRpc=class extends lib$1.EventEmitter{ndk;signer;debug;constructor(e,t,n){super(),this.ndk=e,this.signer=t,this.debug=n.extend("rpc")}subscribe(e){const t=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1});return t.on("event",(async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):this.emit(`response-${t.id}`,t)}catch(t){this.debug("error parsing event",t,e.rawEvent())}})),new Promise(((e,n)=>{t.on("eose",(()=>e(t)))}))}async parseEvent(e){const t=this.ndk.getUser({hexpubkey:e.pubkey});t.ndk=this.ndk;const n=await this.signer.decrypt(t,e.content),r=JSON.parse(n),{id:o,method:s,params:i,result:a,error:l}=r;return s?{id:o,pubkey:e.pubkey,method:s,params:i,event:e}:{id:o,result:a,error:l,event:e}}async sendResponse(e,t,n,r=24133,o){const s={id:e,result:n};o&&(s.error=o);const i=await this.signer.user(),a=this.ndk.getUser({hexpubkey:t}),l=new NDKEvent(this.ndk,{kind:r,content:JSON.stringify(s),tags:[["p",t]],pubkey:i.hexpubkey});l.content=await this.signer.encrypt(a,l.content),await l.sign(this.signer),await l.publish()}async sendRequest(e,t,n=[],r=24133,o){const s=Math.random().toString(36).substring(7),i=await this.signer.user(),a=this.ndk.getUser({hexpubkey:e}),l={id:s,method:t,params:n},c=new Promise((e=>{const t=e=>{"auth_url"===e.result?(this.once(`response-${s}`,t),this.emit("authUrl",e.error)):o&&o(e)};this.once(`response-${s}`,t)})),d=new NDKEvent(this.ndk,{kind:r,content:JSON.stringify(l),tags:[["p",e]],pubkey:i.pubkey});return d.content=await this.signer.encrypt(a,d.content),await d.sign(this.signer),this.debug(`sending ${t} request to`,e),await d.publish(),c}},NDKNip46Signer=class extends lib$1.EventEmitter{ndk;remoteUser;remotePubkey;token;localSigner;nip05;rpc;debug;relayUrls=[];constructor(e,t,n){let r,o;if(super(),t.includes("#")){const e=t.split("#");r=new NDKUser({npub:e[0]}).pubkey,o=e[1]}else t.startsWith("npub")?r=new NDKUser({npub:t}).pubkey:t.match(/\./)?this.nip05=t:r=t;this.ndk=e,r&&(this.remotePubkey=r),this.token=o,this.debug=e.debug.extend("nip46:signer"),this.remoteUser=new NDKUser({pubkey:r}),this.localSigner=n||NDKPrivateKeySigner.generate(),this.rpc=new NDKNostrRpc(e,this.localSigner,this.debug),this.rpc.on("authUrl",((...e)=>{this.emit("authUrl",...e)})),this.localSigner.user().then((e=>{this.rpc.subscribe({kinds:[24133,24134],"#p":[e.pubkey]})}))}async user(){return this.remoteUser}async blockUntilReady(){const e=await this.localSigner.user(),t=this.ndk.getUser({pubkey:this.remotePubkey});if(this.nip05&&!this.remotePubkey&&NDKUser.fromNip05(this.nip05).then((e=>{e&&(this.remoteUser=e,this.remotePubkey=e.pubkey,this.relayUrls=e.nip46Urls)})),!this.remotePubkey)throw new Error("Remote pubkey not set");return new Promise(((n,r)=>{setTimeout((()=>{const o=[e.pubkey];this.token&&o.push(this.token),this.rpc.sendRequest(this.remotePubkey,"connect",o,24133,(e=>{"ack"===e.result?n(t):r(e.error)}))}),100)}))}async encrypt(e,t){this.debug("asking for encryption");return new Promise(((n,r)=>{this.rpc.sendRequest(this.remotePubkey,"nip04_encrypt",[e.pubkey,t],24133,(e=>{e.error?r(e.error):n(e.result)}))}))}async decrypt(e,t){this.debug("asking for decryption");return new Promise(((n,r)=>{this.rpc.sendRequest(this.remotePubkey,"nip04_decrypt",[e.pubkey,t],24133,(e=>{if(e.error)r(e.error);else{const t=JSON.parse(e.result);n(t[0])}}))}))}async sign(e){this.debug("asking for a signature");return new Promise(((t,n)=>{this.rpc.sendRequest(this.remotePubkey,"sign_event",[JSON.stringify(e)],24133,(e=>{if(this.debug("got a response",e),e.error)n(e.error);else{const n=JSON.parse(e.result);t(n.sig)}}))}))}async createAccount(e,t,n){this.debug("asking to create an account");const r=[];return e&&r.push(e),t&&r.push(t),n&&r.push(n),new Promise(((e,t)=>{this.rpc.sendRequest(this.remotePubkey,"create_account",r,24134,(n=>{if(this.debug("got a response",n),n.error)t(n.error);else{const t=n.result;e(t)}}))}))}};function dedup(e,t){return e.created_at>t.created_at?e:t}var OutboxItem=class{type;relayUrlScores;readRelays;writeRelays;constructor(e){this.type=e,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{data;ndk;debug;constructor(e){super(),this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:5e3})}trackUsers(e){for(const t of e){const e=getKeyFromItem(t);if(this.data.has(e))continue;const n=this.track(t,"user"),r=t instanceof NDKUser?t:new NDKUser({hexpubkey:t});r.ndk=this.ndk,r.relayList().then((t=>{if(t){n.readRelays=new Set(t.readRelayUrls),n.writeRelays=new Set(t.writeRelayUrls);for(const e of n.readRelays)this.ndk.pool.blacklistRelayUrls.has(e)&&(this.debug(`removing blacklisted relay ${e} from read relays`),n.readRelays.delete(e));for(const e of n.writeRelays)this.ndk.pool.blacklistRelayUrls.has(e)&&(this.debug(`removing blacklisted relay ${e} from write relays`),n.writeRelays.delete(e));this.data.set(e,n),this.debug(`Adding ${n.readRelays.size} read relays and ${n.writeRelays.size} write relays for ${r.hexpubkey}`)}}))}}track(e,t){const n=getKeyFromItem(e);t??=getTypeFromItem(e);let r=this.data.get(n);return r||(r=new OutboxItem(t)),this.data.set(n,r),r}};function getKeyFromItem(e){return e instanceof NDKUser?e.hexpubkey:e}function getTypeFromItem(e){return e instanceof NDKUser?"user":"kind"}var NDKPool=class extends lib$1.EventEmitter{relays=new Map;blacklistRelayUrls;debug;temporaryRelayTimers=new Map;flappingRelays=new Set;backoffTimes=new Map;constructor(e=[],t=[],n,r){super(),this.debug=r??n.debug.extend("pool");for(const t of e){const e=new NDKRelay(t);this.addRelay(e,!1)}this.blacklistRelayUrls=new Set(t)}useTemporaryRelay(e,t=6e5){const n=this.relays.has(e.url);n||this.addRelay(e);const r=this.temporaryRelayTimers.get(e.url);if(r&&clearTimeout(r),!n||r){const n=setTimeout((()=>{this.removeRelay(e.url)}),t);this.temporaryRelayTimers.set(e.url,n)}}addRelay(e,t=!0){const n=e.url;this.blacklistRelayUrls?.has(n)?this.debug(`Relay ${n} is blacklisted`):(e.on("notice",(async(e,t)=>this.emit("notice",e,t))),e.on("connect",(()=>this.handleRelayConnect(n))),e.on("ready",(()=>this.handleRelayReady(e))),e.on("disconnect",(async()=>this.emit("relay:disconnect",e))),e.on("flapping",(()=>this.handleFlapping(e))),e.on("auth",(async t=>this.emit("relay:auth",e,t))),this.relays.set(n,e),t&&e.connect().catch((e=>{this.debug(`Failed to connect to relay ${n}`,e)})))}removeRelay(e){const t=this.relays.get(e);if(t)return t.disconnect(),this.relays.delete(e),this.emit("relay:disconnect",t),!0;const n=this.temporaryRelayTimers.get(e);return n&&(clearTimeout(n),this.temporaryRelayTimers.delete(e)),!1}getRelay(e,t=!0){let n=this.relays.get(e);return n||(n=new NDKRelay(e),this.addRelay(n,t)),n}handleRelayConnect(e){this.debug(`Relay ${e} connected`),this.emit("relay:connect",this.relays.get(e)),this.stats().connected===this.relays.size&&this.emit("connect")}handleRelayReady(e){this.debug(`Relay ${e.url} ready`),this.emit("relay:ready",e)}async connect(e){const t=[];this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}...`:""}`);for(const n of this.relays.values())if(e){const r=new Promise(((t,n)=>{setTimeout((()=>n(`Timed out after ${e}ms`)),e)}));t.push(Promise.race([n.connect(),r]).catch((e=>{this.debug(`Failed to connect to relay ${n.url}: ${e??"No reason specified"}`)})))}else t.push(n.connect());e&&setTimeout((()=>{const e=this.stats().connected===this.relays.size,t=this.stats().connected>0;!e&&t&&this.emit("connect")}),e),await Promise.all(t)}checkOnFlappingRelays(){if(this.flappingRelays.size/this.relays.size>=.8)for(const e of this.flappingRelays)this.backoffTimes.set(e,0)}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t*=2,this.backoffTimes.set(e.url,t),this.debug(`Backoff time for ${e.url} is ${t}ms`),setTimeout((()=>{this.debug(`Attempting to reconnect to ${e.url}`),e.connect(),this.checkOnFlappingRelays()}),t),e.disconnect(),this.emit("flapping",e)}size(){return this.relays.size}stats(){const e={total:0,connected:0,disconnected:0,connecting:0};for(const t of this.relays.values())e.total++,1===t.status?e.connected++:3===t.status?e.disconnected++:0===t.status&&e.connecting++;return e}connectedRelays(){return Array.from(this.relays.values()).filter((e=>1===e.status))}urls(){return Array.from(this.relays.keys())}};function correctRelaySet(e,t){const n=t.connectedRelays();if(!Array.from(e.relays).some((e=>n.map((e=>e.url)).includes(e.url))))for(const t of n)e.addRelay(t);if(0===n.length)for(const n of t.relays.values())e.addRelay(n);return e}var SPEC_PATH="/.well-known/nostr/nip96.json",Nip96=class{ndk;spec;url;nip98Required=!1;constructor(e,t){this.url=`https://${e}${SPEC_PATH}`,this.ndk=t}async prepareUpload(e,t="POST"){if(this.validateHttpFetch(),this.spec||await this.fetchSpec(),!this.spec)throw new Error("Failed to fetch NIP96 spec");let n={};if(this.nip98Required){n={Authorization:await this.generateNip98Header(this.spec.api_url,t,e)}}return{url:this.spec.api_url,headers:n}}async xhrUpload(e,t){const n="POST",{url:r,headers:o}=await this.prepareUpload(t,n);e.open(n,r,!0),o.Authorization&&e.setRequestHeader("Authorization",o.Authorization);const s=new FormData;return s.append("file",t),new Promise(((t,n)=>{e.onload=function(){e.status>=200&&e.status<300?t(JSON.parse(e.responseText)):n(new Error(e.statusText))},e.onerror=function(){n(new Error("Network Error"))},e.send(s)}))}async upload(e){const t="POST",{url:n,headers:r}=await this.prepareUpload(e,t),o=new FormData;o.append("file",e);const s=await this.ndk.httpFetch(this.spec.api_url,{method:t,headers:r,body:o});if(200!==s.status)throw new Error(`Failed to upload file to ${n}`);const i=await s.json();if("success"!==i.status)throw new Error(i.message);return i}validateHttpFetch(){if(!this.ndk)throw new Error("NDK is required to fetch NIP96 spec");if(!this.ndk.httpFetch)throw new Error("NDK must have an httpFetch method to fetch NIP96 spec")}async fetchSpec(){this.validateHttpFetch();const e=await this.ndk.httpFetch(this.url);if(200!==e.status)throw new Error(`Failed to fetch NIP96 spec from ${this.url}`);const t=await e.json();if(!t)throw new Error(`Failed to parse NIP96 spec from ${this.url}`);this.spec=t,this.nip98Required=this.spec.plans.free.is_nip98_required}async generateNip98Header(e,t,n){const r=new NDKEvent(this.ndk,{kind:27235,tags:[["u",e],["method",t]]});if(["POST","PUT","PATCH"].includes(t)){const e=await this.calculateSha256(n);r.tags.push(["payload",e])}await r.sign();return`Nostr ${btoa(JSON.stringify(r.rawEvent()))}`}async calculateSha256(e){const t=await e.arrayBuffer(),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map((e=>e.toString(16).padStart(2,"0"))).join("")}},DEFAULT_OUTBOX_RELAYS=["wss://purplepag.es","wss://relay.snort.social"],DEFAULT_BLACKLISTED_RELAYS=["wss://brb.io"],NDK=class extends lib$1.EventEmitter{explicitRelayUrls;pool;outboxPool;_signer;_activeUser;cacheAdapter;debug;devWriteRelaySet;outboxTracker;mutedIds;clientName;clientNip89;relayAuthDefaultPolicy;httpFetch;autoConnectUserRelays=!0;autoFetchUserMutelist=!0;constructor(e={}){super(),this.debug=e.debug||debug3("ndk"),this.explicitRelayUrls=e.explicitRelayUrls||[],this.pool=new NDKPool(e.explicitRelayUrls||[],e.blacklistRelayUrls,this),this.debug(`Starting with explicit relays: ${JSON.stringify(this.explicitRelayUrls)}`),this.pool.on("relay:auth",(async(e,t)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(e,t)})),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.autoFetchUserMutelist=e.autoFetchUserMutelist??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,e.enableOutboxModel&&(this.outboxPool=new NDKPool(e.outboxRelayUrls||DEFAULT_OUTBOX_RELAYS,e.blacklistRelayUrls||DEFAULT_BLACKLISTED_RELAYS,this,this.debug.extend("outbox-pool")),this.outboxTracker=new OutboxTracker(this)),this.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.mutedIds=e.mutedIds||new Map,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this));try{this.httpFetch=fetch}catch{}}addExplicitRelay(e,t,n=!0){let r;return r="string"==typeof e?new NDKRelay(e,t):e,this.pool.addRelay(r,n),this.explicitRelayUrls.push(r.url),r}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){const t=this._activeUser?.pubkey!==e?.pubkey;if(this._activeUser=e,e&&t){const t=async e=>{const t=await e.relayList();if(t){this.debug("Connecting to user relays",{npub:e.npub,relays:t.relays});for(const e of t.relays){let t=this.pool.relays.get(e);t||(t=new NDKRelay(e),this.pool.addRelay(t))}}else this.debug("No relay list found for user",{npub:e.npub})},n=async e=>{const t=await this.fetchEvents([{kinds:[1e4],authors:[e.pubkey]},{kinds:[3e4],authors:[e.pubkey],"#d":["mute"],limit:1}]);if(t)for(const e of t){const t=lists_default.from(e);for(const e of t.items)this.mutedIds.set(e[1],e[0])}else this.debug("No mute list found for user",{npub:e.npub})},r=[];this.autoConnectUserRelays&&r.push(t),this.autoFetchUserMutelist&&r.push(n);const o=async e=>{for(const t of r)await t(e)},s=this.outboxPool||this.pool;s.connectedRelays.length>0?o(e):(this.debug("Waiting for connection to main relays"),s.once("relay:ready",(t=>{this.debug("New relay ready",t?.url),o(e)})))}else e||(this.mutedIds=new Map)}get signer(){return this._signer}set signer(e){this._signer=e,this.emit("signer:ready",e),e?.user().then((e=>{e.ndk=this,this.activeUser=e}))}async connect(e){if(this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer"),this._signer.relays)){(await this._signer.relays()).forEach((e=>this.pool.addRelay(e)))}const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),this.debug("Connecting to relays",{timeoutMs:e}),Promise.allSettled(t).then((()=>{}))}getUser(e){const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}subscribe(e,t,n,r=!0){const o=new NDKSubscription(this,e,t,n);if(n)for(const e of n.relays)this.pool.useTemporaryRelay(e);if(this.outboxPool&&o.hasAuthorsFilter()){const e=o.filters.filter((e=>e.authors&&e.authors?.length>0)).map((e=>e.authors)).flat();this.outboxTracker?.trackUsers(e)}return r&&o.start(),o}async publish(e,t,n){return this.debug("Deprecated: Use `event.publish()` instead"),e.publish(t,n)}async fetchEvent(e,t,n){let r,o;if(n instanceof NDKRelay?o=new NDKRelaySet(new Set([n]),this):n instanceof NDKRelaySet&&(o=n),!n&&"string"==typeof e&&!isNip33AValue(e)){const t=relaysFromBech32(e);t.length>0&&(o=new NDKRelaySet(new Set(t),this),o=correctRelaySet(o,this.pool))}if(r="string"==typeof e?filterFromId(e):e,!r)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise((e=>{const n=this.subscribe(r,{...t||{},closeOnEose:!0},o,!1);n.on("event",(t=>{t.ndk=this,e(t)})),n.on("eose",(()=>{e(null)})),n.start()}))}async fetchEvents(e,t,n){return new Promise((r=>{const o=new Map,s=this.subscribe(e,{...t||{},closeOnEose:!0},n,!1),i=e=>{const t=e.deduplicationKey(),n=o.get(t);n&&(e=dedup(n,e)),e.ndk=this,o.set(t,e)};s.on("event",i),s.on("event:dup",i),s.on("eose",(()=>{r(new Set(o.values()))})),s.start()}))}assertSigner(){if(!this.signer)throw this.emit("signerRequired"),new Error("Signer required")}getNip96(e){return new Nip96(e,this)}};const LOCAL_STORE_KEY="__nostrlogin_nip46",LOGGED_IN_ACCOUNTS="__nostrlogin_accounts",RECENT_ACCOUNTS="__nostrlogin_recent",OUTBOX_RELAYS$1=["wss://purplepag.es","wss://relay.nos.social","wss://user.kindpag.es","wss://relay.damus.io","wss://nos.lol"],DEFAULT_SIGNUP_RELAYS=["wss://relay.damus.io/","wss://nos.lol/","wss://relay.primal.net/"],localStorageSetItem=(e,t)=>{localStorage.setItem(e,t)},localStorageGetItem=e=>{const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch{}return null},localStorageRemoveItem=e=>{localStorage.removeItem(e)},fetchProfile=async(e,t)=>{const n=new NDKUser({pubkey:e.pubkey});return n.ndk=t,await n.fetchProfile()},prepareSignupRelays=e=>{const t=(e||"").split(",").map((e=>e.trim())).filter((e=>e.startsWith("ws")));return t.length||t.push(...DEFAULT_SIGNUP_RELAYS),t},createProfile=async(e,t,n,r,o)=>{const s={name:e.name},i=new NDKEvent(t,{kind:0,created_at:Math.floor(Date.now()/1e3),pubkey:e.pubkey,content:JSON.stringify(s),tags:[]});window.location.hostname&&i.tags.push(["client",window.location.hostname]);const a=new NDKEvent(t,{kind:10002,created_at:Math.floor(Date.now()/1e3),pubkey:e.pubkey,content:"",tags:[]}),l=prepareSignupRelays(r);for(const e of l)a.tags.push(["r",e]);await i.sign(n),console.log("signed profile",i),await a.sign(n),console.log("signed relays",a);const c=o&&o.length?o:OUTBOX_RELAYS$1;await i.publish(NDKRelaySet.fromRelayUrls(c,t)),console.log("published profile",i),await a.publish(NDKRelaySet.fromRelayUrls(c,t)),console.log("published relays",a)},bunkerUrlToInfo=(e,t="")=>{const n=new URL(e);return{pubkey:"",signerPubkey:n.hostname||n.pathname.split("//")[1],sk:t||generatePrivateKey(),relays:n.searchParams.getAll("relay"),token:n.searchParams.get("secret")||"",authMethod:"connect"}},isBunkerUrl=e=>e.startsWith("bunker://"),getBunkerUrl=async(e,t)=>{if(!e)return"";if(isBunkerUrl(e))return e;if(e.includes("@")){const[n,r]=e.toLocaleLowerCase().split("@"),o=t.devOverrideBunkerOrigin||`https://${r}`,s=`${o}/.well-known/nostr.json?name=_`,i=`${o}/.well-known/nostr.json?name=${n}`,a=await fetch(s),l=await a.json(),c=l.names._,d=l.nip46[c],h=await fetch(i),u=(await h.json()).names[n];if(!d||0===d.length)throw new Error("Bunker relay not provided");return`bunker://${u}?${d.map((e=>`relay=${encodeURIComponent(e)}`)).join("&")}`}throw new Error("Invalid user name or bunker url")},checkNip05=async e=>{let t=!1,n="",r="";return await(async()=>{if(!e||!e.includes("@"))return;const[o,s]=e.toLocaleLowerCase().split("@");if(!o)return;if(!new RegExp(/^[\w-.]+@([\w-]+\.)+[\w-]{2,8}$/g).test(e))return void(n="Invalid name");if(!s)return void(n="Select service");const i=`https://${s}/.well-known/nostr.json?name=${o.toLowerCase()}`;try{const e=await fetch(i),t=await e.json();if(t.names[o])return void(r=t.names[o])}catch{}t=!0})(),{available:t,taken:""!=r,error:n,pubkey:r}},upgradeInfo=e=>{"typeAuthMethod"in e&&delete e.typeAuthMethod,e.authMethod||("extension"in e&&e.extension?e.authMethod="extension":"readOnly"in e&&e.readOnly?e.authMethod="readOnly":e.authMethod="connect"),e.nip05&&isBunkerUrl(e.nip05)&&(e.bunkerUrl=e.nip05,e.nip05=""),"connect"!==e.authMethod||e.signerPubkey||(e.signerPubkey=e.pubkey)},localStorageAddAccount=e=>{localStorageSetItem(LOCAL_STORE_KEY,JSON.stringify(e));const t=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[],n=localStorageGetItem(RECENT_ACCOUNTS)||[];t.forEach((e=>upgradeInfo(e))),n.forEach((e=>upgradeInfo(e)));const r=t,o=t.findIndex((t=>t.pubkey===e.pubkey&&t.authMethod===e.authMethod));-1!==o?r[o]=e:r.push(e);const s=n.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(s)),localStorageSetItem(LOGGED_IN_ACCOUNTS,JSON.stringify(r))},localStorageRemoveCurrentAccount=()=>{const e=localStorageGetItem(LOCAL_STORE_KEY);if(!e)return;upgradeInfo(e);const t={...e};delete t.sk,delete t.otpData;const n=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[],r=localStorageGetItem(RECENT_ACCOUNTS)||[];n.forEach((e=>upgradeInfo(e))),r.forEach((e=>upgradeInfo(e)));const o=r;if("connect"===t.authMethod&&t.bunkerUrl&&t.bunkerUrl.includes("secret="))console.log("nostr login bunker conn with a secret not saved to recent");else if("local"===t.authMethod)console.log("nostr login temporary local keys not save to recent");else{const e=r.findIndex((e=>e.pubkey===t.pubkey&&e.authMethod===t.authMethod));-1!==e?o[e]=t:o.push(t)}const s=n.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(o)),localStorageSetItem(LOGGED_IN_ACCOUNTS,JSON.stringify(s)),localStorageRemoveItem(LOCAL_STORE_KEY)},localStorageRemoveRecent=e=>{const t=localStorageGetItem(RECENT_ACCOUNTS)||[];t.forEach((e=>upgradeInfo(e)));const n=t.filter((t=>t.pubkey!==e.pubkey||t.authMethod!==e.authMethod));localStorageSetItem(RECENT_ACCOUNTS,JSON.stringify(n))},localStorageGetRecents=()=>{const e=localStorageGetItem(RECENT_ACCOUNTS)||[];return e.forEach((e=>upgradeInfo(e))),e},localStorageGetAccounts=()=>{const e=localStorageGetItem(LOGGED_IN_ACCOUNTS)||[];return e.forEach((e=>upgradeInfo(e))),e},localStorageGetCurrent=()=>{const e=localStorageGetItem(LOCAL_STORE_KEY);return e&&upgradeInfo(e),e},getDarkMode=e=>{const t=localStorage.getItem("nl-dark-mode");return t?Boolean(JSON.parse(t)):void 0!==e.darkMode?e.darkMode:!(!window.matchMedia||!window.matchMedia("(prefers-color-scheme: dark)").matches)},getIcon=async()=>document.location.origin+"/favicon.ico";class NostrRpc extends NDKNostrRpc{_ndk;_signer;requests=new Set;sub;_useNip44=!1;constructor(e,t){super(e,t,e.debug.extend("nip46:signer:rpc")),this._ndk=e,this._signer=t}async subscribe(e){return e.kinds=e.kinds?.filter((e=>24133===e)),this.sub=await super.subscribe(e),this.sub}stop(){this.sub&&(this.sub.stop(),this.sub=void 0)}setUseNip44(e){this._useNip44=e}isNip04(e){const t=e.length;return!(t<28)&&("?"===e[t-28]&&"i"===e[t-27]&&"v"===e[t-26]&&"="===e[t-25])}async parseEvent(e){const t=this._ndk.getUser({pubkey:e.pubkey});t.ndk=this._ndk;const n=this.isNip04(e.content)?this._signer.decrypt:this._signer.decryptNip44,r=await n.call(this._signer,t,e.content),o=JSON.parse(r),{id:s,method:i,params:a,result:l,error:c}=o;return i?{id:s,pubkey:e.pubkey,method:i,params:a,event:e}:{id:s,result:l,error:c,event:e}}async parseNostrConnectReply(e,t){const n=new NDKEvent(this._ndk,e),r=await this.parseEvent(n);if(console.log("nostr connect parsedEvent",r),r.method)throw new Error("Bad nostr connect reply");{const e=r;if(e.result!==t)throw new Error(e.error);return n.pubkey}}async listen(e){const t=this._signer.pubkey;console.log("nostr-login listening for conn to",t);const n=await this.subscribe({kinds:[24133],"#p":[t]});return new Promise(((t,r)=>{n.on("event",(async n=>{try{const o=await this.parseEvent(n);if(!o.method){const s=o;if("auth_url"===s.result)return;"ack"===s.result||s.result===e?t(n.pubkey):r(s.error)}}catch(e){console.log("error parsing event",e,n.rawEvent())}this.stop()}))}))}async connect(e,t,n){return new Promise(((r,o)=>{const s=[e,t||"",n||""];this.sendRequest(e,"connect",s,24133,(e=>{"ack"===e.result?r():o(e.error)}))}))}getId(){return Math.random().toString(36).substring(7)}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId();this.setResponseHandler(s,o);const i=await this.createRequestEvent(s,e,t,n,r);console.log("sendRequest",{event:i,method:t,remotePubkey:e,params:n}),await i.publish()}setResponseHandler(e,t){let n=!1;const r=Date.now();return new Promise((()=>{const o=s=>{"auth_url"===s.result?(this.once(`response-${e}`,o),n||(n=!0,this.emit("authUrl",s.error))):t&&this.requests.has(e)&&(this.requests.delete(e),console.log("nostr-login processed nip46 request in",Date.now()-r,"ms"),t(s))};this.once(`response-${e}`,o)}))}async createRequestEvent(e,t,n,r=[],o=24133){this.requests.add(e);const s=await this._signer.user(),i=this._ndk.getUser({pubkey:t}),a={id:e,method:n,params:r},l=new NDKEvent(this._ndk,{kind:o,content:JSON.stringify(a),tags:[["p",t]],pubkey:s.pubkey}),c=this._useNip44&&"create_account"!==n?this._signer.encryptNip44:this._signer.encrypt;return l.content=await c.call(this._signer,i,l.content),await l.sign(this._signer),l}}class IframeNostrRpc extends NostrRpc{peerOrigin;iframePort;iframeRequests=new Map;constructor(e,t,n){super(e,t),this._ndk=e,this.peerOrigin=n}async subscribe(e){return this.peerOrigin?new NDKSubscription(this._ndk,{},{closeOnEose:!0,cacheUsage:NDKSubscriptionCacheUsage.ONLY_CACHE}):super.subscribe(e)}setWorkerIframePort(e){if(!this.peerOrigin)throw new Error("Unexpected iframe port");this.iframePort=e,setInterval((()=>{console.log("iframe-nip46 ping"),this.iframePort.postMessage("ping")}),5e3),e.onmessage=async e=>{if(console.log("iframe-nip46 got response",e.data),"string"==typeof e.data&&e.data.startsWith("errorNoKey")){const t=e.data.split(":")[1],{id:n="",pubkey:r=""}=this.iframeRequests.get(t)||{};n&&r&&this.requests.has(n)&&this.emit(`iframeRestart-${r}`)}else try{const t=e.data;if(!validateEvent(t))throw new Error("Invalid event from iframe");if(!verifySignature(t))throw new Error("Invalid event signature from iframe");const n=new NDKEvent(this._ndk,t),r=await this.parseEvent(n);r.method||(console.log("parsed response",r),this.emit(`response-${r.id}`,r))}catch(t){console.log("error parsing event",t,e.data)}}}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId(),i=await this.createRequestEvent(s,e,t,n,r);this.setResponseHandler(s,o),this.iframePort?(this.iframeRequests.set(i.id,{id:s,pubkey:e}),console.log("iframe-nip46 sending request to",this.peerOrigin,i.rawEvent()),this.iframePort.postMessage(i.rawEvent())):await i.publish()}}class ReadyListener{origin;messages;promise;constructor(e,t){this.origin=t,this.messages=e,this.promise=new Promise((e=>{console.log(new Date,"started listener for",this.messages);const n=async r=>{const o=new URL(t).hostname,s=new URL(r.origin).hostname;(s===o||s.endsWith("."+o))&&Array.isArray(r.data)&&r.data.length&&this.messages.includes(r.data[0])&&(console.log(new Date,"got ready message from",r.origin,r.data),window.removeEventListener("message",n),e(r.data))};window.addEventListener("message",n)}))}async wait(){console.log(new Date,"waiting for",this.messages);const e=await this.promise;return console.log(new Date,"finished waiting for",this.messages,e),e}}class Nip46Signer extends NDKNip46Signer{_userPubkey="";_rpc;constructor(e,t,n,r){super(e,n,t),this._rpc=new IframeNostrRpc(e,t,r),this._rpc.setUseNip44(!0),this._rpc.on("authUrl",(e=>{this.emit("authUrl",e)})),this.rpc=this._rpc}get userPubkey(){return this._userPubkey}async setSignerPubkey(e,t=!1){console.log("setSignerPubkey",e),this.remotePubkey=e,this._rpc.on(`iframeRestart-${e}`,(()=>{this.emit("iframeRestart")})),await this.initUserPubkey(t?e:"")}async initUserPubkey(e){if(this._userPubkey)throw new Error("Already called initUserPubkey");this._userPubkey=e||await new Promise(((e,t)=>{if(!this.remotePubkey)throw new Error("Signer pubkey not set");console.log("get_public_key",this.remotePubkey),this._rpc.sendRequest(this.remotePubkey,"get_public_key",[],24133,(t=>{e(t.result)}))}))}async listen(e){const t=await this.rpc.listen(e);await this.setSignerPubkey(t)}async connect(e,t){if(!this.remotePubkey)throw new Error("No signer pubkey");await this._rpc.connect(this.remotePubkey,e,t),await this.setSignerPubkey(this.remotePubkey)}async setListenReply(e,t){const n=await this._rpc.parseNostrConnectReply(e,t);await this.setSignerPubkey(n,!0)}async createAccount2({bunkerPubkey:e,name:t,domain:n,perms:r=""}){const o=[t,n,"",r],s=await new Promise((t=>{this.rpc.sendRequest(e,"create_account",o,void 0,t)}));if(console.log("create_account pubkey",s),"error"===s.result)throw new Error(s.error);return s.result}}class BannerManager extends lib$1.EventEmitter{banner=null;iframeReady;params;constructor(e){super(),this.params=e}onAuthUrl(e,t){this.banner&&(this.banner.notify=e?{mode:t?"iframeAuthUrl":"authUrl",url:e}:{mode:""})}onIframeRestart(e){this.banner&&(this.iframeReady=new ReadyListener(["rebinderDone","rebinderError"],new URL(e).origin),this.banner.notify={mode:"rebind",url:e})}onUserInfo(e){this.banner&&(this.banner.userInfo=e)}onCallTimeout(){this.banner&&(this.banner.notify={mode:"timeout"})}onCallStart(){this.banner&&(this.banner.isLoading=!0)}async onCallEnd(){this.banner&&(this.iframeReady&&(await this.iframeReady.wait(),this.iframeReady=void 0),this.banner.isLoading=!1,this.banner.notify={mode:""})}onUpdateAccounts(e){this.banner&&(this.banner.accounts=e)}onDarkMode(e){this.banner&&(this.banner.darkMode=e)}launchAuthBanner(e){this.banner=document.createElement("nl-banner"),this.banner.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.banner.setAttribute("theme",e.theme),e.noBanner&&this.banner.setAttribute("hidden-mode","true"),this.banner.addEventListener("handleLoginBanner",(e=>{this.emit("launch",e.detail)})),this.banner.addEventListener("handleConfirmLogout",(()=>{this.emit("onConfirmLogout")})),this.banner.addEventListener("handleLogoutBanner",(async()=>{this.emit("logout")})),this.banner.addEventListener("handleImportModal",(e=>{this.emit("import")})),this.banner.addEventListener("handleNotifyConfirmBanner",(e=>{this.emit("onAuthUrlClick",e.detail)})),this.banner.addEventListener("handleNotifyConfirmBannerIframe",(e=>{this.emit("onIframeAuthUrlClick",e.detail)})),this.banner.addEventListener("handleSwitchAccount",(e=>{this.emit("onSwitchAccount",e.detail)})),this.banner.addEventListener("handleOpenWelcomeModal",(()=>{this.emit("launch"),this.banner&&(this.banner.isOpen=!1)})),document.body.appendChild(this.banner)}}function extract(e,t,n){return hash$1(e),hmac$1(e,toBytes$1(n),toBytes$1(t))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,n,r=32){if(hash$1(e),number$1(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/e.outputLen);void 0===n&&(n=EMPTY_BUFFER);const s=new Uint8Array(o*e.outputLen),i=hmac$1.create(e,t),a=i._cloneInto(),l=new Uint8Array(i.outputLen);for(let t=0;t<o;t++)HKDF_COUNTER[0]=t+1,a.update(0===t?EMPTY_BUFFER:l).update(n).update(HKDF_COUNTER).digestInto(l),s.set(l,e.outputLen*t),i._cloneInto(a);return i.destroy(),a.destroy(),l.fill(0),HKDF_COUNTER.fill(0),s.slice(0,r)}const decoder=new TextDecoder,u={minPlaintextSize:1,maxPlaintextSize:65535,utf8Encode:utf8ToBytes$1,utf8Decode:e=>decoder.decode(e),getConversationKey(e,t){const n=secp256k1.getSharedSecret(e,"02"+t).subarray(1,33);return extract(sha256,n,"nip44-v2")},getMessageKeys(e,t){const n=expand(sha256,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}},calcPaddedLen(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)},writeU16BE(e){if(!Number.isSafeInteger(e)||e<u.minPlaintextSize||e>u.maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t},pad(e){const t=u.utf8Encode(e),n=t.length;return concatBytes(u.writeU16BE(n),t,new Uint8Array(u.calcPaddedLen(n)-n))},unpad(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<u.minPlaintextSize||t>u.maxPlaintextSize||n.length!==t||e.length!==2+u.calcPaddedLen(t))throw new Error("invalid padding");return u.utf8Decode(n)},hmacAad(e,t,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const r=concatBytes(n,t);return hmac$1(sha256,e,r)},decodePayload(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let n;try{n=base64.decode(e)}catch(e){throw new Error("invalid base64: "+e.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const o=n[0];if(2!==o)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}};function encryptNip44(e,t,n=randomBytes(32)){const{chacha_key:r,chacha_nonce:o,hmac_key:s}=u.getMessageKeys(t,n),i=u.pad(e),a=chacha20(r,o,i),l=u.hmacAad(s,a,n);return base64.encode(concatBytes(new Uint8Array([2]),n,a,l))}function decryptNip44(e,t){const{nonce:n,ciphertext:r,mac:o}=u.decodePayload(e),{chacha_key:s,chacha_nonce:i,hmac_key:a}=u.getMessageKeys(t,n);if(!equalBytes(u.hmacAad(a,r,n),o))throw new Error("invalid MAC");const l=chacha20(s,i,r);return u.unpad(l)}class Nip44{cache=new Map;createKey(e,t){return u.getConversationKey(e,t)}getKey(e,t,n){const r=getPublicKey(e)+t;let o=this.cache.get(r);if(o)return o;const s=this.createKey(e,t);return this.cache.set(r,s),s}encrypt(e,t,n){return encryptNip44(n,this.getKey(e,t))}decrypt(e,t,n){return decryptNip44(n,this.getKey(e,t))}}class PrivateKeySigner extends NDKPrivateKeySigner{nip44=new Nip44;_pubkey;constructor(e){super(e),this._pubkey=getPublicKey(e)}get pubkey(){return this._pubkey}encryptNip44(e,t){return Promise.resolve(this.nip44.encrypt(this.privateKey,e.pubkey,t))}decryptNip44(e,t){return Promise.resolve(this.nip44.decrypt(this.privateKey,e.pubkey,t))}}class AmberDirectSigner{_pubkey="";constructor(e){this._pubkey=e||""}get pubkey(){return this._pubkey}set pubkey(e){this._pubkey=e}nip04={encrypt:(e,t)=>this.encrypt04(e,t),decrypt:(e,t)=>this.decrypt04(e,t)};nip44={encrypt:(e,t)=>this.encrypt44(e,t),decrypt:(e,t)=>this.decrypt44(e,t)};async signEvent(e){const t=Math.random().toString(36).substring(7),n=this.generateUrl(JSON.stringify(e),"sign_event",t);return window.location.href=n,new Promise((()=>{}))}async encrypt04(e,t){const n=Math.random().toString(36).substring(7),r=this.generateUrl(t,"nip04_encrypt",n,e);return window.location.href=r,new Promise((()=>{}))}async decrypt04(e,t){const n=Math.random().toString(36).substring(7),r=this.generateUrl(t,"nip04_decrypt",n,e);return window.location.href=r,new Promise((()=>{}))}async encrypt44(e,t){const n=Math.random().toString(36).substring(7),r=this.generateUrl(t,"nip44_encrypt",n,e);return window.location.href=r,new Promise((()=>{}))}async decrypt44(e,t){const n=Math.random().toString(36).substring(7),r=this.generateUrl(t,"nip44_decrypt",n,e);return window.location.href=r,new Promise((()=>{}))}async getPublicKey(){const e=Math.random().toString(36).substring(7),t=this.generateUrl("","get_public_key",e);return window.location.href=t,new Promise((()=>{}))}generateUrl(e,t,n,r){const o=new URL(window.location.href);o.searchParams.set("amberType",t),o.searchParams.set("amberId",n);const s=new URLSearchParams;return s.set("type",t),s.set("id",n),s.set("callbackUrl",o.toString()),this._pubkey&&s.set("pubkey",this._pubkey),r&&s.set("pubkey",r),`nostrsigner:${encodeURIComponent(e)}?${s.toString()}`}static parseResponse(){const e=new URLSearchParams(window.location.search),t=e.get("amberType"),n=e.get("amberId"),r=e.get("signature")||e.get("result");if(t&&n&&r){const e=new URL(window.location.href);return e.searchParams.delete("amberType"),e.searchParams.delete("amberId"),e.searchParams.delete("signature"),e.searchParams.delete("result"),window.history.replaceState({},"",e.toString()),{type:t,id:n,result:r}}return null}}const OUTBOX_RELAYS=["wss://user.kindpag.es","wss://purplepag.es","wss://relay.nos.social"],DEFAULT_NOSTRCONNECT_RELAYS=["wss://relay.nsec.app/","wss://ephemeral.snowflare.cc/"],CONNECT_TIMEOUT=5e3,NOSTRCONNECT_APPS=[{name:"Nsec.app",domain:"nsec.app",canImport:!0,img:"https://nsec.app/assets/favicon.ico",link:"https://use.nsec.app/<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS},{name:"Amber",img:"https://raw.githubusercontent.com/greenart7c3/Amber/refs/heads/master/assets/android-icon.svg",link:"<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS},{name:"Amber (Direct)",img:"https://raw.githubusercontent.com/greenart7c3/Amber/refs/heads/master/assets/android-icon.svg",link:"amber",relays:DEFAULT_NOSTRCONNECT_RELAYS},{name:"Other key stores",img:"",link:"<nostrconnect>",relays:DEFAULT_NOSTRCONNECT_RELAYS}];class AuthNostrService extends lib$1.EventEmitter{ndk;profileNdk;signer=null;amberSigner=null;localSigner=null;params;signerPromise;signerErrCallback;readyPromise;readyCallback;nip44Codec=new Nip44;nostrConnectKey="";nostrConnectSecret="";iframe;starterReady;nip04;nip44;constructor(e){super(),this.params=e,this.ndk=new NDK({enableOutboxModel:!1}),this.profileNdk=new NDK({enableOutboxModel:!0,explicitRelayUrls:OUTBOX_RELAYS}),this.profileNdk.connect(CONNECT_TIMEOUT),this.nip04={encrypt:this.encrypt04.bind(this),decrypt:this.decrypt04.bind(this)},this.nip44={encrypt:this.encrypt44.bind(this),decrypt:this.decrypt44.bind(this)},this.checkAmberResponse()}checkAmberResponse(){const e=AmberDirectSigner.parseResponse();if(e)if("get_public_key"===e.type){const t={pubkey:e.result,authMethod:"amber"};this.onAuth("login",t)}else console.log("Amber response",e),e.type}isIframe(){return!!this.iframe}async waitReady(){if(this.signerPromise)try{await this.signerPromise}catch{}if(this.readyPromise)try{await this.readyPromise}catch{}}cancelNostrConnect(){this.releaseSigner(),this.resetAuth()}async nostrConnect(e,{domain:t="",link:n="",iframeUrl:r="",importConnect:o=!1}={}){e=e&&e.length>0?e:DEFAULT_NOSTRCONNECT_RELAYS;const s={authMethod:"connect",pubkey:"",signerPubkey:"",sk:this.nostrConnectKey,domain:t,relays:e,iframeUrl:r};if(console.log("nostrconnect info",s,n),n&&!r){if("amber"===n){return(new AmberDirectSigner).getPublicKey()}window.open(n,"_blank","width=400,height=700")}if(await this.initSigner(s,{listen:!0}),!s.pubkey||!s.signerPubkey)throw new Error("Bad remote pubkey");return s.bunkerUrl=`bunker://${s.signerPubkey}?${e.map(((e,t)=>`${0!==t?"&":""}relay=${e}`))}`,o||this.onAuth("login",s),s}async createNostrConnect(e){this.nostrConnectKey=generatePrivateKey(),this.nostrConnectSecret=Math.random().toString(36).substring(7);const t=getPublicKey(this.nostrConnectKey),n=encodeURIComponent(document.location.host),r=encodeURIComponent(document.location.origin);return`nostrconnect://${t}?image=${encodeURIComponent(await getIcon())}&url=${r}&name=${n}&perms=${encodeURIComponent(this.params.optionsModal.perms||"")}&secret=${this.nostrConnectSecret}${(e||[]).length>0?(e||[]).map(((e,t)=>`&relay=${e}`)):""}`}async getNostrConnectServices(){const e=await this.createNostrConnect(),t=NOSTRCONNECT_APPS.map((e=>({...e})));for(const n of t){let t=[...DEFAULT_NOSTRCONNECT_RELAYS];if(n.link.startsWith("https://")){const e=n.domain||new URL(n.link).hostname;try{const r=await(await fetch(`https://${e}/.well-known/nostr.json`)).json(),o=r.names._,s=r.nip46?.[o];Array.isArray(s)&&s.length>0&&(t=s),n.iframeUrl=r.nip46?.iframe_url||""}catch(e){console.log("Bad app info",e,n)}}const r=e+t.map((e=>e.replace(/['"]/g,""))).map((e=>`&relay=${encodeURIComponent(e)}`)).join("");n.iframeUrl?n.link=r:n.link=n.link.replace("<nostrconnect>",r)}return[e,t]}async localSignup(e,t){const n=!t,r={pubkey:getPublicKey(t=t||generatePrivateKey()),sk:t,name:e,authMethod:"local"};console.log(`localSignup name: ${e}`),await this.setLocal(r,n)}async setLocal(e,t){this.releaseSigner(),this.localSigner=new PrivateKeySigner(e.sk),t&&await createProfile(e,this.profileNdk,this.localSigner,this.params.optionsModal.signupRelays,this.params.optionsModal.outboxRelays),this.onAuth(t?"signup":"login",e)}prepareImportUrl(e){if("otp"===this.params.userInfo?.authMethod)return e+"&import=true";if(!this.localSigner||"local"!==this.params.userInfo?.authMethod)throw new Error("Most be local keys");return e+"#import="+nip19_exports.nsecEncode(this.localSigner.privateKey)}async importAndConnect(e){const{relays:t,domain:n,link:r,iframeUrl:o}=e;if(!n)throw new Error("Domain required");const s=await this.nostrConnect(t,{domain:n,link:r,importConnect:!0,iframeUrl:o});await this.logout(!0),this.localSigner=null,this.onAuth("login",s)}setReadOnly(e){const t={pubkey:e,authMethod:"readOnly"};this.onAuth("login",t)}setExtension(e){const t={pubkey:e,authMethod:"extension"};this.onAuth("login",t)}setOTP(e,t){const n={pubkey:e,authMethod:"otp",otpData:t};this.onAuth("login",n)}async setConnect(e){this.releaseSigner(),await this.startAuth(),await this.initSigner(e),this.onAuth("login",e),await this.endAuth()}async setAmber(e){this.releaseSigner(),this.amberSigner=new AmberDirectSigner(e.pubkey),this.onAuth("login",e)}async createAccount(e){const[t,n]=e.split("@"),r=await getBunkerUrl(`_@${n}`,this.params.optionsModal);console.log("create account bunker's url",r);const o=bunkerUrlToInfo(r);if(!o.signerPubkey)throw new Error("Bad bunker url");const s=Boolean(this.params.userInfo);await this.initSigner(o,{eventToAddAccount:s});return{bunkerUrl:`bunker://${await this.signer.createAccount2({bunkerPubkey:o.signerPubkey,name:t,domain:n,perms:this.params.optionsModal.perms})}?`+(o.relays??[]).map((e=>`relay=${encodeURIComponent(e)}`)).join("&"),sk:o.sk}}releaseSigner(){this.signer=null,this.signerErrCallback?.("cancelled"),this.localSigner=null,this.amberSigner=null;for(const e of this.ndk.pool.relays.keys())this.ndk.pool.removeRelay(e)}async logout(e=!1){e||this.releaseSigner(),localStorageRemoveCurrentAccount(),this.onAuth("logout"),this.emit("updateAccounts")}setUserInfo(e){this.params.userInfo=e,this.emit("onUserInfo",e),e&&(localStorageAddAccount(e),this.emit("updateAccounts"))}exportKeys(){return this.params.userInfo?"local"!==this.params.userInfo.authMethod?"":nip19_exports.nsecEncode(this.params.userInfo.sk):""}onAuth(e,t=null){if("logout"!==e&&!t)throw new Error("No user info in onAuth");if(t&&this.params.userInfo&&(t.pubkey!==this.params.userInfo.pubkey||t.authMethod!==this.params.userInfo.authMethod)){const e=new CustomEvent("nlAuth",{detail:{type:"logout"}});console.log("nostr-login auth",e.detail),document.dispatchEvent(e)}this.setUserInfo(t),t&&fetchProfile(t,this.profileNdk).then((e=>{if(this.params.userInfo!==t)return;const n={...this.params.userInfo,picture:e?.image||e?.picture,name:e?.name||e?.displayName||e?.nip05||nip19_exports.npubEncode(t.pubkey)};this.setUserInfo(n)}));try{const n=t?nip19_exports.npubEncode(t.pubkey):"",r={type:e};"logout"===e?(this.iframe&&this.iframe.remove(),this.iframe=void 0):(r.pubkey=t.pubkey,r.name=t.name,t.sk&&(r.localNsec=nip19_exports.nsecEncode(t.sk)),t.relays&&(r.relays=t.relays),t.otpData&&(r.otpData=t.otpData),r.method=t.authMethod||"connect");const o=new CustomEvent("nlAuth",{detail:r});console.log("nostr-login auth",r),document.dispatchEvent(o),this.params.optionsModal.onAuth&&this.params.optionsModal.onAuth(n,r)}catch(e){console.log("onAuth error",e)}}async createIframe(e){if(!e)return;const t=new URL(e);let n;const r="__nostr-login-worker-iframe-"+t.hostname.replaceAll(".","-");n=document.querySelector(`#${r}`),console.log("iframe",r,n),n||(n=document.createElement("iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.setAttribute("border","0"),n.style.display="none",n.id=r,document.body.append(n)),n.setAttribute("src",e);const o=new ReadyListener(["workerReady","workerError"],t.origin);await new Promise((e=>{n.addEventListener("load",e)}));const s=await o.wait();return console.log("nostr-login iframe ready",e,s),{iframe:n,port:s[1]}}async sendNeedAuth(){const[e]=await this.getNostrConnectServices(),t=new CustomEvent("nlNeedAuth",{detail:{nostrconnect:e}});console.log("nostr-login need auth",e),document.dispatchEvent(t)}isAuthing(){return!!this.readyCallback}async startAuth(){if(console.log("startAuth"),this.readyCallback)throw new Error("Already started");this.readyPromise=new Promise((e=>this.readyCallback=e))}async endAuth(){if(console.log("endAuth",this.params.userInfo),this.params.userInfo&&this.params.userInfo.iframeUrl){const{iframe:e,port:t}=await this.createIframe(this.params.userInfo.iframeUrl)||{};if(this.iframe=e,!this.iframe||!t)return;this.signer.rpc.setWorkerIframePort(t)}this.readyCallback(),this.readyCallback=void 0}resetAuth(){this.readyCallback&&this.readyCallback(),this.readyCallback=void 0}async listen(e){if(!e.iframeUrl)return this.signer.listen(this.nostrConnectSecret);const t=await this.starterReady.wait();if("starterError"===t[0])throw new Error(t[1]);return this.signer.setListenReply(t[1],this.nostrConnectSecret)}async connect(e,t){return this.signer.connect(e.token,t)}async initSigner(e,{listen:t=!1,connect:n=!1,eventToAddAccount:r=!1}={}){if(this.signerPromise)try{await this.signerPromise}catch{}console.log("initSigner info",e);const o=e.iframeUrl?new URL(e.iframeUrl).origin:void 0;return o&&(this.starterReady=new ReadyListener(["starterDone","starterError"],o)),this.emit("onIframeUrl",e.iframeUrl),this.signerPromise=new Promise((async(s,i)=>{this.signerErrCallback=i;try{if(e.relays&&!e.iframeUrl)for(const t of e.relays)this.ndk.addExplicitRelay(t,void 0);await this.ndk.connect(CONNECT_TIMEOUT);const i=new PrivateKeySigner(e.sk);this.signer=new Nip46Signer(this.ndk,i,e.signerPubkey,o),this.signer.on("iframeRestart",(async()=>{const t=e.iframeUrl+(e.iframeUrl.includes("?")?"&":"?")+"pubkey="+e.pubkey+"&rebind="+i.pubkey;this.emit("iframeRestart",{pubkey:e.pubkey,iframeUrl:t})})),this.signer.on("authUrl",(t=>{console.log("nostr login auth url",t),this.emit("onAuthUrl",{url:t,iframeUrl:e.iframeUrl,eventToAddAccount:r})})),t?await this.listen(e):n?await this.connect(e,this.params.optionsModal.perms):await this.signer.initUserPubkey(e.pubkey),e.pubkey=this.signer.userPubkey,e.signerPubkey=this.signer.remotePubkey,s()}catch(e){console.log("initSigner failure",e),this.signer=null,i(e)}})),this.signerPromise}async authNip46(e,{name:t,bunkerUrl:n,sk:r="",domain:o="",iframeUrl:s=""}){try{const i=bunkerUrlToInfo(n,r);if(isBunkerUrl(t)?i.bunkerUrl=t:(i.nip05=t,i.domain=t.split("@")[1]),o&&(i.domain=o),s&&(i.iframeUrl=s),!i.signerPubkey||!i.sk||!i.relays||0===i.relays.length)throw new Error(`Bad bunker url ${n}`);const a=Boolean(this.params.userInfo);console.log("authNip46",e,i),await this.initSigner(i,{connect:!0,eventToAddAccount:a}),this.onAuth(e,i)}catch(e){throw console.log("nostr login auth failed",e),e}}async signEvent(e){const t=(async()=>{if(this.localSigner)e.pubkey=getPublicKey(this.localSigner.privateKey),e.id=getEventHash(e),e.sig=await this.localSigner.sign(e);else{if("amber"===this.params.userInfo?.authMethod){const t=this.params.userInfo;return this.amberSigner||(this.amberSigner=new AmberDirectSigner(t.pubkey)),this.amberSigner.signEvent(e)}e.pubkey=this.signer?.remotePubkey,e.id=getEventHash(e),e.sig=await(this.signer?.sign(e))}return e})(),n=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Sign timeout"))),2e4)})),r=await Promise.race([t,n]);return console.log("signed",{event:r}),r}async codec_call(e,t,n){return new Promise(((r,o)=>{this.signer.rpc.sendRequest(this.signer.remotePubkey,e,[t,n],24133,(e=>{e.error?o(e.error):r(e.result)}))}))}async encrypt04(e,t){if(this.localSigner)return this.localSigner.encrypt(new NDKUser({pubkey:e}),t);if("amber"===this.params.userInfo?.authMethod){const n=this.params.userInfo;return this.amberSigner||(this.amberSigner=new AmberDirectSigner(n.pubkey)),this.amberSigner.encrypt04(e,t)}return this.signer.encrypt(new NDKUser({pubkey:e}),t)}async decrypt04(e,t){if(this.localSigner)return this.localSigner.decrypt(new NDKUser({pubkey:e}),t);if("amber"===this.params.userInfo?.authMethod){const n=this.params.userInfo;return this.amberSigner||(this.amberSigner=new AmberDirectSigner(n.pubkey)),this.amberSigner.decrypt04(e,t)}return this.codec_call("nip04_decrypt",e,t)}async encrypt44(e,t){if(this.localSigner)return this.nip44Codec.encrypt(this.localSigner.privateKey,e,t);if("amber"===this.params.userInfo?.authMethod){const n=this.params.userInfo;return this.amberSigner||(this.amberSigner=new AmberDirectSigner(n.pubkey)),this.amberSigner.encrypt44(e,t)}return this.codec_call("nip44_encrypt",e,t)}async decrypt44(e,t){if(this.localSigner)return this.nip44Codec.decrypt(this.localSigner.privateKey,e,t);if("amber"===this.params.userInfo?.authMethod){const n=this.params.userInfo;return this.amberSigner||(this.amberSigner=new AmberDirectSigner(n.pubkey)),this.amberSigner.decrypt44(e,t)}return this.codec_call("nip44_decrypt",e,t)}}class ModalManager extends lib$1.EventEmitter{modal=null;params;extensionService;authNostrService;launcherPromise;accounts=[];recents=[];opt;constructor(e,t,n){super(),this.params=e,this.extensionService=n,this.authNostrService=t}async waitReady(){if(this.launcherPromise){try{await this.launcherPromise}catch{}this.launcherPromise=void 0}}async launch(e){console.log("nostr-login launch",e),this.launcherPromise&&await this.waitReady(),this.authNostrService.isAuthing()&&this.authNostrService.resetAuth(),this.opt=e;const t=document.createElement("dialog");if(this.modal=document.createElement("nl-auth"),this.modal.accounts=this.accounts,this.modal.recents=this.recents,this.modal.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.modal.setAttribute("theme",e.theme),e.startScreen&&this.modal.setAttribute("start-screen",e.startScreen),e.bunkers)this.modal.setAttribute("bunkers",e.bunkers);else{let e="nsec.app,highlighter.com";this.modal.setAttribute("bunkers",e)}void 0!==e.methods&&(this.modal.authMethods=e.methods),void 0!==e.localSignup&&(this.modal.localSignup=e.localSignup),void 0!==e.signupNstart&&(this.modal.signupNjump=e.signupNstart),e.title&&(this.modal.welcomeTitle=e.title),e.description&&(this.modal.welcomeDescription=e.description),this.modal.hasExtension=this.extensionService.hasExtension(),this.modal.hasOTP=!!e.otpRequestUrl&&!!e.otpReplyUrl,this.modal.isLoadingExtension=!1,this.modal.isLoading=!1,[this.modal.connectionString,this.modal.connectionStringServices]=await this.authNostrService.getNostrConnectServices(),t.appendChild(this.modal),document.body.appendChild(t);let n="";return this.launcherPromise=new Promise(((e,r)=>{t.addEventListener("close",(()=>{r(new Error("Closed")),this.authNostrService.resetAuth(),this.modal&&(document.body.removeChild(this.modal.parentNode),this.modal=null)}));const o=async e=>{this.modal&&(this.modal.isLoading=!1),await this.authNostrService.endAuth(),t.close(),this.modal=null,e()},s=async(t,n)=>{this.modal&&(this.modal.isLoading=!0);try{n&&!n.start||await this.authNostrService.startAuth(),await t(),n&&!n.end||await o(e)}catch(e){console.log("error",e),this.modal&&(this.modal.isLoading=!1,this.modal.authUrl="",this.modal.iframeUrl="","cancelled"!==e&&(this.modal.error=e.toString()))}},i=async(e,t)=>{await s((async()=>{const n=await getBunkerUrl(e,this.params.optionsModal);await this.authNostrService.authNip46("login",{name:e,bunkerUrl:n,domain:t})}))},a=async e=>{await s((async()=>{const{bunkerUrl:t,sk:n}=await this.authNostrService.createAccount(e);await this.authNostrService.authNip46("signup",{name:e,bunkerUrl:t,sk:n})}))},l=async()=>{try{await navigator.clipboard.writeText(this.authNostrService.exportKeys()),localStorageSetItem("backupKey","true")}catch(e){console.error("Failed to copy to clipboard: ",e)}},c=async e=>{await s((async()=>{const{iframeUrl:t}=e;e.link=this.authNostrService.prepareImportUrl(e.link),this.modal&&t&&(this.modal.authUrl=e.link,this.modal.iframeUrl=t,this.modal.isLoading=!1,console.log("nostrconnect authUrl",this.modal.authUrl,this.modal.iframeUrl)),await this.authNostrService.importAndConnect(e)}))},d=async e=>{await s((async()=>{const{relays:t,domain:n,link:r,iframeUrl:o}=e||{};console.log("nostrConnect",e,t,n,r,o),this.modal&&(o&&(this.modal.authUrl=r,this.modal.iframeUrl=o,this.modal.isLoading=!1,console.log("nostrconnect authUrl",this.modal.authUrl,this.modal.iframeUrl)),e||(this.modal.isLoading=!1)),await this.authNostrService.nostrConnect(t,{domain:n,link:r,iframeUrl:o})}))},h=async e=>{await s((async()=>{if(!e)throw new Error("Please enter some nickname");await this.authNostrService.localSignup(e)}))},u=async()=>{await s((async()=>{const e=new URL(window.location.href),t=e.hostname.toLocaleLowerCase().replace(/^www\./i,"").charAt(0).toUpperCase()+e.hostname.slice(1),n=prepareSignupRelays(this.params.optionsModal.signupRelays);return this.modal.njumpIframe=`\n <html><body>\n <script src='https://start.njump.me/modal.js'><\/script>\n <script>\n new NstartModal({\n baseUrl: 'https://start.njump.me',\n // Required parameters\n an: '${t}',\n // Optional parameters\n s: [${this.opt.followNpubs?`'${this.opt.followNpubs}'`:""}],\n afb: false, // forceBunker\n asb: false, // skipBunker\n aan: false, // avoidNsec\n aac: true, // avoidNcryptsec\n ahc: true, // hide close button\n arr: ${JSON.stringify(n)}, //readRelays\n awr: ${JSON.stringify(n)}, //writeRelays\n // Callbacks\n onComplete: (result) => {\n console.log('Login token:', result.nostrLogin);\n window.parent.location.href='${window.location.href}#nostr-login='+result.nostrLogin;\n },\n onCancel: () => {\n window.parent.location.href='${window.location.href}#nostr-login=null';\n },\n }).open();\n <\/script>\n </body></html>\n `.replaceAll("&","&"),new Promise(((e,t)=>{const n=async n=>{if(console.log("nsecOrBunker",n),n.startsWith("nsec1")){let t;try{t=nip19_exports.decode(n)}catch(e){throw new Error("Bad nsec value")}if("nsec"!==t.type)throw new Error("Bad bech32 type");await this.authNostrService.localSignup("",t.data),e()}else n.startsWith("bunker:")?(await this.authNostrService.authNip46("login",{name:"",bunkerUrl:n}),e()):t("null"===n?"Cancelled":"Unknown return value")};window.addEventListener("hashchange",(async()=>{if(window.location.hash.startsWith("#nostr-login=")){const e=window.location.hash.split("#nostr-login=")[1],t=new URL(window.location.toString());t.hash="",window.history.replaceState({},"",t.toString()),n(e)}}))}))}))};if(!this.modal)throw new Error("WTH?");this.modal.addEventListener("handleContinue",(()=>{this.modal&&(this.modal.isLoading=!0,this.emit("onAuthUrlClick",this.modal.authUrl))})),this.modal.addEventListener("nlLogin",(e=>{i(e.detail)})),this.modal.addEventListener("nlSignup",(e=>{a(e.detail)})),this.modal.addEventListener("nlLocalSignup",(e=>{h(e.detail)})),this.modal.addEventListener("nlSignupNjump",(e=>{u()})),this.modal.addEventListener("nlImportAccount",(e=>{c(e.detail)})),this.modal.addEventListener("nlExportKeys",(e=>{l()})),this.modal.addEventListener("handleLogoutBanner",(()=>{this.emit("onLogoutBanner")})),this.modal.addEventListener("nlNostrConnect",(e=>{d(e.detail)})),this.modal.addEventListener("nlNostrConnectDefault",(()=>{this.authNostrService.isAuthing()||d()})),this.modal.addEventListener("nlNostrConnectDefaultCancel",(()=>{console.log("nlNostrConnectDefaultCancel"),this.authNostrService.cancelNostrConnect()})),this.modal.addEventListener("nlSwitchAccount",(e=>{const n=e.detail;this.emit("onSwitchAccount",n),setTimeout((()=>t.close()),300)})),this.modal.addEventListener("nlLoginRecentAccount",(async e=>{const n=e.detail;if("readOnly"===n.authMethod)this.authNostrService.setReadOnly(n.pubkey),t.close();else if("otp"===n.authMethod)try{this.modal.dispatchEvent(new CustomEvent("nlLoginOTPUser",{detail:n.nip05||n.pubkey}))}catch(e){console.error(e)}else if("extension"===n.authMethod)await this.extensionService.trySetExtensionForPubkey(n.pubkey),t.close();else if("amber"===n.authMethod)this.authNostrService.setAmber(n),t.close();else{const e=n.bunkerUrl||n.nip05;if(!e)throw new Error("Bad connect info");i(e,n.domain)}})),this.modal.addEventListener("nlRemoveRecent",(e=>{localStorageRemoveRecent(e.detail),this.emit("updateAccounts")}));const p=async e=>{let t="";if(e.includes("@")){const{error:n,pubkey:r}=await checkNip05(e);if(!r)throw new Error(n);t=r}else if(e.startsWith("npub")){const{type:n,data:r}=nip19_exports.decode(e);if("npub"!==n)throw new Error("Bad npub");t=r}else 64===e.trim().length&&(t=e.trim(),nip19_exports.npubEncode(t));return t};this.modal.addEventListener("nlLoginReadOnly",(async e=>{await s((async()=>{const t=e.detail,n=await p(t);this.authNostrService.setReadOnly(n)}))})),this.modal.addEventListener("nlLoginExtension",(async()=>{if(!this.extensionService.hasExtension())throw new Error("No extension");await s((async()=>{this.modal&&(this.modal.isLoadingExtension=!0,await this.extensionService.setExtension(),this.modal.isLoadingExtension=!1)}))})),this.modal.addEventListener("nlLoginOTPUser",(async e=>{await s((async()=>{if(!this.modal)return;const t=e.detail,r=await p(t),o=this.opt.otpRequestUrl+(this.opt.otpRequestUrl.includes("?")?"&":"?")+"pubkey="+r,s=await fetch(o);if(200!==s.status)throw console.warn("nostr-login: bad otp reply",s),new Error("Failed to send DM");this.modal.isOTP=!0,n=r,this.modal.isLoading=!1}),{start:!0})})),this.modal.addEventListener("nlLoginOTPCode",(async e=>{await s((async()=>{if(!this.modal)return;const t=e.detail,r=this.opt.otpReplyUrl+(this.opt.otpRequestUrl.includes("?")?"&":"?")+"pubkey="+n+"&code="+t,o=await fetch(r);if(200!==o.status)throw console.warn("nostr-login: bad otp reply",o),new Error("Invalid code");const s=await o.text();this.authNostrService.setOTP(n,s),this.modal.isOTP=!1}),{end:!0})})),this.modal.addEventListener("nlCheckSignup",(async e=>{const{available:t,taken:n,error:r}=await checkNip05(e.detail);this.modal&&(this.modal.error=String(r),!r&&n&&(this.modal.error="Already taken"),this.modal.signupNameIsAvailable=t)})),this.modal.addEventListener("nlCheckLogin",(async e=>{const{available:t,taken:n,error:r}=await checkNip05(e.detail);this.modal&&(this.modal.error=String(r),t&&(this.modal.error="Name not found"),this.modal.loginIsGood=n)}));const f=()=>{this.modal&&(this.modal.isLoading=!1),t.close(),r(new Error("Cancelled"))};this.modal.addEventListener("stopFetchHandler",f),this.modal.addEventListener("nlCloseModal",f),this.modal.addEventListener("nlChangeDarkMode",(e=>{setDarkMode(e.detail),document.dispatchEvent(new CustomEvent("nlDarkMode",{detail:e.detail}))})),this.on("onIframeAuthUrlCallEnd",(()=>{t.close(),this.modal=null,e()})),t.showModal()})),this.launcherPromise}async showIframeUrl(e){await this.waitReady(),this.launch({startScreen:"iframe"}).catch((()=>console.log("closed auth iframe"))),this.modal.authUrl=e}connectModals(e){const t=async e=>{await this.launch(e)},n=document.getElementsByTagName("nl-button");for(let r=0;r<n.length;r++){const o=n[r].getAttribute("nl-theme"),s=n[r].getAttribute("start-screen"),i={...e};switch(o&&(i.theme=o),s){case"login":case"login-bunker-url":case"login-read-only":case"signup":case"switch-account":case"welcome":i.startScreen=s}n[r].addEventListener("click",(function(){t(i)}))}}onAuthUrl(e){this.modal&&(this.modal.authUrl=e,this.modal.isLoading=!1)}onIframeUrl(e){this.modal&&(console.log("modal iframe url",e),this.modal.iframeUrl=e)}onCallEnd(){this.modal&&this.modal.authUrl&&this.params.userInfo?.iframeUrl&&this.emit("onIframeAuthUrlCallEnd")}onUpdateAccounts(e,t){this.accounts=e,this.recents=t,this.modal&&(this.modal.accounts=e,this.modal.recents=t)}onDarkMode(e){this.modal&&(this.modal.darkMode=e)}}class Nostr{#e;nip04;nip44;constructor(e){this.#e=e,this.getPublicKey=this.getPublicKey.bind(this),this.signEvent=this.signEvent.bind(this),this.getRelays=this.getRelays.bind(this),this.nip04={encrypt:this.encrypt04.bind(this),decrypt:this.decrypt04.bind(this)},this.nip44={encrypt:this.encrypt44.bind(this),decrypt:this.decrypt44.bind(this)}}async ensureAuth(){if(await this.#e.waitReady(),!this.#e.getUserInfo()&&(await this.#e.launch(),!this.#e.getUserInfo()))throw new Error("Rejected by user")}async getPublicKey(){await this.ensureAuth();const e=this.#e.getUserInfo();if(e)return e.pubkey;throw new Error("No user")}async signEvent(e){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().signEvent(e)))}async getRelays(){return{}}async encrypt04(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip04.encrypt(e,t)))}async decrypt04(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip04.decrypt(e,t)))}async encrypt44(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip44.encrypt(e,t)))}async decrypt44(e,t){return await this.ensureAuth(),this.#e.wait((async()=>await this.#e.getSigner().nip44.decrypt(e,t)))}}class NostrExtensionService extends lib$1.EventEmitter{params;nostrExtension;constructor(e){super(),this.params=e}startCheckingExtension(e){if(this.checkExtension(e))return;const t=setInterval((()=>{this.checkExtension(e)&&clearTimeout(t)}),100)}checkExtension(e){return!(this.nostrExtension||!window.nostr||window.nostr===e)&&(this.initExtension(e),!0)}async initExtension(e,t){this.nostrExtension=window.nostr,window.nostr=e,"extension"===this.params.userInfo?.authMethod&&await this.trySetExtensionForPubkey(this.params.userInfo.pubkey),t||setTimeout((()=>{window.nostr!==e&&this.nostrExtension!==window.nostr&&this.initExtension(e,!0)}),300)}async setExtensionReadPubkey(e){window.nostr=this.nostrExtension;const t=await window.nostr.getPublicKey();e&&e!==t?this.emit("extensionLogout"):this.emit("extensionLogin",t)}async trySetExtensionForPubkey(e){if(this.nostrExtension)return this.setExtensionReadPubkey(e)}async setExtension(){return this.setExtensionReadPubkey()}unsetExtension(e){window.nostr===this.nostrExtension&&(window.nostr=e)}getExtension(){return this.nostrExtension}hasExtension(){return!!this.nostrExtension}}class NostrParams{userInfo;optionsModal;constructor(){this.userInfo=null,this.optionsModal={theme:"default",startScreen:"welcome",devOverrideBunkerOrigin:""}}}class Popup{popup=null;constructor(){}openPopup(e){if((!this.popup||this.popup.closed)&&(this.popup=window.open(e,"_blank","width=400,height=700"),console.log("popup",this.popup),!this.popup))throw new Error("Popup blocked. Try again, please!")}closePopup(){try{this.popup?.close(),this.popup=null}catch{}}}const CALL_TIMEOUT=5e3;class ProcessManager extends lib$1.EventEmitter{callCount=0;callTimer;constructor(){super()}onAuthUrl(){Boolean(this.callTimer)&&clearTimeout(this.callTimer)}onIframeUrl(){Boolean(this.callTimer)&&clearTimeout(this.callTimer)}async wait(e){let t,n;this.callTimer||(this.callTimer=setTimeout((()=>this.emit("onCallTimeout")),CALL_TIMEOUT)),this.callCount||this.emit("onCallStart"),this.callCount++;try{n=await e()}catch(e){t=e}if(this.callCount--,this.emit("onCallEnd"),this.callTimer&&clearTimeout(this.callTimer),this.callTimer=void 0,t)throw t;return n}}class NostrLoginInitializer{extensionService;params;authNostrService;nostr;processManager;popupManager;bannerManager;modalManager;customLaunchCallback;constructor(){this.params=new NostrParams,this.processManager=new ProcessManager,this.popupManager=new Popup,this.bannerManager=new BannerManager(this.params),this.authNostrService=new AuthNostrService(this.params),this.extensionService=new NostrExtensionService(this.params),this.modalManager=new ModalManager(this.params,this.authNostrService,this.extensionService);const e={waitReady:async()=>{await this.authNostrService.waitReady(),await this.modalManager.waitReady()},getUserInfo:()=>this.params.userInfo,getSigner:()=>{if("readOnly"===this.params.userInfo.authMethod)throw new Error("Read only");return"extension"===this.params.userInfo.authMethod?this.extensionService.getExtension():this.authNostrService},launch:()=>this.launch(),wait:e=>this.processManager.wait(e)};this.nostr=new Nostr(e),this.processManager.on("onCallTimeout",(()=>{this.bannerManager.onCallTimeout()})),this.processManager.on("onCallEnd",(()=>{this.bannerManager.onCallEnd(),this.modalManager.onCallEnd()})),this.processManager.on("onCallStart",(()=>{this.bannerManager.onCallStart()})),this.authNostrService.on("onIframeUrl",(e=>{this.modalManager.onIframeUrl(e)})),this.authNostrService.on("iframeRestart",(({iframeUrl:e})=>{this.processManager.onIframeUrl(),this.bannerManager.onIframeRestart(e)})),this.authNostrService.on("onAuthUrl",(({url:e,iframeUrl:t,eventToAddAccount:n})=>{this.processManager.onAuthUrl(),n?this.modalManager.onAuthUrl(e):this.params.userInfo?this.bannerManager.onAuthUrl(e,t):this.modalManager.onAuthUrl(e)})),this.authNostrService.on("updateAccounts",(()=>{this.updateAccounts()})),this.authNostrService.on("onUserInfo",(e=>{this.bannerManager.onUserInfo(e)})),this.modalManager.on("onAuthUrlClick",(e=>{this.openPopup(e)})),this.bannerManager.on("onIframeAuthUrlClick",(e=>{this.modalManager.showIframeUrl(e)})),this.modalManager.on("onSwitchAccount",(async e=>{this.switchAccount(e)})),this.modalManager.on("onLogoutBanner",(async e=>{logout()})),this.bannerManager.on("onConfirmLogout",(async()=>{this.launch("confirm-logout")})),this.modalManager.on("updateAccounts",(()=>{this.updateAccounts()})),this.bannerManager.on("logout",(()=>{logout()})),this.bannerManager.on("onAuthUrlClick",(e=>{this.openPopup(e)})),this.bannerManager.on("onSwitchAccount",(async e=>{this.switchAccount(e)})),this.bannerManager.on("import",(()=>{this.launch("import")})),this.extensionService.on("extensionLogin",(e=>{this.authNostrService.setExtension(e)})),this.extensionService.on("extensionLogout",(()=>{logout()})),this.bannerManager.on("launch",(e=>{this.launch(e)}))}openPopup(e){this.popupManager.openPopup(e)}async switchAccount(e,t=!1){if(console.log("nostr login switch to info",e),this.extensionService.unsetExtension(this.nostr),"readOnly"===e.authMethod)this.authNostrService.setReadOnly(e.pubkey);else if("otp"===e.authMethod)this.authNostrService.setOTP(e.pubkey,e.otpData||"");else if("local"===e.authMethod&&e.sk)this.authNostrService.setLocal(e,t);else if("extension"===e.authMethod)await this.extensionService.trySetExtensionForPubkey(e.pubkey);else{if(!("connect"===e.authMethod&&e.sk&&e.relays&&e.relays[0]))throw new Error("Bad auth info");this.authNostrService.setConnect(e)}}updateAccounts(){const e=localStorageGetAccounts(),t=localStorageGetRecents();this.bannerManager.onUpdateAccounts(e),this.modalManager.onUpdateAccounts(e,t)}async launchCustomNostrConnect(){try{this.authNostrService.isAuthing()&&this.authNostrService.cancelNostrConnect();const e=new Promise((e=>this.customLaunchCallback=e));await this.authNostrService.startAuth(),await this.authNostrService.sendNeedAuth();try{await this.authNostrService.nostrConnect(),await this.authNostrService.endAuth()}catch(t){"cancelled"===t&&await e}}catch(e){console.error("launchCustomNostrConnect",e)}}fulfillCustomLaunchPromise(){if(this.customLaunchCallback){const e=this.customLaunchCallback;this.customLaunchCallback=void 0,e()}}launch=async e=>{if(!e&&this.params.optionsModal.customNostrConnect)return this.launchCustomNostrConnect();const t=localStorageGetRecents(),n=localStorageGetAccounts(),r={...this.params.optionsModal};e&&"default"!==e?r.startScreen=e:(Boolean(t?.length)||Boolean(n?.length))&&(r.startScreen="switch-account"),this.customLaunchCallback&&this.authNostrService.cancelNostrConnect();try{await this.modalManager.launch(r),this.fulfillCustomLaunchPromise()}catch(e){console.log("nostr-login failed",e)}};init=async e=>{this.extensionService.startCheckingExtension(this.nostr),window.nostr=this.nostr,this.modalManager.connectModals(e),this.bannerManager.launchAuthBanner(e),e&&(this.params.optionsModal={...e});try{const e=localStorageGetCurrent();if(e){if(!e.pubkey)throw new Error("Bad stored info");await this.switchAccount(e)}}catch(e){console.log("nostr login init error",e),await logout()}this.updateAccounts()};logout=async()=>{this.extensionService.unsetExtension(this.nostr),await this.authNostrService.logout()};setDarkMode=e=>{localStorageSetItem("nl-dark-mode",`${e}`),this.bannerManager.onDarkMode(e),this.modalManager.onDarkMode(e)};setAuth=async e=>{if(!e.type)throw new Error("Invalid auth event");if("login"!==e.type&&"logout"!==e.type&&"signup"!==e.type)throw new Error("Invalid auth event");if(e.method&&"connect"!==e.method&&"extension"!==e.method&&"local"!==e.method&&"otp"!==e.method&&"readOnly"!==e.method)throw new Error("Invalid auth event");if("logout"===e.type)return this.logout();if(!e.method||!e.pubkey)throw new Error("Invalid pubkey");const t={authMethod:e.method,pubkey:e.pubkey,relays:e.relays,sk:e.localNsec,otpData:e.otpData,name:e.name};await this.switchAccount(t,"signup"===e.type)};cancelNeedAuth=()=>{console.log("cancelNeedAuth"),this.fulfillCustomLaunchPromise(),this.authNostrService.cancelNostrConnect()}}const initializer=new NostrLoginInitializer,{init:init,launch:launch,logout:logout,setDarkMode:setDarkMode,setAuth:setAuth,cancelNeedAuth:cancelNeedAuth}=initializer;document.addEventListener("nlLogout",logout),document.addEventListener("nlLaunch",(e=>{launch(e.detail||"")})),document.addEventListener("nlNeedAuthCancel",(()=>{cancelNeedAuth()})),document.addEventListener("nlDarkMode",(e=>{setDarkMode(!!e.detail)})),document.addEventListener("nlSetAuth",(e=>{setAuth(e.detail)}));export{NostrLoginInitializer,cancelNeedAuth,init,launch,logout,setAuth,setDarkMode};
|
|
18
18
|
//# sourceMappingURL=index.esm.js.map
|