nostr-double-ratchet 0.0.38 → 0.0.48
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/README.md +52 -15
- package/dist/AppKeys.d.ts +52 -0
- package/dist/AppKeys.d.ts.map +1 -0
- package/dist/AppKeysManager.d.ts +136 -0
- package/dist/AppKeysManager.d.ts.map +1 -0
- package/dist/Invite.d.ts +5 -6
- package/dist/Invite.d.ts.map +1 -1
- package/dist/Session.d.ts +29 -0
- package/dist/Session.d.ts.map +1 -1
- package/dist/SessionManager.d.ts +15 -8
- package/dist/SessionManager.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/inviteUtils.d.ts +6 -6
- package/dist/inviteUtils.d.ts.map +1 -1
- package/dist/nostr-double-ratchet.es.js +2518 -2168
- package/dist/nostr-double-ratchet.umd.js +1 -1
- package/dist/types.d.ts +24 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +20 -2
- package/dist/utils.d.ts.map +1 -1
- package/package.json +5 -19
- package/src/AppKeys.ts +210 -0
- package/src/AppKeysManager.ts +405 -0
- package/src/Invite.ts +9 -8
- package/src/Session.ts +46 -3
- package/src/SessionManager.ts +341 -174
- package/src/index.ts +3 -3
- package/src/inviteUtils.ts +12 -11
- package/src/types.ts +28 -5
- package/src/utils.ts +42 -5
- package/LICENSE +0 -21
- package/dist/DeviceManager.d.ts +0 -127
- package/dist/DeviceManager.d.ts.map +0 -1
- package/dist/InviteList.d.ts +0 -43
- package/dist/InviteList.d.ts.map +0 -1
- package/dist/UserRecord.d.ts +0 -117
- package/dist/UserRecord.d.ts.map +0 -1
- package/src/DeviceManager.ts +0 -565
- package/src/InviteList.ts +0 -333
- package/src/UserRecord.ts +0 -338
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(L,Y){typeof exports=="object"&&typeof module<"u"?Y(exports):typeof define=="function"&&define.amd?define(["exports"],Y):(L=typeof globalThis<"u"?globalThis:L||self,Y(L["nostr-double-ratchet"]={}))})(this,function(L){"use strict";var ku=Object.defineProperty;var Lu=(L,Y,ke)=>Y in L?ku(L,Y,{enumerable:!0,configurable:!0,writable:!0,value:ke}):L[Y]=ke;var x=(L,Y,ke)=>Lu(L,typeof Y!="symbol"?Y+"":Y,ke);function Y(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function ke(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Hi(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Y(t.outputLen),Y(t.blockLen)}function ct(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function qi(t,e){ke(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Rt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zn=t=>t instanceof Uint8Array,Bt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ae=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function zi(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function _t(t){if(typeof t=="string"&&(t=zi(t)),!zn(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function ji(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!zn(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}let jn=class{clone(){return this._cloneInto()}};function Vi(t){const e=r=>t().update(_t(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Vn(t=32){if(Rt&&typeof Rt.getRandomValues=="function")return Rt.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Fi(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,h=r?0:4;t.setUint32(e+a,o,r),t.setUint32(e+h,c,r)}let Wi=class extends jn{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Bt(this.buffer)}update(e){ct(this);const{view:n,buffer:r,blockLen:i}=this;e=_t(e);const s=e.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=Bt(e);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(e.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ct(this),qi(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;Fi(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=Bt(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=a/4,d=this.get();if(h>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)c.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return e.length=i,e.pos=c,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}};const Zi=(t,e,n)=>t&e^~t&n,Gi=(t,e,n)=>t&e^t&n^e&n,Ji=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),me=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ee=new Uint32Array(64);let Yi=class extends Wi{constructor(){super(64,32,8,!1),this.A=me[0]|0,this.B=me[1]|0,this.C=me[2]|0,this.D=me[3]|0,this.E=me[4]|0,this.F=me[5]|0,this.G=me[6]|0,this.H=me[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[e,n,r,i,s,o,c,a]}set(e,n,r,i,s,o,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(e,n){for(let u=0;u<16;u++,n+=4)Ee[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const y=Ee[u-15],p=Ee[u-2],g=ae(y,7)^ae(y,18)^y>>>3,l=ae(p,17)^ae(p,19)^p>>>10;Ee[u]=l+Ee[u-7]+g+Ee[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:h,H:d}=this;for(let u=0;u<64;u++){const y=ae(c,6)^ae(c,11)^ae(c,25),p=d+y+Zi(c,a,h)+Ji[u]+Ee[u]|0,l=(ae(r,2)^ae(r,13)^ae(r,22))+Gi(r,i,s)|0;d=h,h=a,a=c,c=o+p|0,o=s,s=i,i=r,r=p+l|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,h=h+this.G|0,d=d+this.H|0,this.set(r,i,s,o,c,a,h,d)}roundClean(){Ee.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const $t=Vi(()=>new Yi);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Fn=BigInt(0),ut=BigInt(1),Xi=BigInt(2),ht=t=>t instanceof Uint8Array,Qi=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function He(t){if(!ht(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Qi[t[n]];return e}function Wn(t){const e=t.toString(16);return e.length&1?`0${e}`:e}function Tt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function qe(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const i=r*2,s=t.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function X(t){return Tt(He(t))}function Mt(t){if(!ht(t))throw new Error("Uint8Array expected");return Tt(He(Uint8Array.from(t).reverse()))}function xe(t,e){return qe(t.toString(16).padStart(e*2,"0"))}function Ot(t,e){return xe(t,e).reverse()}function es(t){return qe(Wn(t))}function G(t,e,n){let r;if(typeof e=="string")try{r=qe(e)}catch(s){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${s}`)}else if(ht(e))r=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${t} expected ${n} bytes, got ${i}`);return r}function Le(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!ht(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}function ts(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function ns(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function rs(t){let e;for(e=0;t>Fn;t>>=ut,e+=1);return e}function is(t,e){return t>>BigInt(e)&ut}const ss=(t,e,n)=>t|(n?ut:Fn)<<BigInt(e),Dt=t=>(Xi<<BigInt(t-1))-ut,Ht=t=>new Uint8Array(t),Zn=t=>Uint8Array.from(t);function Gn(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Ht(t),i=Ht(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},c=(...u)=>n(i,r,...u),a=(u=Ht())=>{i=c(Zn([0]),u),r=c(),u.length!==0&&(i=c(Zn([1]),u),r=c())},h=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const y=[];for(;u<e;){r=c();const p=r.slice();y.push(p),u+=r.length}return Le(...y)};return(u,y)=>{o(),a(u);let p;for(;!(p=y(h()));)a();return o(),p}}const os={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Qe(t,e,n={}){const r=(i,s,o)=>{const c=os[s];if(typeof c!="function")throw new Error(`Invalid validator "${s}", expected function`);const a=t[i];if(!(o&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${s}`)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}const as=Object.freeze(Object.defineProperty({__proto__:null,bitGet:is,bitLen:rs,bitMask:Dt,bitSet:ss,bytesToHex:He,bytesToNumberBE:X,bytesToNumberLE:Mt,concatBytes:Le,createHmacDrbg:Gn,ensureBytes:G,equalBytes:ts,hexToBytes:qe,hexToNumber:Tt,numberToBytesBE:xe,numberToBytesLE:Ot,numberToHexUnpadded:Wn,numberToVarBytesBE:es,utf8ToBytes:ns,validateObject:Qe},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const W=BigInt(0),F=BigInt(1),Ue=BigInt(2),cs=BigInt(3),qt=BigInt(4),Jn=BigInt(5),Yn=BigInt(8);BigInt(9),BigInt(16);function Z(t,e){const n=t%e;return n>=W?n:e+n}function us(t,e,n){if(n<=W||e<W)throw new Error("Expected power/modulo > 0");if(n===F)return W;let r=F;for(;e>W;)e&F&&(r=r*t%n),t=t*t%n,e>>=F;return r}function ee(t,e,n){let r=t;for(;e-- >W;)r*=r,r%=n;return r}function zt(t,e){if(t===W||e<=W)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=Z(t,e),r=e,i=W,s=F;for(;n!==W;){const c=r/n,a=r%n,h=i-s*c;r=n,n=a,i=s,s=h}if(r!==F)throw new Error("invert: does not exist");return Z(i,e)}function hs(t){const e=(t-F)/Ue;let n,r,i;for(n=t-F,r=0;n%Ue===W;n/=Ue,r++);for(i=Ue;i<t&&us(i,e,t)!==t-F;i++);if(r===1){const o=(t+F)/qt;return function(a,h){const d=a.pow(h,o);if(!a.eql(a.sqr(d),h))throw new Error("Cannot find square root");return d}}const s=(n+F)/Ue;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let h=r,d=c.pow(c.mul(c.ONE,i),n),u=c.pow(a,s),y=c.pow(a,n);for(;!c.eql(y,c.ONE);){if(c.eql(y,c.ZERO))return c.ZERO;let p=1;for(let l=c.sqr(y);p<h&&!c.eql(l,c.ONE);p++)l=c.sqr(l);const g=c.pow(d,F<<BigInt(h-p-1));d=c.sqr(g),u=c.mul(u,g),y=c.mul(y,d),h=p}return u}}function ds(t){if(t%qt===cs){const e=(t+F)/qt;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Yn===Jn){const e=(t-Jn)/Yn;return function(r,i){const s=r.mul(i,Ue),o=r.pow(s,e),c=r.mul(i,o),a=r.mul(r.mul(c,Ue),o),h=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(h),i))throw new Error("Cannot find square root");return h}}return hs(t)}const ls=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function fs(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=ls.reduce((r,i)=>(r[i]="function",r),e);return Qe(t,n)}function ys(t,e,n){if(n<W)throw new Error("Expected power > 0");if(n===W)return t.ONE;if(n===F)return e;let r=t.ONE,i=e;for(;n>W;)n&F&&(r=t.mul(r,i)),i=t.sqr(i),n>>=F;return r}function ps(t,e){const n=new Array(e.length),r=e.reduce((s,o,c)=>t.is0(o)?s:(n[c]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,c)=>t.is0(o)?s:(n[c]=t.mul(s,n[c]),t.mul(s,o)),i),n}function Xn(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function gs(t,e,n=!1,r={}){if(t<=W)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:i,nByteLength:s}=Xn(t,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=ds(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:s,MASK:Dt(i),ZERO:W,ONE:F,create:a=>Z(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return W<=a&&a<t},is0:a=>a===W,isOdd:a=>(a&F)===F,neg:a=>Z(-a,t),eql:(a,h)=>a===h,sqr:a=>Z(a*a,t),add:(a,h)=>Z(a+h,t),sub:(a,h)=>Z(a-h,t),mul:(a,h)=>Z(a*h,t),pow:(a,h)=>ys(c,a,h),div:(a,h)=>Z(a*zt(h,t),t),sqrN:a=>a*a,addN:(a,h)=>a+h,subN:(a,h)=>a-h,mulN:(a,h)=>a*h,inv:a=>zt(a,t),sqrt:r.sqrt||(a=>o(c,a)),invertBatch:a=>ps(c,a),cmov:(a,h,d)=>d?h:a,toBytes:a=>n?Ot(a,s):xe(a,s),fromBytes:a=>{if(a.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${a.length}`);return n?Mt(a):X(a)}});return Object.freeze(c)}function Qn(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function er(t){const e=Qn(t);return e+Math.ceil(e/2)}function vs(t,e,n=!1){const r=t.length,i=Qn(e),s=er(e);if(r<16||r<s||r>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=n?X(t):Mt(t),c=Z(o,e-F)+F;return n?Ot(c,i):xe(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bs=BigInt(0),jt=BigInt(1);function ws(t,e){const n=(i,s)=>{const o=s.negate();return i?o:s},r=i=>{const s=Math.ceil(e/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:n,unsafeLadder(i,s){let o=t.ZERO,c=i;for(;s>bs;)s&jt&&(o=o.add(c)),c=c.double(),s>>=jt;return o},precomputeWindow(i,s){const{windows:o,windowSize:c}=r(s),a=[];let h=i,d=h;for(let u=0;u<o;u++){d=h,a.push(d);for(let y=1;y<c;y++)d=d.add(h),a.push(d);h=d.double()}return a},wNAF(i,s,o){const{windows:c,windowSize:a}=r(i);let h=t.ZERO,d=t.BASE;const u=BigInt(2**i-1),y=2**i,p=BigInt(i);for(let g=0;g<c;g++){const l=g*a;let f=Number(o&u);o>>=p,f>a&&(f-=y,o+=jt);const v=l,m=l+Math.abs(f)-1,A=g%2!==0,R=f<0;f===0?d=d.add(n(A,s[v])):h=h.add(n(R,s[m]))}return{p:h,f:d}},wNAFCached(i,s,o,c){const a=i._WINDOW_SIZE||1;let h=s.get(i);return h||(h=this.precomputeWindow(i,a),a!==1&&s.set(i,c(h))),this.wNAF(a,h,o)}}}function tr(t){return fs(t.Fp),Qe(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Xn(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ms(t){const e=tr(t);Qe(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Es,hexToBytes:xs}=as,Re={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){const{Err:e}=Re;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Es(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=Re,n=typeof t=="string"?xs(t):t;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:i,l:s}=Re._parseInt(n.subarray(2)),{d:o,l:c}=Re._parseInt(s);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(t){const e=h=>Number.parseInt(h[0],16)&8?"00"+h:h,n=h=>{const d=h.toString(16);return d.length&1?`0${d}`:d},r=e(n(t.s)),i=e(n(t.r)),s=r.length/2,o=i.length/2,c=n(s),a=n(o);return`30${n(o+s+4)}02${a}${i}02${c}${r}`}},le=BigInt(0),te=BigInt(1);BigInt(2);const nr=BigInt(3);BigInt(4);function Ks(t){const e=ms(t),{Fp:n}=e,r=e.toBytes||((g,l,f)=>{const v=l.toAffine();return Le(Uint8Array.from([4]),n.toBytes(v.x),n.toBytes(v.y))}),i=e.fromBytes||(g=>{const l=g.subarray(1),f=n.fromBytes(l.subarray(0,n.BYTES)),v=n.fromBytes(l.subarray(n.BYTES,2*n.BYTES));return{x:f,y:v}});function s(g){const{a:l,b:f}=e,v=n.sqr(g),m=n.mul(v,g);return n.add(n.add(m,n.mul(g,l)),f)}if(!n.eql(n.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function o(g){return typeof g=="bigint"&&le<g&&g<e.n}function c(g){if(!o(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){const{allowedPrivateKeyLengths:l,nByteLength:f,wrapPrivateKey:v,n:m}=e;if(l&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=He(g)),typeof g!="string"||!l.includes(g.length))throw new Error("Invalid key");g=g.padStart(f*2,"0")}let A;try{A=typeof g=="bigint"?g:X(G("private key",g,f))}catch{throw new Error(`private key must be ${f} bytes, hex or bigint, not ${typeof g}`)}return v&&(A=Z(A,m)),c(A),A}const h=new Map;function d(g){if(!(g instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(l,f,v){if(this.px=l,this.py=f,this.pz=v,l==null||!n.isValid(l))throw new Error("x required");if(f==null||!n.isValid(f))throw new Error("y required");if(v==null||!n.isValid(v))throw new Error("z required")}static fromAffine(l){const{x:f,y:v}=l||{};if(!l||!n.isValid(f)||!n.isValid(v))throw new Error("invalid affine point");if(l instanceof u)throw new Error("projective point not allowed");const m=A=>n.eql(A,n.ZERO);return m(f)&&m(v)?u.ZERO:new u(f,v,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(l){const f=n.invertBatch(l.map(v=>v.pz));return l.map((v,m)=>v.toAffine(f[m])).map(u.fromAffine)}static fromHex(l){const f=u.fromAffine(i(G("pointHex",l)));return f.assertValidity(),f}static fromPrivateKey(l){return u.BASE.multiply(a(l))}_setWindowSize(l){this._WINDOW_SIZE=l,h.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:l,y:f}=this.toAffine();if(!n.isValid(l)||!n.isValid(f))throw new Error("bad point: x or y not FE");const v=n.sqr(f),m=s(l);if(!n.eql(v,m))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:l}=this.toAffine();if(n.isOdd)return!n.isOdd(l);throw new Error("Field doesn't support isOdd")}equals(l){d(l);const{px:f,py:v,pz:m}=this,{px:A,py:R,pz:C}=l,E=n.eql(n.mul(f,C),n.mul(A,m)),K=n.eql(n.mul(v,C),n.mul(R,m));return E&&K}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:l,b:f}=e,v=n.mul(f,nr),{px:m,py:A,pz:R}=this;let C=n.ZERO,E=n.ZERO,K=n.ZERO,S=n.mul(m,m),H=n.mul(A,A),U=n.mul(R,R),N=n.mul(m,A);return N=n.add(N,N),K=n.mul(m,R),K=n.add(K,K),C=n.mul(l,K),E=n.mul(v,U),E=n.add(C,E),C=n.sub(H,E),E=n.add(H,E),E=n.mul(C,E),C=n.mul(N,C),K=n.mul(v,K),U=n.mul(l,U),N=n.sub(S,U),N=n.mul(l,N),N=n.add(N,K),K=n.add(S,S),S=n.add(K,S),S=n.add(S,U),S=n.mul(S,N),E=n.add(E,S),U=n.mul(A,R),U=n.add(U,U),S=n.mul(U,N),C=n.sub(C,S),K=n.mul(U,H),K=n.add(K,K),K=n.add(K,K),new u(C,E,K)}add(l){d(l);const{px:f,py:v,pz:m}=this,{px:A,py:R,pz:C}=l;let E=n.ZERO,K=n.ZERO,S=n.ZERO;const H=e.a,U=n.mul(e.b,nr);let N=n.mul(f,A),T=n.mul(v,R),M=n.mul(m,C),V=n.add(f,v),b=n.add(A,R);V=n.mul(V,b),b=n.add(N,T),V=n.sub(V,b),b=n.add(f,m);let w=n.add(A,C);return b=n.mul(b,w),w=n.add(N,M),b=n.sub(b,w),w=n.add(v,m),E=n.add(R,C),w=n.mul(w,E),E=n.add(T,M),w=n.sub(w,E),S=n.mul(H,b),E=n.mul(U,M),S=n.add(E,S),E=n.sub(T,S),S=n.add(T,S),K=n.mul(E,S),T=n.add(N,N),T=n.add(T,N),M=n.mul(H,M),b=n.mul(U,b),T=n.add(T,M),M=n.sub(N,M),M=n.mul(H,M),b=n.add(b,M),N=n.mul(T,b),K=n.add(K,N),N=n.mul(w,b),E=n.mul(V,E),E=n.sub(E,N),N=n.mul(V,T),S=n.mul(w,S),S=n.add(S,N),new u(E,K,S)}subtract(l){return this.add(l.negate())}is0(){return this.equals(u.ZERO)}wNAF(l){return p.wNAFCached(this,h,l,f=>{const v=n.invertBatch(f.map(m=>m.pz));return f.map((m,A)=>m.toAffine(v[A])).map(u.fromAffine)})}multiplyUnsafe(l){const f=u.ZERO;if(l===le)return f;if(c(l),l===te)return this;const{endo:v}=e;if(!v)return p.unsafeLadder(this,l);let{k1neg:m,k1:A,k2neg:R,k2:C}=v.splitScalar(l),E=f,K=f,S=this;for(;A>le||C>le;)A&te&&(E=E.add(S)),C&te&&(K=K.add(S)),S=S.double(),A>>=te,C>>=te;return m&&(E=E.negate()),R&&(K=K.negate()),K=new u(n.mul(K.px,v.beta),K.py,K.pz),E.add(K)}multiply(l){c(l);let f=l,v,m;const{endo:A}=e;if(A){const{k1neg:R,k1:C,k2neg:E,k2:K}=A.splitScalar(f);let{p:S,f:H}=this.wNAF(C),{p:U,f:N}=this.wNAF(K);S=p.constTimeNegate(R,S),U=p.constTimeNegate(E,U),U=new u(n.mul(U.px,A.beta),U.py,U.pz),v=S.add(U),m=H.add(N)}else{const{p:R,f:C}=this.wNAF(f);v=R,m=C}return u.normalizeZ([v,m])[0]}multiplyAndAddUnsafe(l,f,v){const m=u.BASE,A=(C,E)=>E===le||E===te||!C.equals(m)?C.multiplyUnsafe(E):C.multiply(E),R=A(this,f).add(A(l,v));return R.is0()?void 0:R}toAffine(l){const{px:f,py:v,pz:m}=this,A=this.is0();l==null&&(l=A?n.ONE:n.inv(m));const R=n.mul(f,l),C=n.mul(v,l),E=n.mul(m,l);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:R,y:C}}isTorsionFree(){const{h:l,isTorsionFree:f}=e;if(l===te)return!0;if(f)return f(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:l,clearCofactor:f}=e;return l===te?this:f?f(u,this):this.multiplyUnsafe(e.h)}toRawBytes(l=!0){return this.assertValidity(),r(u,this,l)}toHex(l=!0){return He(this.toRawBytes(l))}}u.BASE=new u(e.Gx,e.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const y=e.nBitLength,p=ws(u,e.endo?Math.ceil(y/2):y);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:o}}function Ss(t){const e=tr(t);return Qe(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Is(t){const e=Ss(t),{Fp:n,n:r}=e,i=n.BYTES+1,s=2*n.BYTES+1;function o(b){return le<b&&b<n.ORDER}function c(b){return Z(b,r)}function a(b){return zt(b,r)}const{ProjectivePoint:h,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:y}=Ks({...e,toBytes(b,w,I){const k=w.toAffine(),P=n.toBytes(k.x),_=Le;return I?_(Uint8Array.from([w.hasEvenY()?2:3]),P):_(Uint8Array.from([4]),P,n.toBytes(k.y))},fromBytes(b){const w=b.length,I=b[0],k=b.subarray(1);if(w===i&&(I===2||I===3)){const P=X(k);if(!o(P))throw new Error("Point is not on curve");const _=u(P);let O=n.sqrt(_);const $=(O&te)===te;return(I&1)===1!==$&&(O=n.neg(O)),{x:P,y:O}}else if(w===s&&I===4){const P=n.fromBytes(k.subarray(0,n.BYTES)),_=n.fromBytes(k.subarray(n.BYTES,2*n.BYTES));return{x:P,y:_}}else throw new Error(`Point of length ${w} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),p=b=>He(xe(b,e.nByteLength));function g(b){const w=r>>te;return b>w}function l(b){return g(b)?c(-b):b}const f=(b,w,I)=>X(b.slice(w,I));class v{constructor(w,I,k){this.r=w,this.s=I,this.recovery=k,this.assertValidity()}static fromCompact(w){const I=e.nByteLength;return w=G("compactSignature",w,I*2),new v(f(w,0,I),f(w,I,2*I))}static fromDER(w){const{r:I,s:k}=Re.toSig(G("DER",w));return new v(I,k)}assertValidity(){if(!y(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!y(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(w){return new v(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:k,recovery:P}=this,_=K(G("msgHash",w));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const O=P===2||P===3?I+e.n:I;if(O>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const $=(P&1)===0?"02":"03",se=h.fromHex($+p(O)),Pe=a(O),Ge=c(-_*Pe),at=c(k*Pe),Ce=h.BASE.multiplyAndAddUnsafe(se,Ge,at);if(!Ce)throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return qe(this.toDERHex())}toDERHex(){return Re.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qe(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return d(b),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{const b=er(e.n);return vs(e.randomBytes(b),e.n)},precompute(b=8,w=h.BASE){return w._setWindowSize(b),w.multiply(BigInt(3)),w}};function A(b,w=!0){return h.fromPrivateKey(b).toRawBytes(w)}function R(b){const w=b instanceof Uint8Array,I=typeof b=="string",k=(w||I)&&b.length;return w?k===i||k===s:I?k===2*i||k===2*s:b instanceof h}function C(b,w,I=!0){if(R(b))throw new Error("first arg must be private key");if(!R(w))throw new Error("second arg must be public key");return h.fromHex(w).multiply(d(b)).toRawBytes(I)}const E=e.bits2int||function(b){const w=X(b),I=b.length*8-e.nBitLength;return I>0?w>>BigInt(I):w},K=e.bits2int_modN||function(b){return c(E(b))},S=Dt(e.nBitLength);function H(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(le<=b&&b<S))throw new Error(`bigint expected < 2^${e.nBitLength}`);return xe(b,e.nByteLength)}function U(b,w,I=N){if(["recovered","canonical"].some(De=>De in I))throw new Error("sign() legacy options not supported");const{hash:k,randomBytes:P}=e;let{lowS:_,prehash:O,extraEntropy:$}=I;_==null&&(_=!0),b=G("msgHash",b),O&&(b=G("prehashed msgHash",k(b)));const se=K(b),Pe=d(w),Ge=[H(Pe),H(se)];if($!=null){const De=$===!0?P(n.BYTES):$;Ge.push(G("extraEntropy",De))}const at=Le(...Ge),Ce=se;function qn(De){const Je=E(De);if(!y(Je))return;const Mi=a(Je),Ye=h.BASE.multiply(Je).toAffine(),oe=c(Ye.x);if(oe===le)return;const Xe=c(Mi*c(Ce+oe*Pe));if(Xe===le)return;let Oi=(Ye.x===oe?0:2)|Number(Ye.y&te),Di=Xe;return _&&g(Xe)&&(Di=l(Xe),Oi^=1),new v(oe,Di,Oi)}return{seed:at,k2sig:qn}}const N={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function M(b,w,I=N){const{seed:k,k2sig:P}=U(b,w,I),_=e;return Gn(_.hash.outputLen,_.nByteLength,_.hmac)(k,P)}h.BASE._setWindowSize(8);function V(b,w,I,k=T){var Ye;const P=b;if(w=G("msgHash",w),I=G("publicKey",I),"strict"in k)throw new Error("options.strict was renamed to lowS");const{lowS:_,prehash:O}=k;let $,se;try{if(typeof P=="string"||P instanceof Uint8Array)try{$=v.fromDER(P)}catch(oe){if(!(oe instanceof Re.Err))throw oe;$=v.fromCompact(P)}else if(typeof P=="object"&&typeof P.r=="bigint"&&typeof P.s=="bigint"){const{r:oe,s:Xe}=P;$=new v(oe,Xe)}else throw new Error("PARSE");se=h.fromHex(I)}catch(oe){if(oe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(_&&$.hasHighS())return!1;O&&(w=e.hash(w));const{r:Pe,s:Ge}=$,at=K(w),Ce=a(Ge),qn=c(at*Ce),De=c(Pe*Ce),Je=(Ye=h.BASE.multiplyAndAddUnsafe(se,qn,De))==null?void 0:Ye.toAffine();return Je?c(Je.x)===Pe:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:C,sign:M,verify:V,ProjectivePoint:h,Signature:v,utils:m}}let rr=class extends jn{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Hi(e);const r=_t(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return ct(this),this.iHash.update(e),this}digestInto(e){ct(this),ke(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:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ir=(t,e,n)=>new rr(t,e).update(n).digest();ir.create=(t,e)=>new rr(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function As(t){return{hash:t,hmac:(e,...n)=>ir(t,e,ji(...n)),randomBytes:Vn}}function Ns(t,e){const n=r=>Is({...t,...As(r)});return Object.freeze({...n(e),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const dt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),lt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),sr=BigInt(1),ft=BigInt(2),or=(t,e)=>(t+e/ft)/e;function ar(t){const e=dt,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),c=BigInt(44),a=BigInt(88),h=t*t*t%e,d=h*h*t%e,u=ee(d,n,e)*d%e,y=ee(u,n,e)*d%e,p=ee(y,ft,e)*h%e,g=ee(p,i,e)*p%e,l=ee(g,s,e)*g%e,f=ee(l,c,e)*l%e,v=ee(f,a,e)*f%e,m=ee(v,c,e)*l%e,A=ee(m,n,e)*d%e,R=ee(A,o,e)*g%e,C=ee(R,r,e)*h%e,E=ee(C,ft,e);if(!Vt.eql(Vt.sqr(E),t))throw new Error("Cannot find square root");return E}const Vt=gs(dt,void 0,void 0,{sqrt:ar}),Be=Ns({a:BigInt(0),b:BigInt(7),Fp:Vt,n:lt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=lt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-sr*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),c=or(s*t,e),a=or(-r*t,e);let h=Z(t-c*n-a*i,e),d=Z(-c*r-a*s,e);const u=h>o,y=d>o;if(u&&(h=e-h),y&&(d=e-d),h>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:h,k2neg:y,k2:d}}}},$t),yt=BigInt(0),cr=t=>typeof t=="bigint"&&yt<t&&t<dt,Ps=t=>typeof t=="bigint"&&yt<t&&t<lt,ur={};function pt(t,...e){let n=ur[t];if(n===void 0){const r=$t(Uint8Array.from(t,i=>i.charCodeAt(0)));n=Le(r,r),ur[t]=n}return $t(Le(n,...e))}const Ft=t=>t.toRawBytes(!0).slice(1),Wt=t=>xe(t,32),Zt=t=>Z(t,dt),et=t=>Z(t,lt),Gt=Be.ProjectivePoint,Cs=(t,e,n)=>Gt.BASE.multiplyAndAddUnsafe(t,e,n);function Jt(t){let e=Be.utils.normPrivateKeyToScalar(t),n=Gt.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:et(-e),bytes:Ft(n)}}function hr(t){if(!cr(t))throw new Error("bad x: need 0 < x < p");const e=Zt(t*t),n=Zt(e*t+BigInt(7));let r=ar(n);r%ft!==yt&&(r=Zt(-r));const i=new Gt(t,r,sr);return i.assertValidity(),i}function dr(...t){return et(X(pt("BIP0340/challenge",...t)))}function ks(t){return Jt(t).bytes}function Ls(t,e,n=Vn(32)){const r=G("message",t),{bytes:i,scalar:s}=Jt(e),o=G("auxRand",n,32),c=Wt(s^X(pt("BIP0340/aux",o))),a=pt("BIP0340/nonce",c,i,r),h=et(X(a));if(h===yt)throw new Error("sign failed: k is zero");const{bytes:d,scalar:u}=Jt(h),y=dr(d,i,r),p=new Uint8Array(64);if(p.set(d,0),p.set(Wt(et(u+y*s)),32),!lr(p,r,i))throw new Error("sign: Invalid signature produced");return p}function lr(t,e,n){const r=G("signature",t,64),i=G("message",e),s=G("publicKey",n,32);try{const o=hr(X(s)),c=X(r.subarray(0,32));if(!cr(c))return!1;const a=X(r.subarray(32,64));if(!Ps(a))return!1;const h=dr(Wt(c),Ft(o),i),d=Cs(o,a,et(-h));return!(!d||!d.hasEvenY()||d.toAffine().x!==c)}catch{return!1}}const tt={getPublicKey:ks,sign:Ls,verify:lr,utils:{randomPrivateKey:Be.utils.randomPrivateKey,lift_x:hr,pointToBytes:Ft,numberToBytesBE:xe,bytesToNumberBE:X,taggedHash:pt,mod:Z}},Yt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xt=t=>t instanceof Uint8Array,Qt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ce=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const Us=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function D(t){if(!Xt(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Us[t[n]];return e}function z(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const i=r*2,s=t.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Rs(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function nt(t){if(typeof t=="string"&&(t=Rs(t)),!Xt(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function gt(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!Xt(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}class fr{clone(){return this._cloneInto()}}function yr(t){const e=r=>t().update(nt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function pr(t=32){if(Yt&&typeof Yt.getRandomValues=="function")return Yt.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function en(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Bs(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}function gr(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function _s(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");en(t.outputLen),en(t.blockLen)}function $s(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ts(t,e){gr(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const ue={number:en,bool:Bs,bytes:gr,hash:_s,exists:$s,output:Ts};function Ms(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,h=r?0:4;t.setUint32(e+a,o,r),t.setUint32(e+h,c,r)}class Os extends fr{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Qt(this.buffer)}update(e){ue.exists(this);const{view:n,buffer:r,blockLen:i}=this;e=nt(e);const s=e.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=Qt(e);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(e.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ue.exists(this),ue.output(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;Ms(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=Qt(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=a/4,d=this.get();if(h>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)c.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return e.length=i,e.pos=c,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const Ds=(t,e,n)=>t&e^~t&n,Hs=(t,e,n)=>t&e^t&n^e&n,qs=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ke=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Se=new Uint32Array(64);class vr extends Os{constructor(){super(64,32,8,!1),this.A=Ke[0]|0,this.B=Ke[1]|0,this.C=Ke[2]|0,this.D=Ke[3]|0,this.E=Ke[4]|0,this.F=Ke[5]|0,this.G=Ke[6]|0,this.H=Ke[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[e,n,r,i,s,o,c,a]}set(e,n,r,i,s,o,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(e,n){for(let u=0;u<16;u++,n+=4)Se[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const y=Se[u-15],p=Se[u-2],g=ce(y,7)^ce(y,18)^y>>>3,l=ce(p,17)^ce(p,19)^p>>>10;Se[u]=l+Se[u-7]+g+Se[u-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:h,H:d}=this;for(let u=0;u<64;u++){const y=ce(c,6)^ce(c,11)^ce(c,25),p=d+y+Ds(c,a,h)+qs[u]+Se[u]|0,l=(ce(r,2)^ce(r,13)^ce(r,22))+Hs(r,i,s)|0;d=h,h=a,a=c,c=o+p|0,o=s,s=i,i=r,r=p+l|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,h=h+this.G|0,d=d+this.H|0,this.set(r,i,s,o,c,a,h,d)}roundClean(){Se.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class zs extends vr{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const fe=yr(()=>new vr);yr(()=>new zs);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ze(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function ye(...t){const e=(i,s)=>o=>i(s(o)),n=Array.from(t).reverse().reduce((i,s)=>i?e(i,s.encode):s.encode,void 0),r=t.reduce((i,s)=>i?e(i,s.decode):s.decode,void 0);return{encode:n,decode:r}}function pe(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(n=>{if(ze(n),n<0||n>=t.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${t.length})`);return t[n]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=t.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return r})}}}function ge(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of e)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function vt(t,e="="){if(ze(t),typeof e!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if(!((r-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function br(t){if(typeof t!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>t(e)}}function wr(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, 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(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let r=0;const i=[],s=Array.from(t);for(s.forEach(o=>{if(ze(o),o<0||o>=e)throw new Error(`Wrong integer: ${o}`)});;){let o=0,c=!0;for(let a=r;a<s.length;a++){const h=s[a],d=e*o+h;if(!Number.isSafeInteger(d)||e*o/e!==o||d-h!==e*o)throw new Error("convertRadix: carry overflow");if(o=d%n,s[a]=Math.floor(d/n),!Number.isSafeInteger(s[a])||s[a]*n+o!==d)throw new Error("convertRadix: carry overflow");if(c)s[a]?c=!1:r=a;else continue}if(i.push(o),c)break}for(let o=0;o<t.length-1&&t[o]===0;o++)i.push(0);return i.reverse()}const mr=(t,e)=>e?mr(e,t%e):t,bt=(t,e)=>t+(e-mr(t,e));function tn(t,e,n,r){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(bt(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${bt(e,n)}`);let i=0,s=0;const o=2**n-1,c=[];for(const a of t){if(ze(a),a>=2**e)throw new Error(`convertRadix2: invalid data word=${a} from=${e}`);if(i=i<<e|a,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<<n-s&o,!r&&s>=e)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function js(t){return ze(t),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return wr(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(wr(e,t,2**8))}}}function Ie(t,e=!1){if(ze(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(bt(8,t)>32||bt(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return tn(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(tn(n,t,8,e))}}}function Er(t){if(typeof t!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return t.apply(null,e)}catch{}}}const Vs=ye(Ie(4),pe("0123456789ABCDEF"),ge("")),Fs=ye(Ie(5),pe("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),vt(5),ge(""));ye(Ie(5),pe("0123456789ABCDEFGHIJKLMNOPQRSTUV"),vt(5),ge("")),ye(Ie(5),pe("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ge(""),br(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ve=ye(Ie(6),pe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),vt(6),ge("")),Ws=ye(Ie(6),pe("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),vt(6),ge("")),nn=t=>ye(js(58),pe(t),ge("")),rn=nn("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");nn("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),nn("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const xr=[0,2,3,5,6,7,9,10,11],Zs={encode(t){let e="";for(let n=0;n<t.length;n+=8){const r=t.subarray(n,n+8);e+=rn.encode(r).padStart(xr[r.length],"1")}return e},decode(t){let e=[];for(let n=0;n<t.length;n+=11){const r=t.slice(n,n+11),i=xr.indexOf(r.length),s=rn.decode(r);for(let o=0;o<s.length-i;o++)if(s[o]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(e)}},sn=ye(pe("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ge("")),Kr=[996825010,642813549,513874426,1027748829,705979059];function rt(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Kr.length;r++)(e>>r&1)===1&&(n^=Kr[r]);return n}function Sr(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=rt(i)^o>>5}i=rt(i);for(let s=0;s<r;s++)i=rt(i)^t.charCodeAt(s)&31;for(let s of e)i=rt(i)^s;for(let s=0;s<6;s++)i=rt(i);return i^=n,sn.encode(tn([i%2**30],30,5,!1))}function Ir(t){const e=t==="bech32"?1:734539939,n=Ie(5),r=n.decode,i=n.encode,s=Er(r);function o(d,u,y=90){if(typeof d!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof d}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const p=d.length+7+u.length;if(y!==!1&&p>y)throw new TypeError(`Length ${p} exceeds limit ${y}`);return d=d.toLowerCase(),`${d}1${sn.encode(u)}${Sr(d,u,e)}`}function c(d,u=90){if(typeof d!="string")throw new Error(`bech32.decode input should be string, not ${typeof d}`);if(d.length<8||u!==!1&&d.length>u)throw new TypeError(`Wrong string length: ${d.length} (${d}). Expected (8..${u})`);const y=d.toLowerCase();if(d!==y&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");d=y;const p=d.lastIndexOf("1");if(p===0||p===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=d.slice(0,p),l=d.slice(p+1);if(l.length<6)throw new Error("Data must be at least 6 characters long");const f=sn.decode(l).slice(0,-6),v=Sr(g,f,e);if(!l.endsWith(v))throw new Error(`Invalid checksum in ${d}: expected "${v}"`);return{prefix:g,words:f}}const a=Er(c);function h(d){const{prefix:u,words:y}=c(d,!1);return{prefix:u,words:y,bytes:r(y)}}return{encode:o,decode:c,decodeToBytes:h,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:s,toWords:i}}const je=Ir("bech32");Ir("bech32m");const Gs={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},Js=ye(Ie(4),pe("0123456789abcdef"),ge(""),br(t=>{if(typeof t!="string"||t.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));`${Object.keys({utf8:Gs,hex:Js,base16:Vs,base32:Fs,base64:ve,base64url:Ws,base58:rn,base58xmr:Zs}).join(", ")}`;function on(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function Ar(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Ys(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function be(t,...e){if(!Ys(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const J=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Xs(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Qs(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const eo=(t,e)=>(Object.assign(e,t),e),Ae=16,to=283;function an(t){return t<<1^to&-(t>>7)}function Ve(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(e&1),t=an(t);return n}const cn=(()=>{let t=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=an(r))t[n]=r;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return e})(),no=cn.map((t,e)=>cn.indexOf(e)),ro=t=>t<<24|t>>>8,un=t=>t<<8|t>>>24;function Nr(t,e){if(t.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((h,d)=>e(t[d])),r=n.map(un),i=r.map(un),s=i.map(un),o=new Uint32Array(256*256),c=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let h=0;h<256;h++)for(let d=0;d<256;d++){const u=h*256+d;o[u]=n[h]^r[d],c[u]=i[h]^s[d],a[u]=t[h]<<8|t[d]}return{sbox:t,sbox2:a,T0:n,T1:r,T2:i,T3:s,T01:o,T23:c}}const hn=Nr(cn,t=>Ve(t,3)<<24|t<<16|t<<8|Ve(t,2)),Pr=Nr(no,t=>Ve(t,11)<<24|Ve(t,13)<<16|Ve(t,9)<<8|Ve(t,14)),io=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=an(n))t[e]=n;return t})();function Cr(t){be(t);const e=t.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:n}=hn,r=J(t),i=r.length,s=c=>he(n,c,c,c,c),o=new Uint32Array(e+28);o.set(r);for(let c=i;c<o.length;c++){let a=o[c-1];c%i===0?a=s(ro(a))^io[c/i-1]:i>6&&c%i===4&&(a=s(a)),o[c]=o[c-i]^a}return o}function so(t){const e=Cr(t),n=e.slice(),r=e.length,{sbox2:i}=hn,{T0:s,T1:o,T2:c,T3:a}=Pr;for(let h=0;h<r;h+=4)for(let d=0;d<4;d++)n[h+d]=e[r-h-4+d];e.fill(0);for(let h=4;h<r-4;h++){const d=n[h],u=he(i,d,d,d,d);n[h]=s[u&255]^o[u>>>8&255]^c[u>>>16&255]^a[u>>>24]}return n}function Ne(t,e,n,r,i,s){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|s>>>24&255]}function he(t,e,n,r,i){return t[e&255|n&65280]|t[r>>>16&255|i>>>16&65280]<<16}function kr(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=hn;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const h=t.length/4-2;for(let g=0;g<h;g++){const l=t[a++]^Ne(o,c,e,n,r,i),f=t[a++]^Ne(o,c,n,r,i,e),v=t[a++]^Ne(o,c,r,i,e,n),m=t[a++]^Ne(o,c,i,e,n,r);e=l,n=f,r=v,i=m}const d=t[a++]^he(s,e,n,r,i),u=t[a++]^he(s,n,r,i,e),y=t[a++]^he(s,r,i,e,n),p=t[a++]^he(s,i,e,n,r);return{s0:d,s1:u,s2:y,s3:p}}function oo(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=Pr;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const h=t.length/4-2;for(let g=0;g<h;g++){const l=t[a++]^Ne(o,c,e,i,r,n),f=t[a++]^Ne(o,c,n,e,i,r),v=t[a++]^Ne(o,c,r,n,e,i),m=t[a++]^Ne(o,c,i,r,n,e);e=l,n=f,r=v,i=m}const d=t[a++]^he(s,e,i,r,n),u=t[a++]^he(s,n,e,i,r),y=t[a++]^he(s,r,n,e,i),p=t[a++]^he(s,i,r,n,e);return{s0:d,s1:u,s2:y,s3:p}}function Lr(t,e){if(!e)return new Uint8Array(t);if(be(e),e.length<t)throw new Error(`aes: wrong destination length, expected at least ${t}, got: ${e.length}`);return e}function ao(t){if(be(t),t.length%Ae!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Ae}`)}function co(t,e,n){let r=t.length;const i=r%Ae;if(!e&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=J(t);if(e){let a=Ae-i;a||(a=Ae),r=r+a}const o=Lr(r,n),c=J(o);return{b:s,o:c,out:o}}function uo(t,e){if(!e)return t;const n=t.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=t[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=t.subarray(0,-r);for(let s=0;s<r;s++)if(t[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function ho(t){const e=new Uint8Array(16),n=J(e);e.set(t);const r=Ae-t.length;for(let i=Ae-r;i<Ae;i++)e[i]=r;return n}const Ur=eo({blockSize:16,nonceLength:16},function(e,n,r={}){be(e),be(n,16);const i=!r.disablePadding;return{encrypt:(s,o)=>{const c=Cr(e),{b:a,o:h,out:d}=co(s,i,o),u=J(n);let y=u[0],p=u[1],g=u[2],l=u[3],f=0;for(;f+4<=a.length;)y^=a[f+0],p^=a[f+1],g^=a[f+2],l^=a[f+3],{s0:y,s1:p,s2:g,s3:l}=kr(c,y,p,g,l),h[f++]=y,h[f++]=p,h[f++]=g,h[f++]=l;if(i){const v=ho(s.subarray(f*4));y^=v[0],p^=v[1],g^=v[2],l^=v[3],{s0:y,s1:p,s2:g,s3:l}=kr(c,y,p,g,l),h[f++]=y,h[f++]=p,h[f++]=g,h[f++]=l}return c.fill(0),d},decrypt:(s,o)=>{ao(s);const c=so(e),a=J(n),h=Lr(s.length,o),d=J(s),u=J(h);let y=a[0],p=a[1],g=a[2],l=a[3];for(let f=0;f+4<=d.length;){const v=y,m=p,A=g,R=l;y=d[f+0],p=d[f+1],g=d[f+2],l=d[f+3];const{s0:C,s1:E,s2:K,s3:S}=oo(c,y,p,g,l);u[f++]=C^v,u[f++]=E^m,u[f++]=K^A,u[f++]=S^R}return c.fill(0),uo(h,i)}}}),Rr=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),lo=Rr("expand 16-byte k"),fo=Rr("expand 32-byte k"),yo=J(lo),Br=J(fo);Br.slice();function B(t,e){return t<<e|t>>>32-e}function dn(t){return t.byteOffset%4===0}const wt=64,po=16,_r=2**32-1,$r=new Uint32Array;function go(t,e,n,r,i,s,o,c){const a=i.length,h=new Uint8Array(wt),d=J(h),u=dn(i)&&dn(s),y=u?J(i):$r,p=u?J(s):$r;for(let g=0;g<a;o++){if(t(e,n,r,d,o,c),o>=_r)throw new Error("arx: counter overflow");const l=Math.min(wt,a-g);if(u&&l===wt){const f=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let v=0,m;v<po;v++)m=f+v,p[m]=y[m]^d[v];g+=wt;continue}for(let f=0,v;f<l;f++)v=g+f,s[v]=i[v]^h[f];g+=l}}function vo(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Xs({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return on(i),on(o),Ar(s),Ar(n),(c,a,h,d,u=0)=>{be(c),be(a),be(h);const y=h.length;if(d||(d=new Uint8Array(y)),be(d),on(u),u<0||u>=_r)throw new Error("arx: counter overflow");if(d.length<y)throw new Error(`arx: output (${d.length}) is shorter than data (${y})`);const p=[];let g=c.length,l,f;if(g===32)l=c.slice(),p.push(l),f=Br;else if(g===16&&n)l=new Uint8Array(32),l.set(c),l.set(c,16),f=yo,p.push(l);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);dn(a)||(a=a.slice(),p.push(a));const v=J(l);if(r){if(a.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(f,v,J(a.subarray(0,16)),v),a=a.subarray(16)}const m=16-i;if(m!==a.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const R=new Uint8Array(12);R.set(a,s?0:12-a.length),a=R,p.push(a)}const A=J(a);for(go(t,f,v,A,h,d,u,o);p.length>0;)p.pop().fill(0);return d}}function bo(t,e,n,r,i,s=20){let o=t[0],c=t[1],a=t[2],h=t[3],d=e[0],u=e[1],y=e[2],p=e[3],g=e[4],l=e[5],f=e[6],v=e[7],m=i,A=n[0],R=n[1],C=n[2],E=o,K=c,S=a,H=h,U=d,N=u,T=y,M=p,V=g,b=l,w=f,I=v,k=m,P=A,_=R,O=C;for(let se=0;se<s;se+=2)E=E+U|0,k=B(k^E,16),V=V+k|0,U=B(U^V,12),E=E+U|0,k=B(k^E,8),V=V+k|0,U=B(U^V,7),K=K+N|0,P=B(P^K,16),b=b+P|0,N=B(N^b,12),K=K+N|0,P=B(P^K,8),b=b+P|0,N=B(N^b,7),S=S+T|0,_=B(_^S,16),w=w+_|0,T=B(T^w,12),S=S+T|0,_=B(_^S,8),w=w+_|0,T=B(T^w,7),H=H+M|0,O=B(O^H,16),I=I+O|0,M=B(M^I,12),H=H+M|0,O=B(O^H,8),I=I+O|0,M=B(M^I,7),E=E+N|0,O=B(O^E,16),w=w+O|0,N=B(N^w,12),E=E+N|0,O=B(O^E,8),w=w+O|0,N=B(N^w,7),K=K+T|0,k=B(k^K,16),I=I+k|0,T=B(T^I,12),K=K+T|0,k=B(k^K,8),I=I+k|0,T=B(T^I,7),S=S+M|0,P=B(P^S,16),V=V+P|0,M=B(M^V,12),S=S+M|0,P=B(P^S,8),V=V+P|0,M=B(M^V,7),H=H+U|0,_=B(_^H,16),b=b+_|0,U=B(U^b,12),H=H+U|0,_=B(_^H,8),b=b+_|0,U=B(U^b,7);let $=0;r[$++]=o+E|0,r[$++]=c+K|0,r[$++]=a+S|0,r[$++]=h+H|0,r[$++]=d+U|0,r[$++]=u+N|0,r[$++]=y+T|0,r[$++]=p+M|0,r[$++]=g+V|0,r[$++]=l+b|0,r[$++]=f+w|0,r[$++]=v+I|0,r[$++]=m+k|0,r[$++]=A+P|0,r[$++]=R+_|0,r[$++]=C+O|0}const Tr=vo(bo,{counterRight:!1,counterLength:4,allowShortKeys:!1});class Mr extends fr{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ue.hash(e);const r=nt(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return ue.exists(this),this.iHash.update(e),this}digestInto(e){ue.exists(this),ue.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:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const mt=(t,e,n)=>new Mr(t,e).update(n).digest();mt.create=(t,e)=>new Mr(t,e);function ln(t,e,n){return ue.hash(t),n===void 0&&(n=new Uint8Array(t.outputLen)),mt(t,nt(n),nt(e))}const fn=new Uint8Array([0]),Or=new Uint8Array;function Dr(t,e,n,r=32){if(ue.hash(t),ue.number(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);n===void 0&&(n=Or);const s=new Uint8Array(i*t.outputLen),o=mt.create(t,e),c=o._cloneInto(),a=new Uint8Array(o.outputLen);for(let h=0;h<i;h++)fn[0]=h+1,c.update(h===0?Or:a).update(n).update(fn).digestInto(a),s.set(a,t.outputLen*h),o._cloneInto(c);return o.destroy(),c.destroy(),a.fill(0),fn.fill(0),s.slice(0,r)}var wo=Object.defineProperty,q=(t,e)=>{for(var n in e)wo(t,n,{get:e[n],enumerable:!0})},Fe=Symbol("verified"),mo=t=>t instanceof Object;function Et(t){if(!mo(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var Eo={};q(Eo,{Queue:()=>Io,QueueNode:()=>Hr,binarySearch:()=>yn,bytesToHex:()=>D,hexToBytes:()=>z,insertEventIntoAscendingList:()=>So,insertEventIntoDescendingList:()=>Ko,normalizeURL:()=>xo,utf8Decoder:()=>we,utf8Encoder:()=>re});var we=new TextDecoder("utf-8"),re=new TextEncoder;function xo(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}function Ko(t,e){const[n,r]=yn(t,i=>e.id===i.id?0:e.created_at===i.created_at?-1:i.created_at-e.created_at);return r||t.splice(n,0,e),t}function So(t,e){const[n,r]=yn(t,i=>e.id===i.id?0:e.created_at===i.created_at?-1:e.created_at-i.created_at);return r||t.splice(n,0,e),t}function yn(t,e){let n=0,r=t.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=e(t[i]);if(s===0)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var Hr=class{constructor(t){x(this,"value");x(this,"next",null);x(this,"prev",null);this.value=t}},Io=class{constructor(){x(this,"first");x(this,"last");this.first=null,this.last=null}enqueue(t){const e=new Hr(t);return this.last?this.last===this.first?(this.last=e,this.last.prev=this.first,this.first.next=e):(e.prev=this.last,this.last.next=e,this.last=e):(this.first=e,this.last=e),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const e=this.first;return this.first=null,this.last=null,e.value}const t=this.first;return this.first=t.next,this.first&&(this.first.prev=null),t.value}},Ao=class{generateSecretKey(){return tt.utils.randomPrivateKey()}getPublicKey(t){return D(tt.getPublicKey(t))}finalizeEvent(t,e){const n=t;return n.pubkey=D(tt.getPublicKey(e)),n.id=_e(n),n.sig=D(tt.sign(_e(n),e)),n[Fe]=!0,n}verifyEvent(t){if(typeof t[Fe]=="boolean")return t[Fe];const e=_e(t);if(e!==t.id)return t[Fe]=!1,!1;try{const n=tt.verify(t.sig,e,t.pubkey);return t[Fe]=n,n}catch{return t[Fe]=!1,!1}}};function No(t){if(!Et(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function _e(t){let e=fe(re.encode(No(t)));return D(e)}var xt=new Ao,de=xt.generateSecretKey,ie=xt.getPublicKey,Q=xt.finalizeEvent,it=xt.verifyEvent,Po={};q(Po,{Application:()=>Na,BadgeAward:()=>$o,BadgeDefinition:()=>ma,BlockedRelaysList:()=>ia,BookmarkList:()=>ta,Bookmarksets:()=>va,Calendar:()=>Ba,CalendarEventRSVP:()=>_a,ChannelCreation:()=>Wr,ChannelHideMessage:()=>Jr,ChannelMessage:()=>Gr,ChannelMetadata:()=>Zr,ChannelMuteUser:()=>Yr,ClassifiedListing:()=>ka,ClientAuth:()=>Qr,CommunitiesList:()=>na,CommunityDefinition:()=>Ma,CommunityPostApproval:()=>jo,Contacts:()=>Ro,CreateOrUpdateProduct:()=>Ka,CreateOrUpdateStall:()=>xa,Curationsets:()=>ba,Date:()=>Ua,DirectMessageRelaysList:()=>ca,DraftClassifiedListing:()=>La,DraftLong:()=>Ia,Emojisets:()=>Aa,EncryptedDirectMessage:()=>Bo,EventDeletion:()=>_o,FileMetadata:()=>Mo,FileServerPreference:()=>ua,Followsets:()=>ya,GenericRepost:()=>wn,Genericlists:()=>pa,GiftWrap:()=>Xr,HTTPAuth:()=>mn,Handlerinformation:()=>Ta,Handlerrecommendation:()=>$a,Highlights:()=>Yo,InterestsList:()=>oa,Interestsets:()=>Ea,JobFeedback:()=>Wo,JobRequest:()=>Vo,JobResult:()=>Fo,Label:()=>zo,LightningPubRPC:()=>da,LiveChatMessage:()=>Oo,LiveEvent:()=>Pa,LongFormArticle:()=>Sa,Metadata:()=>Lo,Mutelist:()=>Xo,NWCWalletInfo:()=>ha,NWCWalletRequest:()=>ei,NWCWalletResponse:()=>la,NostrConnect:()=>fa,OpenTimestamps:()=>To,Pinlist:()=>Qo,PrivateDirectMessage:()=>Fr,ProblemTracker:()=>Do,ProfileBadges:()=>wa,PublicChatsList:()=>ra,Reaction:()=>bn,RecommendRelay:()=>Uo,RelayList:()=>ea,Relaysets:()=>ga,Report:()=>Ho,Reporting:()=>qo,Repost:()=>vn,Seal:()=>Vr,SearchRelaysList:()=>sa,ShortTextNote:()=>jr,Time:()=>Ra,UserEmojiList:()=>aa,UserStatuses:()=>Ca,Zap:()=>Jo,ZapGoal:()=>Zo,ZapRequest:()=>Go,classifyKind:()=>Co,isAddressableKind:()=>gn,isEphemeralKind:()=>zr,isKind:()=>ko,isRegularKind:()=>qr,isReplaceableKind:()=>pn});function qr(t){return 1e3<=t&&t<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(t)}function pn(t){return[0,3].includes(t)||1e4<=t&&t<2e4}function zr(t){return 2e4<=t&&t<3e4}function gn(t){return 3e4<=t&&t<4e4}function Co(t){return qr(t)?"regular":pn(t)?"replaceable":zr(t)?"ephemeral":gn(t)?"parameterized":"unknown"}function ko(t,e){const n=e instanceof Array?e:[e];return Et(t)&&n.includes(t.kind)||!1}var Lo=0,jr=1,Uo=2,Ro=3,Bo=4,_o=5,vn=6,bn=7,$o=8,Vr=13,Fr=14,wn=16,Wr=40,Zr=41,Gr=42,Jr=43,Yr=44,To=1040,Xr=1059,Mo=1063,Oo=1311,Do=1971,Ho=1984,qo=1984,zo=1985,jo=4550,Vo=5999,Fo=6999,Wo=7e3,Zo=9041,Go=9734,Jo=9735,Yo=9802,Xo=1e4,Qo=10001,ea=10002,ta=10003,na=10004,ra=10005,ia=10006,sa=10007,oa=10015,aa=10030,ca=10050,ua=10096,ha=13194,da=21e3,Qr=22242,ei=23194,la=23195,fa=24133,mn=27235,ya=3e4,pa=30001,ga=30002,va=30003,ba=30004,wa=30008,ma=30009,Ea=30015,xa=30017,Ka=30018,Sa=30023,Ia=30024,Aa=30030,Na=30078,Pa=30311,Ca=30315,ka=30402,La=30403,Ua=31922,Ra=31923,Ba=31924,_a=31925,$a=31989,Ta=31990,Ma=34550,Oa={};q(Oa,{getHex64:()=>En,getInt:()=>ti,getSubscriptionId:()=>Da,matchEventId:()=>Ha,matchEventKind:()=>za,matchEventPubkey:()=>qa});function En(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,i=t.slice(r).indexOf('"')+r+1;return t.slice(i,i+64)}function ti(t,e){let n=e.length,r=t.indexOf(`"${e}":`)+n+3,i=t.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function Da(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,i=t.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return t.slice(r+1,s)}function Ha(t,e){return e===En(t,"id")}function qa(t,e){return e===En(t,"pubkey")}function za(t,e){return e===ti(t,"kind")}var ja={};q(ja,{makeAuthEvent:()=>Va});function Va(t,e){return{kind:Qr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var Fa;try{Fa=WebSocket}catch{}var Wa;try{Wa=WebSocket}catch{}var Za={};q(Za,{BECH32_REGEX:()=>ni,Bech32MaxSize:()=>xn,NostrTypeGuard:()=>Ga,decode:()=>Kt,decodeNostrURI:()=>Ya,encodeBytes:()=>It,naddrEncode:()=>rc,neventEncode:()=>nc,noteEncode:()=>ec,nprofileEncode:()=>tc,npubEncode:()=>Qa,nsecEncode:()=>Xa});var Ga={isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")},xn=5e3,ni=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function Ja(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function Ya(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),Kt(t)}catch{return{type:"invalid",data:null}}}function Kt(t){var i,s,o,c,a,h,d;let{prefix:e,words:n}=je.decode(t,xn),r=new Uint8Array(je.fromWords(n));switch(e){case"nprofile":{let u=Kn(r);if(!((i=u[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:D(u[0][0]),relays:u[1]?u[1].map(y=>we.decode(y)):[]}}}case"nevent":{let u=Kn(r);if(!((s=u[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(u[2]&&u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(u[3]&&u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:D(u[0][0]),relays:u[1]?u[1].map(y=>we.decode(y)):[],author:(o=u[2])!=null&&o[0]?D(u[2][0]):void 0,kind:(c=u[3])!=null&&c[0]?parseInt(D(u[3][0]),16):void 0}}}case"naddr":{let u=Kn(r);if(!((a=u[0])!=null&&a[0]))throw new Error("missing TLV 0 for naddr");if(!((h=u[2])!=null&&h[0]))throw new Error("missing TLV 2 for naddr");if(u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((d=u[3])!=null&&d[0]))throw new Error("missing TLV 3 for naddr");if(u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:we.decode(u[0][0]),pubkey:D(u[2][0]),kind:parseInt(D(u[3][0]),16),relays:u[1]?u[1].map(y=>we.decode(y)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:D(r)};default:throw new Error(`unknown prefix ${e}`)}}function Kn(t){let e={},n=t;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(s)}return e}function Xa(t){return It("nsec",t)}function Qa(t){return It("npub",z(t))}function ec(t){return It("note",z(t))}function St(t,e){let n=je.toWords(e);return je.encode(t,n,xn)}function It(t,e){return St(t,e)}function tc(t){let e=Sn({0:[z(t.pubkey)],1:(t.relays||[]).map(n=>re.encode(n))});return St("nprofile",e)}function nc(t){let e;t.kind!==void 0&&(e=Ja(t.kind));let n=Sn({0:[z(t.id)],1:(t.relays||[]).map(r=>re.encode(r)),2:t.author?[z(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return St("nevent",n)}function rc(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let n=Sn({0:[re.encode(t.identifier)],1:(t.relays||[]).map(r=>re.encode(r)),2:[z(t.pubkey)],3:[new Uint8Array(e)]});return St("naddr",n)}function Sn(t){let e=[];return Object.entries(t).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),e.push(s)})}),gt(...e)}var ic={};q(ic,{decrypt:()=>sc,encrypt:()=>ri});function ri(t,e,n){const r=t instanceof Uint8Array?D(t):t,i=Be.getSharedSecret(r,"02"+e),s=ii(i);let o=Uint8Array.from(pr(16)),c=re.encode(n),a=Ur(s,o).encrypt(c),h=ve.encode(new Uint8Array(a)),d=ve.encode(new Uint8Array(o.buffer));return`${h}?iv=${d}`}function sc(t,e,n){const r=t instanceof Uint8Array?D(t):t;let[i,s]=n.split("?iv="),o=Be.getSharedSecret(r,"02"+e),c=ii(o),a=ve.decode(s),h=ve.decode(i),d=Ur(c,a).decrypt(h);return we.decode(d)}function ii(t){return t.slice(1,33)}var oc={};q(oc,{NIP05_REGEX:()=>In,isNip05:()=>ac,isValid:()=>hc,queryProfile:()=>si,searchDomain:()=>uc,useFetchImplementation:()=>cc});var In=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,ac=t=>In.test(t||""),At;try{At=fetch}catch{}function cc(t){At=t}async function uc(t,e=""){try{const n=`https://${t}/.well-known/nostr.json?name=${e}`,r=await At(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function si(t){var i;const e=t.match(In);if(!e)return null;const[,n="_",r]=e;try{const s=`https://${r}/.well-known/nostr.json?name=${n}`,o=await At(s,{redirect:"manual"});if(o.status!==200)throw Error("Wrong response code");const c=await o.json(),a=c.names[n];return a?{pubkey:a,relays:(i=c.relays)==null?void 0:i[a]}:null}catch{return null}}async function hc(t,e){const n=await si(e);return n?n.pubkey===t:!1}var dc={};q(dc,{parse:()=>lc});function lc(t){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=t.tags.length-1;i>=0;i--){const s=t.tags[i];if(s[0]==="e"&&s[1]){const[o,c,a,h,d]=s,u={id:c,relays:a?[a]:[],author:d};if(h==="root"){e.root=u;continue}if(h==="reply"){e.reply=u;continue}if(h==="mention"){e.mentions.push(u);continue}n?r=u:n=u,e.mentions.push(u);continue}if(s[0]==="q"&&s[1]){const[o,c,a]=s;e.quotes.push({id:c,relays:a?[a]:[]})}if(s[0]==="p"&&s[1]){e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return e.root||(e.root=r||n||e.reply),e.reply||(e.reply=n||e.root),[e.reply,e.root].forEach(i=>{if(!i)return;let s=e.mentions.indexOf(i);if(s!==-1&&e.mentions.splice(s,1),i.author){let o=e.profiles.find(c=>c.pubkey===i.author);o&&o.relays&&(i.relays||(i.relays=[]),o.relays.forEach(c=>{var a;((a=i.relays)==null?void 0:a.indexOf(c))===-1&&i.relays.push(c)}),o.relays=i.relays)}}),e.mentions.forEach(i=>{if(i.author){let s=e.profiles.find(o=>o.pubkey===i.author);s&&s.relays&&(i.relays||(i.relays=[]),s.relays.forEach(o=>{i.relays.indexOf(o)===-1&&i.relays.push(o)}),s.relays=i.relays)}}),e}var fc={};q(fc,{fetchRelayInformation:()=>pc,useFetchImplementation:()=>yc});var oi;try{oi=fetch}catch{}function yc(t){oi=t}async function pc(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var gc={};q(gc,{fastEventHash:()=>ci,getPow:()=>ai,minePow:()=>vc});function ai(t){let e=0;for(let n=0;n<64;n+=8){const r=parseInt(t.substring(n,n+8),16);if(r===0)e+=32;else{e+=Math.clz32(r);break}}return e}function vc(t,e){let n=0;const r=t,i=["nonce",n.toString(),e.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);if(s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString(),r.id=ci(r),ai(r.id)>=e)break}return r}function ci(t){return D(fe(re.encode(JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]))))}var bc={};q(bc,{unwrapEvent:()=>Cc,unwrapManyEvents:()=>kc,wrapEvent:()=>xi,wrapManyEvents:()=>Pc});var wc={};q(wc,{createRumor:()=>bi,createSeal:()=>wi,createWrap:()=>mi,unwrapEvent:()=>kn,unwrapManyEvents:()=>Ei,wrapEvent:()=>Nt,wrapManyEvents:()=>Ac});var j={};q(j,{decrypt:()=>Cn,encrypt:()=>Pn,getConversationKey:()=>An,v2:()=>Sc});var ui=1,hi=65535;function An(t,e){const n=Be.getSharedSecret(t,"02"+e).subarray(1,33);return ln(fe,n,"nip44-v2")}function di(t,e){const n=Dr(fe,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Nn(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;const e=1<<Math.floor(Math.log2(t-1))+1,n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function mc(t){if(!Number.isSafeInteger(t)||t<ui||t>hi)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function Ec(t){const e=re.encode(t),n=e.length,r=mc(n),i=new Uint8Array(Nn(n)-n);return gt(r,e,i)}function xc(t){const e=new DataView(t.buffer).getUint16(0),n=t.subarray(2,2+e);if(e<ui||e>hi||n.length!==e||t.length!==2+Nn(e))throw new Error("invalid padding");return we.decode(n)}function li(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=gt(n,e);return mt(fe,t,r)}function Kc(t){if(typeof t!="string")throw new Error("payload must be a valid string");const e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=ve.decode(t)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Pn(t,e,n=pr(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=di(e,n),o=Ec(t),c=Tr(r,i,o),a=li(s,c,n);return ve.encode(gt(new Uint8Array([2]),n,c,a))}function Cn(t,e){const{nonce:n,ciphertext:r,mac:i}=Kc(t),{chacha_key:s,chacha_nonce:o,hmac_key:c}=di(e,n),a=li(c,r,n);if(!Qs(a,i))throw new Error("invalid MAC");const h=Tr(s,o,r);return xc(h)}var Sc={utils:{getConversationKey:An,calcPaddedLen:Nn},encrypt:Pn,decrypt:Cn},Ic=2*24*60*60,fi=()=>Math.round(Date.now()/1e3),yi=()=>Math.round(fi()-Math.random()*Ic),pi=(t,e)=>An(t,e),gi=(t,e,n)=>Pn(JSON.stringify(t),pi(e,n)),vi=(t,e)=>JSON.parse(Cn(t.content,pi(e,t.pubkey)));function bi(t,e){const n={created_at:fi(),content:"",tags:[],...t,pubkey:ie(e)};return n.id=_e(n),n}function wi(t,e,n){return Q({kind:Vr,content:gi(t,e,n),created_at:yi(),tags:[]},e)}function mi(t,e){const n=de();return Q({kind:Xr,content:gi(t,n,e),created_at:yi(),tags:[["p",e]]},n)}function Nt(t,e,n){const r=bi(t,e),i=wi(r,e,n);return mi(i,n)}function Ac(t,e,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");const r=ie(e),i=[Nt(t,e,r)];return n.forEach(s=>{i.push(Nt(t,e,s))}),i}function kn(t,e){const n=vi(t,e);return vi(n,e)}function Ei(t,e){let n=[];return t.forEach(r=>{n.push(kn(r,e))}),n.sort((r,i)=>r.created_at-i.created_at),n}function Nc(t,e,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:Fr,tags:[],content:e};return(Array.isArray(t)?t:[t]).forEach(({publicKey:o,relayUrl:c})=>{i.tags.push(c?["p",o,c]:["p",o])}),r&&i.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&i.tags.push(["subject",n]),i}function xi(t,e,n,r,i){const s=Nc(e,n,r,i);return Nt(s,t,e.publicKey)}function Pc(t,e,n,r,i){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:ie(t)},...e].map(o=>xi(t,o,n,r,i))}var Cc=kn,kc=Ei,Lc={};q(Lc,{finishRepostEvent:()=>Uc,getRepostedEvent:()=>Rc,getRepostedEventPointer:()=>Ki});function Uc(t,e,n,r){var o;let i;const s=[...t.tags??[],["e",e.id,n],["p",e.pubkey]];return e.kind===jr?i=vn:(i=wn,s.push(["k",String(e.kind)])),Q({kind:i,tags:s,content:t.content===""||(o=e.tags)!=null&&o.find(c=>c[0]==="-")?"":JSON.stringify(e),created_at:t.created_at},r)}function Ki(t){if(![vn,wn].includes(t.kind))return;let e,n;for(let r=t.tags.length-1;r>=0&&(e===void 0||n===void 0);r--){const i=t.tags[r];i.length>=2&&(i[0]==="e"&&e===void 0?e=i:i[0]==="p"&&n===void 0&&(n=i))}if(e!==void 0)return{id:e[1],relays:[e[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function Rc(t,{skipVerification:e}={}){const n=Ki(t);if(n===void 0||t.content==="")return;let r;try{r=JSON.parse(t.content)}catch{return}if(r.id===n.id&&!(!e&&!it(r)))return r}var Bc={};q(Bc,{NOSTR_URI_REGEX:()=>Ln,parse:()=>$c,test:()=>_c});var Ln=new RegExp(`nostr:(${ni.source})`);function _c(t){return typeof t=="string"&&new RegExp(`^${Ln.source}$`).test(t)}function $c(t){const e=t.match(new RegExp(`^${Ln.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:Kt(e[1])}}var Tc={};q(Tc,{finishReactionEvent:()=>Mc,getReactedEventPointer:()=>Oc});function Mc(t,e,n){const r=e.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return Q({...t,kind:bn,tags:[...t.tags??[],...r,["e",e.id],["p",e.pubkey]],content:t.content??"+"},n)}function Oc(t){if(t.kind!==bn)return;let e,n;for(let r=t.tags.length-1;r>=0&&(e===void 0||n===void 0);r--){const i=t.tags[r];i.length>=2&&(i[0]==="e"&&e===void 0?e=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(e===void 0||n===void 0))return{id:e[1],relays:[e[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Dc={};q(Dc,{parse:()=>qc});var Hc=/\W/m,Si=/\W |\W$|$|,| /m;function*qc(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.indexOf(":",r);if(i===-1)break;if(t.substring(i-5,i)==="nostr"){const s=t.substring(i+60).match(Hc),o=s?i+60+s.index:e;try{let c,{data:a,type:h}=Kt(t.substring(i+1,o));switch(h){case"npub":c={pubkey:a};break;case"nsec":case"note":r=o+1;continue;default:c=a}n!==i-5&&(yield{type:"text",text:t.substring(n,i-5)}),yield{type:"reference",pointer:c},r=o,n=r;continue}catch{r=i+1;continue}}else if(t.substring(i-5,i)==="https"||t.substring(i-4,i)==="http"){const s=t.substring(i+4).match(Si),o=s?i+4+s.index:e,c=t[i-1]==="s"?5:4;try{let a=new URL(t.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid url");if(n!==i-c&&(yield{type:"text",text:t.substring(n,i-c)}),a.pathname.endsWith(".png")||a.pathname.endsWith(".jpg")||a.pathname.endsWith(".jpeg")||a.pathname.endsWith(".gif")||a.pathname.endsWith(".webp")){yield{type:"image",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp4")||a.pathname.endsWith(".avi")||a.pathname.endsWith(".webm")||a.pathname.endsWith(".mkv")){yield{type:"video",url:a.toString()},r=o,n=r;continue}if(a.pathname.endsWith(".mp3")||a.pathname.endsWith(".aac")||a.pathname.endsWith(".ogg")||a.pathname.endsWith(".opus")){yield{type:"audio",url:a.toString()},r=o,n=r;continue}yield{type:"url",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else if(t.substring(i-3,i)==="wss"||t.substring(i-2,i)==="ws"){const s=t.substring(i+4).match(Si),o=s?i+4+s.index:e,c=t[i-1]==="s"?3:2;try{let a=new URL(t.substring(i-c,o));if(a.hostname.indexOf(".")===-1)throw new Error("invalid ws url");n!==i-c&&(yield{type:"text",text:t.substring(n,i-c)}),yield{type:"relay",url:a.toString()},r=o,n=r;continue}catch{r=o+1;continue}}else{r=i+1;continue}}n!==e&&(yield{type:"text",text:t.substring(n)})}var zc={};q(zc,{channelCreateEvent:()=>jc,channelHideMessageEvent:()=>Wc,channelMessageEvent:()=>Fc,channelMetadataEvent:()=>Vc,channelMuteUserEvent:()=>Zc});var jc=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return Q({kind:Wr,tags:[...t.tags??[]],content:n,created_at:t.created_at},e)},Vc=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return Q({kind:Zr,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},Fc=(t,e)=>{const n=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&n.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),Q({kind:Gr,tags:[...n,...t.tags??[]],content:t.content,created_at:t.created_at},e)},Wc=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return Q({kind:Jr,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},Zc=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return Q({kind:Yr,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:n,created_at:t.created_at},e)},Gc={};q(Gc,{EMOJI_SHORTCODE_REGEX:()=>Ii,matchAll:()=>Jc,regex:()=>Un,replaceAll:()=>Yc});var Ii=/:(\w+):/,Un=()=>new RegExp(`\\B${Ii.source}\\B`,"g");function*Jc(t){const e=t.matchAll(Un());for(const n of e)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function Yc(t,e){return t.replaceAll(Un(),(n,r)=>e({shortcode:n,name:r}))}var Xc={};q(Xc,{useFetchImplementation:()=>Qc,validateGithub:()=>eu});var Rn;try{Rn=fetch}catch{}function Qc(t){Rn=t}async function eu(t,e,n){try{return await(await Rn(`https://gist.github.com/${e}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch{return!1}}var tu={};q(tu,{makeNwcRequestEvent:()=>ru,parseConnectionString:()=>nu});function nu(t){const{host:e,pathname:n,searchParams:r}=new URL(t),i=n||e,s=r.get("relay"),o=r.get("secret");if(!i||!s||!o)throw new Error("invalid connection string");return{pubkey:i,relay:s,secret:o}}async function ru(t,e,n){const i=ri(e,t,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:ei,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",t]]};return Q(s,e)}var iu={};q(iu,{normalizeIdentifier:()=>su});function su(t){return t=t.trim().toLowerCase(),t=t.normalize("NFKC"),Array.from(t).map(e=>new RegExp("\\p{Letter}","u").test(e)||new RegExp("\\p{Number}","u").test(e)?e:"-").join("")}var ou={};q(ou,{getSatoshisAmountFromBolt11:()=>lu,getZapEndpoint:()=>cu,makeZapReceipt:()=>du,makeZapRequest:()=>uu,useFetchImplementation:()=>au,validateZapRequest:()=>hu});var Bn;try{Bn=fetch}catch{}function au(t){Bn=t}async function cu(t){try{let e="",{lud06:n,lud16:r}=JSON.parse(t.content);if(n){let{words:o}=je.decode(n,1e3),c=je.fromWords(o);e=we.decode(c)}else if(r){let[o,c]=r.split("@");e=new URL(`/.well-known/lnurlp/${o}`,`https://${c}`).toString()}else return null;let s=await(await Bn(e)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function uu(t){let e={kind:9734,created_at:Math.round(Date.now()/1e3),content:t.comment||"",tags:[["p","pubkey"in t?t.pubkey:t.event.pubkey],["amount",t.amount.toString()],["relays",...t.relays]]};if("event"in t){if(e.tags.push(["e",t.event.id]),pn(t.event.kind)){const n=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(n)}else if(gn(t.event.kind)){let n=t.event.tags.find(([i,s])=>i==="d"&&s);if(!n)throw new Error("d tag not found or is empty");const r=["a",`${t.event.kind}:${t.event.pubkey}:${n[1]}`];e.tags.push(r)}e.tags.push(["k",t.event.kind.toString()])}return e}function hu(t){let e;try{e=JSON.parse(t)}catch{return"Invalid zap request JSON."}if(!Et(e))return"Zap request is not a valid Nostr event.";if(!it(e))return"Invalid signature on zap request.";let n=e.tags.find(([s,o])=>s==="p"&&o);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=e.tags.find(([s,o])=>s==="e"&&o);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([s,o])=>s==="relays"&&o)?null:"Zap request doesn't have a 'relays' tag."}function du({zapRequest:t,preimage:e,bolt11:n,paidAt:r}){let i=JSON.parse(t),s=i.tags.filter(([c])=>c==="e"||c==="p"||c==="a"),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",t]]};return e&&o.tags.push(["preimage",e]),o}function lu(t){if(t.length<50)return 0;t=t.substring(0,50);const e=t.lastIndexOf("1");if(e===-1)return 0;const n=t.substring(0,e);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const i=r[r.length-1],s=i.charCodeAt(0)-48,o=s>=0&&s<=9;let c=r.length-1;if(o&&c++,c<1)return 0;const a=parseInt(r.substring(0,c));switch(i){case"m":return a*1e5;case"u":return a*100;case"n":return a/10;case"p":return a/1e4;default:return a*1e8}}var fu={};q(fu,{getToken:()=>yu,hashPayload:()=>_n,unpackEventFromToken:()=>Ni,validateEvent:()=>Ri,validateEventKind:()=>Ci,validateEventMethodTag:()=>Li,validateEventPayloadTag:()=>Ui,validateEventTimestamp:()=>Pi,validateEventUrlTag:()=>ki,validateToken:()=>pu});var Ai="Nostr ";async function yu(t,e,n,r=!1,i){const s={kind:mn,tags:[["u",t],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",_n(i)]);const o=await n(s);return(r?Ai:"")+ve.encode(re.encode(JSON.stringify(o)))}async function pu(t,e,n){const r=await Ni(t).catch(s=>{throw s});return await Ri(r,e,n).catch(s=>{throw s})}async function Ni(t){if(!t)throw new Error("Missing token");t=t.replace(Ai,"");const e=we.decode(ve.decode(t));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function Pi(t){return t.created_at?Math.round(new Date().getTime()/1e3)-t.created_at<60:!1}function Ci(t){return t.kind===mn}function ki(t,e){const n=t.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===e:!1}function Li(t,e){const n=t.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===e.toLowerCase():!1}function _n(t){const e=fe(re.encode(JSON.stringify(t)));return D(e)}function Ui(t,e){const n=t.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=_n(e);return n.length>0&&n[1]===r}async function Ri(t,e,n,r){if(!it(t))throw new Error("Invalid nostr event, signature invalid");if(!Ci(t))throw new Error("Invalid nostr event, kind invalid");if(!Pi(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!ki(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!Li(t,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!Ui(t,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const $e=1060,Pt=30078,Ct=1059,Te=10078,$n=14,gu=100,vu=1;function Tn(t){return JSON.stringify({version:vu,rootKey:D(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:D(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:D(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?D(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?D(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys).map(([e,n])=>[e,{headerKeys:n.headerKeys.map(r=>D(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,D(i)]))}]))})}function Mn(t){const e=JSON.parse(t);if(!e.version){const n={};return e.skippedMessageKeys&&Object.entries(e.skippedMessageKeys).forEach(([r,i])=>{var s;n[r]={headerKeys:((s=e.skippedHeaderKeys)==null?void 0:s[r])||[],messageKeys:i}}),{rootKey:z(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:z(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:z(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?z(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?z(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:n}}return{rootKey:z(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:z(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:z(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?z(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?z(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(e.skippedKeys||{}).map(([n,r])=>[n,{headerKeys:r.headerKeys.map(i=>z(i)),messageKeys:Object.fromEntries(Object.entries(r.messageKeys).map(([i,s])=>[i,z(s)]))}]))}}function Bi(t){return{rootKey:new Uint8Array(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:new Uint8Array(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:new Uint8Array(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?new Uint8Array(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?new Uint8Array(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys).map(([e,n])=>[e,{headerKeys:n.headerKeys.map(r=>new Uint8Array(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,new Uint8Array(i)]))}]))}}async function*bu(t){const e=[];let n=null;const r=t.onEvent(i=>{n?(n(i),n=null):e.push(i)});try{for(;;)e.length>0?yield e.shift():yield new Promise(i=>{n=i})}finally{r()}}function Me(t,e=new Uint8Array(32),n=1){const r=ln(fe,t,e),i=[];for(let s=1;s<=n;s++)i.push(Dr(fe,r,new Uint8Array([s]),32));return i}function wu(t,e){return`${t}:${e}`}function mu(t){var n;const e=(n=t.tags)==null?void 0:n.find(r=>r[0]==="ms");return e?parseInt(e[1]):t.created_at*1e3}const Eu=1e3,xu="0000000000000000000000000000000000000000000000000000000000000000";class We{constructor(e,n){x(this,"skippedSubscription");x(this,"nostrUnsubscribe");x(this,"nostrNextUnsubscribe");x(this,"internalSubscriptions",new Map);x(this,"currentInternalSubscriptionId",0);x(this,"name");this.nostrSubscribe=e,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(e,n,r,i,s,o){const c=de();let a,h,d,u;i?([a,h]=Me(s,j.getConversationKey(c,n),2),d={publicKey:ie(r),privateKey:r},u={publicKey:ie(c),privateKey:c}):(a=s,h=void 0,d=void 0,u={publicKey:ie(r),privateKey:r});const y={rootKey:a,theirNextNostrPublicKey:n,ourCurrentNostrKey:d,ourNextNostrKey:u,receivingChainKey:void 0,sendingChainKey:h,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedKeys:{}},p=new We(e,y);return o&&(p.name=o),p}send(e){return this.sendEvent({content:e,kind:$n})}sendEvent(e){if(!this.state.theirNextNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");if("sig"in e)throw new Error("Event must be unsigned "+JSON.stringify(e));const n=Date.now(),r={...e,content:e.content||"",kind:e.kind||$e,created_at:e.created_at||Math.floor(n/1e3),tags:e.tags||[],pubkey:e.pubkey||xu};r.tags.some(([h])=>h==="ms")||r.tags.push(["ms",String(n)]),r.id=_e(r);const[i,s]=this.ratchetEncrypt(JSON.stringify(r)),o=j.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNextNostrPublicKey),c=j.encrypt(JSON.stringify(i),o);return{event:Q({content:s,kind:$e,tags:[["header",c]],created_at:Math.floor(n/1e3)},this.state.ourCurrentNostrKey.privateKey),innerEvent:r}}onEvent(e){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,e),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var e,n,r;(e=this.nostrUnsubscribe)==null||e.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this),(r=this.skippedSubscription)==null||r.call(this),this.internalSubscriptions.clear()}ratchetEncrypt(e){const[n,r]=Me(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,previousChainLength:this.state.previousSendingChainMessageCount},j.encrypt(e,r)]}ratchetDecrypt(e,n,r){const i=this.trySkippedMessageKeys(e,n,r);if(i)return i;this.skipMessageKeys(e.number,r);const[s,o]=Me(this.state.receivingChainKey,new Uint8Array([1]),2);return this.state.receivingChainKey=s,this.state.receivingChainMessageNumber++,j.decrypt(n,o)}ratchetStep(){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0;const e=j.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[n,r]=Me(this.state.rootKey,e,2);this.state.receivingChainKey=r,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const i=de();this.state.ourNextNostrKey={publicKey:ie(i),privateKey:i};const s=j.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[o,c]=Me(n,s,2);this.state.rootKey=o,this.state.sendingChainKey=c}skipMessageKeys(e,n){if(!(e<=this.state.receivingChainMessageNumber)){if(e>this.state.receivingChainMessageNumber+Eu)throw new Error("Too many skipped messages");if(!this.state.skippedKeys[n]){if(this.state.skippedKeys[n]={headerKeys:[],messageKeys:{}},this.state.ourCurrentNostrKey){const i=j.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(i)||this.state.skippedKeys[n].headerKeys.push(i)}const r=j.getConversationKey(this.state.ourNextNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(r)||this.state.skippedKeys[n].headerKeys.push(r)}for(;this.state.receivingChainMessageNumber<e;){const[r,i]=Me(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r,this.state.skippedKeys[n].messageKeys[this.state.receivingChainMessageNumber]=i,this.state.receivingChainMessageNumber++}}}trySkippedMessageKeys(e,n,r){const i=this.state.skippedKeys[r];if(!i)return null;const s=i.messageKeys[e.number];return s?(delete i.messageKeys[e.number],Object.keys(i.messageKeys).length===0&&delete this.state.skippedKeys[r],j.decrypt(n,s)):null}decryptHeader(e){const n=e.tags[0][1];if(this.state.ourCurrentNostrKey){const s=j.getConversationKey(this.state.ourCurrentNostrKey.privateKey,e.pubkey);try{return[JSON.parse(j.decrypt(n,s)),!1,!1]}catch{}}const r=j.getConversationKey(this.state.ourNextNostrKey.privateKey,e.pubkey);try{return[JSON.parse(j.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedKeys[e.pubkey];if(i!=null&&i.headerKeys)for(const s of i.headerKeys)try{return[JSON.parse(j.decrypt(n,s)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(e){var i,s;const n=Bi(this.state);let r=!1;try{const[o,c,a]=this.decryptHeader(e);if(!a&&this.state.theirNextNostrPublicKey!==o.nextPublicKey&&(this.state.theirCurrentNostrPublicKey=this.state.theirNextNostrPublicKey,this.state.theirNextNostrPublicKey=o.nextPublicKey,r=!0),!a)c&&(this.skipMessageKeys(o.previousChainLength,e.pubkey),this.ratchetStep());else if(!((i=this.state.skippedKeys[e.pubkey])!=null&&i.messageKeys[o.number]))return;const h=this.ratchetDecrypt(o,e.content,e.pubkey),d=JSON.parse(h);if(!Et(d)){this.state=n;return}if(d.id!==_e(d)){this.state=n;return}r&&((s=this.nostrUnsubscribe)==null||s.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},u=>this.handleNostrEvent(u))),this.internalSubscriptions.forEach(u=>u(d,e))}catch(o){if(this.state=n,o instanceof Error&&(o.message.includes("Failed to decrypt header")||o.message==="invalid MAC"))return;throw o}}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)),this.state.theirCurrentNostrPublicKey&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:[this.state.theirCurrentNostrPublicKey],kinds:[$e]},n=>this.handleNostrEvent(n)));const e=Object.keys(this.state.skippedKeys);e.length&&(this.skippedSubscription=this.nostrSubscribe({authors:e,kinds:[$e]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function kt(t,e){const n=Be.getSharedSecret(t,"02"+e).subarray(1,33);return ln(fe,n,"nip44-v2")}function st(){const t=de();return{publicKey:ie(t),privateKey:t}}function On(){return D(de())}function _i(){return D(de()).slice(0,16)}const Ku=2*24*60*60,$i=()=>Math.round(Date.now()/1e3),Su=()=>Math.round($i()-Math.random()*Ku);async function Dn(t){const{inviteeSessionPublicKey:e,inviteePublicKey:n,inviteePrivateKey:r,inviterPublicKey:i,inviterEphemeralPublicKey:s,sharedSecret:o,deviceId:c,encrypt:a}=t,h=z(o),d=a??(async(m,A)=>{if(!r)throw new Error("inviteePrivateKey is required when encrypt function is not provided");return j.encrypt(m,kt(r,A))}),u=JSON.stringify({sessionKey:e,deviceId:c}),y=await d(u,i),p={pubkey:n,content:j.encrypt(y,h),created_at:$i()},g=de(),l=ie(g),f=JSON.stringify(p),v={kind:Ct,pubkey:l,content:j.encrypt(f,kt(g,s)),created_at:Su(),tags:[["p",s]]};return{innerEvent:p,envelope:v,randomSenderPublicKey:l,randomSenderPrivateKey:g}}async function Lt(t){const{envelopeContent:e,envelopeSenderPubkey:n,inviterEphemeralPrivateKey:r,inviterPrivateKey:i,sharedSecret:s,decrypt:o}=t,c=z(s),a=j.decrypt(e,kt(r,n)),h=JSON.parse(a),d=h.pubkey,u=j.decrypt(h.content,c),p=await(o??(async(f,v)=>{if(!i)throw new Error("inviterPrivateKey is required when decrypt function is not provided");return j.decrypt(f,kt(i,v))}))(u,d);let g,l;try{const f=JSON.parse(p);g=f.sessionKey,l=f.deviceId}catch{g=p}return{inviteeIdentity:d,inviteeSessionPublicKey:g,deviceId:l}}function Ze(t){const{nostrSubscribe:e,theirPublicKey:n,ourSessionPrivateKey:r,sharedSecret:i,isSender:s,name:o}=t,c=z(i);return We.init(e,n,r,s,c,o)}const Iu=()=>Math.round(Date.now()/1e3);class Oe{constructor(e,n,r,i,s,o,c=[],a=Iu()){this.inviterEphemeralPublicKey=e,this.sharedSecret=n,this.inviter=r,this.inviterEphemeralPrivateKey=i,this.deviceId=s,this.maxUses=o,this.usedBy=c,this.createdAt=a}static createNew(e,n,r){if(!e)throw new Error("Inviter public key is required");const i=st(),s=On();return new Oe(i.publicKey,s,e,i.privateKey,n,r)}static fromUrl(e){const r=new URL(e).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let s;try{s=JSON.parse(i)}catch(h){throw new Error("Invite data in URL hash is not valid JSON: "+h)}const{inviter:o,ephemeralKey:c,sharedSecret:a}=s;if(!o||!c||!a)throw new Error("Missing required fields (inviter, ephemeralKey, sharedSecret) in invite data.");return new Oe(c,a,o)}static deserialize(e){const n=JSON.parse(e);return new Oe(n.inviterEphemeralPublicKey,n.sharedSecret,n.inviter,n.inviterEphemeralPrivateKey?new Uint8Array(n.inviterEphemeralPrivateKey):void 0,n.deviceId,n.maxUses,n.usedBy,n.createdAt)}static fromEvent(e){var a,h,d,u;if(!e.sig)throw new Error("Event is not signed");if(!it(e))throw new Error("Event signature is invalid");const{tags:n}=e;if(!n)throw new Error("Invalid invite event: missing tags");const r=(a=n.find(([y])=>y==="ephemeralKey"))==null?void 0:a[1],i=(h=n.find(([y])=>y==="sharedSecret"))==null?void 0:h[1],s=e.pubkey,o=(d=n.find(([y])=>y==="d"))==null?void 0:d[1],c=(u=o==null?void 0:o.split("/"))==null?void 0:u[2];if(!r||!i)throw new Error("Invalid invite event: missing session key or sharedSecret");return new Oe(r,i,s,void 0,c)}static fromUser(e,n,r){const i={kinds:[Pt],authors:[e],"#l":["double-ratchet/invites"]},s=new Set;return n(i,c=>{if(c.pubkey!==e){console.error("Got invite event from wrong user",c.pubkey,"expected",e);return}if(!s.has(c.id)){s.add(c.id);try{const a=Oe.fromEvent(c);r(a)}catch{}}})}serialize(){return JSON.stringify({inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,inviter:this.inviter,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey?Array.from(this.inviterEphemeralPrivateKey):void 0,deviceId:this.deviceId,maxUses:this.maxUses,usedBy:this.usedBy,createdAt:this.createdAt})}getUrl(e="https://iris.to"){const n={inviter:this.inviter,ephemeralKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret},r=new URL(e);return r.hash=encodeURIComponent(JSON.stringify(n)),r.toString()}getEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Pt,pubkey:this.inviter,content:"",created_at:this.createdAt,tags:[["ephemeralKey",this.inviterEphemeralPublicKey],["sharedSecret",this.sharedSecret],["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}getDeletionEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Pt,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}async accept(e,n,r,i){const s=st(),o=this.inviter||this.inviterEphemeralPublicKey,c=Ze({nostrSubscribe:e,theirPublicKey:this.inviterEphemeralPublicKey,ourSessionPrivateKey:s.privateKey,sharedSecret:this.sharedSecret,isSender:!0}),a=typeof r=="function"?r:void 0,h=typeof r=="function"?void 0:r,d=await Dn({inviteeSessionPublicKey:s.publicKey,inviteePublicKey:n,inviteePrivateKey:h,inviterPublicKey:o,inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,deviceId:i,encrypt:a});return{session:c,event:Q(d.envelope,d.randomSenderPrivateKey)}}listen(e,n,r){if(!this.inviterEphemeralPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[Ct],"#p":[this.inviterEphemeralPublicKey]};return n(i,async s=>{try{if(this.maxUses&&this.usedBy.length>=this.maxUses)return;const o=typeof e=="function"?e:void 0,c=typeof e=="function"?void 0:e,a=await Lt({envelopeContent:s.content,envelopeSenderPubkey:s.pubkey,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey,inviterPrivateKey:c,sharedSecret:this.sharedSecret,decrypt:o});this.usedBy.push(a.inviteeIdentity);const h=Ze({nostrSubscribe:n,theirPublicKey:a.inviteeSessionPublicKey,ourSessionPrivateKey:this.inviterEphemeralPrivateKey,sharedSecret:this.sharedSecret,isSender:!1,name:s.id});r(h,a.inviteeIdentity,a.deviceId)}catch{}})}}const Ti=()=>Math.round(Date.now()/1e3),Au=t=>t.length>=6&&t[0]==="device"&&t.slice(1,6).every(e=>typeof e=="string"),Nu=t=>t.length>=2&&t[0]==="removed"&&typeof t[1]=="string";class ne{constructor(e,n=[],r=[]){x(this,"devices",new Map);x(this,"removedDeviceIds",new Set);this.ownerPublicKey=e,this.removedDeviceIds=new Set(r),n.filter(i=>!this.removedDeviceIds.has(i.deviceId)).forEach(i=>this.devices.set(i.deviceId,i))}createDevice(e,n){const r=st();return{ephemeralPublicKey:r.publicKey,ephemeralPrivateKey:r.privateKey,sharedSecret:On(),deviceId:n||_i(),deviceLabel:e,createdAt:Ti(),identityPubkey:this.ownerPublicKey}}addDevice(e){this.removedDeviceIds.has(e.deviceId)||this.devices.has(e.deviceId)||this.devices.set(e.deviceId,e)}removeDevice(e){this.devices.delete(e),this.removedDeviceIds.add(e)}getDevice(e){return this.devices.get(e)}getAllDevices(){return Array.from(this.devices.values())}getRemovedDeviceIds(){return Array.from(this.removedDeviceIds)}updateDeviceLabel(e,n){const r=this.devices.get(e);r&&(r.deviceLabel=n)}getEvent(){const e=this.getAllDevices().map(r=>["device",r.ephemeralPublicKey,r.sharedSecret,r.deviceId,String(r.createdAt),r.identityPubkey]),n=this.getRemovedDeviceIds().map(r=>["removed",r]);return{kind:Te,pubkey:this.ownerPublicKey,content:"",created_at:Ti(),tags:[["d","double-ratchet/invite-list"],["version","1"],...e,...n]}}static fromEvent(e){if(!e.sig)throw new Error("Event is not signed");if(!it(e))throw new Error("Event signature is invalid");const n=e.tags.filter(Au).map(([,i,s,o,c,a])=>({ephemeralPublicKey:i,sharedSecret:s,deviceId:o,deviceLabel:o,createdAt:parseInt(c,10)||e.created_at,identityPubkey:a})),r=e.tags.filter(Nu).map(([,i])=>i);return new ne(e.pubkey,n,r)}serialize(){const e=this.getAllDevices().map(n=>({...n,ephemeralPrivateKey:n.ephemeralPrivateKey?Array.from(n.ephemeralPrivateKey):void 0}));return JSON.stringify({ownerPublicKey:this.ownerPublicKey,devices:e,removedDeviceIds:this.getRemovedDeviceIds()})}static deserialize(e){const n=JSON.parse(e),r=n.devices.map(i=>({...i,ephemeralPrivateKey:i.ephemeralPrivateKey?new Uint8Array(i.ephemeralPrivateKey):void 0}));return new ne(n.ownerPublicKey,r,n.removedDeviceIds||[])}merge(e){const n=new Set([...this.removedDeviceIds,...e.removedDeviceIds]),r=[...this.devices.values(),...e.devices.values()].reduce((s,o)=>{const c=s.get(o.deviceId);return s.set(o.deviceId,c?{...o,ephemeralPrivateKey:c.ephemeralPrivateKey||o.ephemeralPrivateKey}:o),s},new Map),i=Array.from(r.values()).filter(s=>!n.has(s.deviceId));return new ne(this.ownerPublicKey,i,Array.from(n))}async accept(e,n,r,i,s){const o=this.devices.get(e);if(!o)throw new Error(`Device ${e} not found in invite list`);const c=st(),a=Ze({nostrSubscribe:n,theirPublicKey:o.ephemeralPublicKey,ourSessionPrivateKey:c.privateKey,sharedSecret:o.sharedSecret,isSender:!0}),h=typeof i=="function"?i:void 0,d=typeof i=="function"?void 0:i,u=await Dn({inviteeSessionPublicKey:c.publicKey,inviteePublicKey:r,inviteePrivateKey:d,inviterPublicKey:o.identityPubkey,inviterEphemeralPublicKey:o.ephemeralPublicKey,sharedSecret:o.sharedSecret,deviceId:s,encrypt:h});return{session:a,event:Q(u.envelope,u.randomSenderPrivateKey)}}listen(e,n,r){const s=this.getAllDevices().filter(h=>!!h.ephemeralPrivateKey);if(s.length===0)return()=>{};const o=s.map(h=>h.ephemeralPublicKey),c=typeof e=="function"?e:void 0,a=typeof e=="function"?void 0:e;return n({kinds:[Ct],"#p":o},async h=>{var y;const d=(y=h.tags.find(p=>p[0]==="p"))==null?void 0:y[1],u=s.find(p=>p.ephemeralPublicKey===d);if(!(!u||!u.ephemeralPrivateKey))try{const p=await Lt({envelopeContent:h.content,envelopeSenderPubkey:h.pubkey,inviterEphemeralPrivateKey:u.ephemeralPrivateKey,inviterPrivateKey:a,sharedSecret:u.sharedSecret,decrypt:c}),g=Ze({nostrSubscribe:n,theirPublicKey:p.inviteeSessionPublicKey,ourSessionPrivateKey:u.ephemeralPrivateKey,sharedSecret:u.sharedSecret,isSender:!1,name:h.id});r(g,p.inviteeIdentity,p.deviceId,u.deviceId)}catch{}})}}class ot{constructor(){x(this,"store",new Map)}async get(e){return this.store.get(e)}async put(e,n){this.store.set(e,n)}async del(e){this.store.delete(e)}async list(e=""){const n=[],r=Array.from(this.store.keys());for(const i of r)i.startsWith(e)&&n.push(i);return n}}class Pu{constructor(e="session_"){x(this,"keyPrefix");this.keyPrefix=e}getFullKey(e){return`${this.keyPrefix}${e}`}async get(e){try{const n=localStorage.getItem(this.getFullKey(e));return n?JSON.parse(n):void 0}catch{return}}async put(e,n){try{localStorage.setItem(this.getFullKey(e),JSON.stringify(n))}catch(r){throw console.error(`Failed to put key ${e} to localStorage:`,r),r}}async del(e){try{localStorage.removeItem(this.getFullKey(e))}catch{}}async list(e=""){const n=[],r=this.getFullKey(e);try{for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);s&&s.startsWith(r)&&n.push(s.substring(this.keyPrefix.length))}}catch{}return n}}class Hn{constructor(e,n,r,i,s,o,c,a){x(this,"storageVersion","1");x(this,"versionPrefix");x(this,"deviceId");x(this,"storage");x(this,"nostrSubscribe");x(this,"nostrPublish");x(this,"identityKey");x(this,"ourPublicKey");x(this,"ownerPublicKey");x(this,"inviteKeys");x(this,"userRecords",new Map);x(this,"messageHistory",new Map);x(this,"delegateToOwner",new Map);x(this,"ourInviteResponseSubscription",null);x(this,"inviteSubscriptions",new Map);x(this,"sessionSubscriptions",new Map);x(this,"internalSubscriptions",new Set);x(this,"initialized",!1);this.userRecords=new Map,this.nostrSubscribe=i,this.nostrPublish=s,this.ourPublicKey=e,this.identityKey=n,this.deviceId=r,this.ownerPublicKey=o,this.inviteKeys=c,this.storage=a||new ot,this.versionPrefix=`v${this.storageVersion}`}async init(){if(this.initialized)return;this.initialized=!0,await this.runMigrations().catch(n=>{console.error("Failed to run migrations:",n)}),await this.loadAllUserRecords().catch(n=>{console.error("Failed to load user records:",n)});const e=this.getOrCreateUserRecord(this.ownerPublicKey);this.upsertDeviceRecord(e,this.deviceId),this.startInviteResponseListener(),this.setupUser(this.ownerPublicKey)}startInviteResponseListener(){const{publicKey:e,privateKey:n}=this.inviteKeys.ephemeralKeypair,r=this.inviteKeys.sharedSecret;this.ourInviteResponseSubscription=this.nostrSubscribe({kinds:[1059],"#p":[e]},async i=>{try{const s=await Lt({envelopeContent:i.content,envelopeSenderPubkey:i.pubkey,inviterEphemeralPrivateKey:n,inviterPrivateKey:this.identityKey instanceof Uint8Array?this.identityKey:void 0,sharedSecret:r,decrypt:this.identityKey instanceof Uint8Array?void 0:this.identityKey.decrypt});if(s.deviceId===this.deviceId)return;const o=this.resolveToOwner(s.inviteeIdentity),c=this.getOrCreateUserRecord(o),a=this.upsertDeviceRecord(c,s.deviceId||"default");if(a.hasResponderSession)return;const h=s.inviteeSessionPublicKey,d=a.activeSession,u=a.inactiveSessions||[];if((d?[d,...u]:u).some(l=>{var f,v,m;return((f=l.state)==null?void 0:f.receivingChainKey)!==void 0||((v=l.state)==null?void 0:v.theirNextNostrPublicKey)===h||((m=l.state)==null?void 0:m.theirCurrentNostrPublicKey)===h}))return;const g=Ze({nostrSubscribe:this.nostrSubscribe,theirPublicKey:s.inviteeSessionPublicKey,ourSessionPrivateKey:n,sharedSecret:r,isSender:!1,name:i.id});a.hasResponderSession=!0,this.attachSessionSubscription(o,a,g,!0),this.storeUserRecord(o).catch(console.error)}catch{}})}getOrCreateUserRecord(e){let n=this.userRecords.get(e);return n||(n={publicKey:e,devices:new Map},this.userRecords.set(e,n)),n}upsertDeviceRecord(e,n){if(!n)throw new Error("Device record must include a deviceId");const r=e.devices.get(n);if(r)return r;const i={deviceId:n,inactiveSessions:[],createdAt:Date.now()};return e.devices.set(n,i),i}sessionKey(e,n,r){return`${this.sessionKeyPrefix(e)}${n}/${r}`}sessionKeyPrefix(e){return`${this.versionPrefix}/session/${e}/`}userRecordKey(e){return`${this.userRecordKeyPrefix()}${e}`}userRecordKeyPrefix(){return`${this.versionPrefix}/user/`}versionKey(){return"storage-version"}resolveToOwner(e){return this.delegateToOwner.get(e)||e}updateDelegateMapping(e,n){for(const r of n.getAllDevices())r.identityPubkey&&this.delegateToOwner.set(r.identityPubkey,e)}subscribeToUserInviteList(e,n){return this.nostrSubscribe({kinds:[Te],authors:[e],"#d":["double-ratchet/invite-list"]},r=>{try{const i=ne.fromEvent(r);this.updateDelegateMapping(e,i),n(i)}catch{}})}attachSessionSubscription(e,n,r,i=!1){if(n.staleAt!==void 0)return;const s=this.sessionKey(e,n.deviceId,r.name);if(this.sessionSubscriptions.has(s))return;const o=n,c=h=>{const d=o.activeSession;if(!d){o.activeSession=h;return}if(d===h||d.name===h.name){o.activeSession=h;return}o.inactiveSessions=o.inactiveSessions.filter(u=>u!==d&&u.name!==d.name),o.inactiveSessions.push(d),o.inactiveSessions=o.inactiveSessions.slice(-1),o.activeSession=h};i?o.inactiveSessions.some(d=>d===r||d.name===r.name)||(o.inactiveSessions.push(r),o.inactiveSessions=o.inactiveSessions.slice(-1)):c(r);const a=r.onEvent(h=>{for(const d of this.internalSubscriptions)d(h,e);c(r),this.storeUserRecord(e).catch(console.error)});this.storeUserRecord(e).catch(console.error),this.sessionSubscriptions.set(s,a)}attachInviteListSubscription(e,n){const r=`invitelist:${e}`;if(this.inviteSubscriptions.has(r))return;const i=this.subscribeToUserInviteList(e,async s=>{n&&await n(s)});this.inviteSubscriptions.set(r,i)}setupUser(e){const n=this.getOrCreateUserRecord(e),r=async(i,s)=>{const o=this.upsertDeviceRecord(n,s),c=this.identityKey instanceof Uint8Array?this.identityKey:this.identityKey.encrypt,{session:a,event:h}=await i.accept(s,this.nostrSubscribe,this.ourPublicKey,c,this.deviceId);return this.nostrPublish(h).then(()=>this.attachSessionSubscription(e,o,a)).then(()=>this.sendMessageHistory(e,s)).catch(console.error)};this.attachInviteListSubscription(e,async i=>{const s=i.getAllDevices();for(const o of i.getRemovedDeviceIds())await this.cleanupDevice(e,o);for(const o of s)n.devices.has(o.deviceId)||await r(i,o.deviceId)})}onEvent(e){return this.internalSubscriptions.add(e),()=>{this.internalSubscriptions.delete(e)}}getDeviceId(){return this.deviceId}getUserRecords(){return this.userRecords}close(){var e;for(const n of this.inviteSubscriptions.values())n();for(const n of this.sessionSubscriptions.values())n();(e=this.ourInviteResponseSubscription)==null||e.call(this)}deactivateCurrentSessions(e){const n=this.userRecords.get(e);if(n){for(const r of n.devices.values())r.activeSession&&(r.inactiveSessions.push(r.activeSession),r.activeSession=void 0);this.storeUserRecord(e).catch(console.error)}}async deleteUser(e){await this.init();const n=this.userRecords.get(e);if(n){for(const s of n.devices.values()){s.activeSession&&this.removeSessionSubscription(e,s.deviceId,s.activeSession.name);for(const o of s.inactiveSessions)this.removeSessionSubscription(e,s.deviceId,o.name)}this.userRecords.delete(e)}const r=`invitelist:${e}`,i=this.inviteSubscriptions.get(r);i&&(i(),this.inviteSubscriptions.delete(r)),this.messageHistory.delete(e),await Promise.allSettled([this.deleteUserSessionsFromStorage(e),this.storage.del(this.userRecordKey(e))])}removeSessionSubscription(e,n,r){const i=this.sessionKey(e,n,r),s=this.sessionSubscriptions.get(i);s&&(s(),this.sessionSubscriptions.delete(i))}async deleteUserSessionsFromStorage(e){const n=this.sessionKeyPrefix(e),r=await this.storage.list(n);await Promise.all(r.map(i=>this.storage.del(i)))}async sendMessageHistory(e,n){const r=this.messageHistory.get(e)||[],i=this.userRecords.get(e);if(!i)return;const s=i.devices.get(n);if(s&&s.staleAt===void 0)for(const o of r){const{activeSession:c}=s;if(!c)continue;const{event:a}=c.sendEvent(o);await this.nostrPublish(a),await this.storeUserRecord(e)}}async sendEvent(e,n){await this.init();const r=n,i=new Set([e,this.ownerPublicKey]);for(const u of i){const y=this.messageHistory.get(u)||[];this.messageHistory.set(u,[...y,r])}const s=this.getOrCreateUserRecord(e),o=this.getOrCreateUserRecord(this.ownerPublicKey);this.setupUser(e),this.setupUser(this.ownerPublicKey);const c=Array.from(s.devices.values()).filter(u=>u.staleAt===void 0),a=Array.from(o.devices.values()).filter(u=>u.staleAt===void 0),h=new Map;for(const u of[...c,...a])u.deviceId!==this.deviceId&&h.set(u.deviceId,u);const d=Array.from(h.values());return Promise.allSettled(d.map(async u=>{const{activeSession:y}=u;if(!y)return;const{event:p}=y.sendEvent(n);await this.nostrPublish(p).catch(console.error)})).then(()=>{this.storeUserRecord(e),this.ownerPublicKey!==e&&this.storeUserRecord(this.ownerPublicKey)}).catch(console.error),r}async sendMessage(e,n,r={}){const{kind:i=$n,tags:s=[]}=r,o=Date.now(),c=this.buildMessageTags(e,s),a={content:n,kind:i,created_at:Math.floor(o/1e3),tags:c,pubkey:this.ourPublicKey,id:""};return a.tags.some(([h])=>h==="ms")||a.tags.push(["ms",String(o)]),a.id=_e(a),this.sendEvent(e,a).catch(console.error),a}async cleanupDevice(e,n){const r=this.userRecords.get(e);if(!r)return;const i=r.devices.get(n);if(i){i.activeSession&&this.removeSessionSubscription(e,n,i.activeSession.name);for(const s of i.inactiveSessions)this.removeSessionSubscription(e,n,s.name);i.activeSession=void 0,i.inactiveSessions=[],i.staleAt=Date.now(),await this.storeUserRecord(e).catch(console.error)}}buildMessageTags(e,n){return n.some(s=>s[0]==="p"&&s[1]===e)?[...n]:[["p",e],...n]}storeUserRecord(e){var r;const n={publicKey:e,devices:Array.from(((r=this.userRecords.get(e))==null?void 0:r.devices.entries())||[]).map(([,i])=>({deviceId:i.deviceId,activeSession:i.activeSession?Tn(i.activeSession.state):null,inactiveSessions:i.inactiveSessions.map(s=>Tn(s.state)),createdAt:i.createdAt,staleAt:i.staleAt,hasResponderSession:i.hasResponderSession}))};return this.storage.put(this.userRecordKey(e),n)}loadUserRecord(e){return this.storage.get(this.userRecordKey(e)).then(n=>{if(!n)return;const r=new Map;for(const i of n.devices){const{deviceId:s,activeSession:o,inactiveSessions:c,createdAt:a,staleAt:h,hasResponderSession:d}=i;try{const u=o?new We(this.nostrSubscribe,Mn(o)):void 0,y=c.map(p=>new We(this.nostrSubscribe,Mn(p)));r.set(s,{deviceId:s,activeSession:u,inactiveSessions:y,createdAt:a,staleAt:h,hasResponderSession:d})}catch(u){console.error(`Failed to deserialize session for user ${e}, device ${s}:`,u)}}this.userRecords.set(e,{publicKey:n.publicKey,devices:r});for(const i of r.values()){const{deviceId:s,activeSession:o,inactiveSessions:c,staleAt:a}=i;if(!(!s||a!==void 0)){for(const h of c.reverse())this.attachSessionSubscription(e,i,h);o&&this.attachSessionSubscription(e,i,o)}}}).catch(n=>{console.error(`Failed to load user record for ${e}:`,n)})}loadAllUserRecords(){const e=this.userRecordKeyPrefix();return this.storage.list(e).then(n=>Promise.all(n.map(r=>{const i=r.slice(e.length);return this.loadUserRecord(i)})))}async runMigrations(){let e=await this.storage.get(this.versionKey());if(!e){const r=await this.storage.list("invite/");await Promise.all(r.map(o=>this.storage.del(o)));const i="user/",s=await this.storage.list(i);await Promise.all(s.map(async o=>{try{const c=o.slice(i.length),a=await this.storage.get(o);if(a){const h=this.userRecordKey(c),d={publicKey:a.publicKey,devices:a.devices.map(u=>({deviceId:u.deviceId,activeSession:null,createdAt:u.createdAt,inactiveSessions:[]}))};await this.storage.put(h,d),await this.storage.del(o)}}catch(c){console.error("Migration error for user record:",c)}})),e="1",await this.storage.put(this.versionKey(),e)}}}class Cu{constructor(e){x(this,"deviceId");x(this,"deviceLabel");x(this,"nostrSubscribe");x(this,"nostrPublish");x(this,"storage");x(this,"ownerPublicKey");x(this,"identityKey");x(this,"inviteList",null);x(this,"initialized",!1);x(this,"subscriptions",[]);x(this,"storageVersion","1");this.deviceId=e.deviceId,this.deviceLabel=e.deviceLabel,this.nostrSubscribe=e.nostrSubscribe,this.nostrPublish=e.nostrPublish,this.storage=e.storage||new ot,this.ownerPublicKey=e.ownerPublicKey,this.identityKey=e.identityKey}get versionPrefix(){return`v${this.storageVersion}`}async init(){if(this.initialized)return;this.initialized=!0;const e=await this.loadInviteList(),n=await this.fetchInviteList(this.ownerPublicKey),r=this.mergeInviteLists(e,n);if(!r.getDevice(this.deviceId)){const s=r.createDevice(this.deviceLabel,this.deviceId);r.addDevice(s)}this.inviteList=r,await this.saveInviteList(r);const i=r.getEvent();await this.nostrPublish(i).catch(s=>{console.error("Failed to publish InviteList:",s)}),this.subscribeToOwnInviteList()}getDeviceId(){return this.deviceId}getIdentityPublicKey(){return this.ownerPublicKey}getIdentityKey(){return this.identityKey}getEphemeralKeypair(){var n;const e=(n=this.inviteList)==null?void 0:n.getDevice(this.deviceId);return!(e!=null&&e.ephemeralPublicKey)||!(e!=null&&e.ephemeralPrivateKey)?null:{publicKey:e.ephemeralPublicKey,privateKey:e.ephemeralPrivateKey}}getSharedSecret(){var n;const e=(n=this.inviteList)==null?void 0:n.getDevice(this.deviceId);return(e==null?void 0:e.sharedSecret)||null}getOwnerPublicKey(){return this.ownerPublicKey}getInviteList(){return this.inviteList}getOwnDevices(){var e;return((e=this.inviteList)==null?void 0:e.getAllDevices())||[]}async addDevice(e){await this.init(),await this.modifyInviteList(n=>{const r={ephemeralPublicKey:e.ephemeralPubkey,sharedSecret:e.sharedSecret,deviceId:e.deviceId,deviceLabel:e.deviceLabel,createdAt:Math.floor(Date.now()/1e3),identityPubkey:e.identityPubkey};n.addDevice(r)})}async revokeDevice(e){if(e===this.deviceId)throw new Error("Cannot revoke own device");await this.init(),await this.modifyInviteList(n=>{n.removeDevice(e)})}async updateDeviceLabel(e,n){await this.init(),await this.modifyInviteList(r=>{r.updateDeviceLabel(e,n)})}close(){for(const e of this.subscriptions)e();this.subscriptions=[]}createSessionManager(e){if(!this.initialized)throw new Error("DeviceManager must be initialized before creating SessionManager");const n=this.getEphemeralKeypair(),r=this.getSharedSecret();if(!n||!r)throw new Error("Ephemeral keypair and shared secret required for SessionManager");return new Hn(this.ownerPublicKey,this.identityKey,this.deviceId,this.nostrSubscribe,this.nostrPublish,this.ownerPublicKey,{ephemeralKeypair:n,sharedSecret:r},e||this.storage)}inviteListKey(){return`${this.versionPrefix}/device-manager/invite-list`}async loadInviteList(){const e=await this.storage.get(this.inviteListKey());if(!e)return null;try{return ne.deserialize(e)}catch{return null}}async saveInviteList(e){await this.storage.put(this.inviteListKey(),e.serialize())}fetchInviteList(e,n=500){return new Promise(r=>{let i=null,s=!1;setTimeout(()=>{s||(s=!0,o(),r((i==null?void 0:i.inviteList)??null))},n);let o=()=>{};o=this.nostrSubscribe({kinds:[Te],authors:[e],"#d":["double-ratchet/invite-list"]},c=>{if(!s)try{const a=ne.fromEvent(c);(!i||c.created_at>=i.event.created_at)&&(i={event:c,inviteList:a})}catch{}}),s&&o()})}mergeInviteLists(e,n){return e&&n?e.merge(n):e||n||new ne(this.ownerPublicKey)}async modifyInviteList(e){const n=await this.fetchInviteList(this.ownerPublicKey),r=this.mergeInviteLists(this.inviteList,n);e(r);const i=r.getEvent();await this.nostrPublish(i),await this.saveInviteList(r),this.inviteList=r}subscribeToOwnInviteList(){const e=this.nostrSubscribe({kinds:[Te],authors:[this.ownerPublicKey],"#d":["double-ratchet/invite-list"]},n=>{try{const r=ne.fromEvent(n);this.inviteList&&(this.inviteList=this.inviteList.merge(r),this.saveInviteList(this.inviteList).catch(console.error))}catch{}});this.subscriptions.push(e)}}class Ut{constructor(e,n,r,i,s,o,c,a,h){x(this,"deviceId");x(this,"nostrSubscribe");x(this,"nostrPublish");x(this,"storage");x(this,"devicePublicKey");x(this,"devicePrivateKey");x(this,"ephemeralPublicKey");x(this,"ephemeralPrivateKey");x(this,"sharedSecret");x(this,"ownerPubkeyFromActivation");x(this,"initialized",!1);x(this,"subscriptions",[]);x(this,"storageVersion","1");this.deviceId=e,this.nostrSubscribe=n,this.nostrPublish=r,this.storage=i,this.devicePublicKey=s,this.devicePrivateKey=o,this.ephemeralPublicKey=c,this.ephemeralPrivateKey=a,this.sharedSecret=h}get versionPrefix(){return`v${this.storageVersion}`}static create(e){const n=de(),r=ie(n),i=de(),s=ie(i),o=D(de()),c=new Ut(e.deviceId,e.nostrSubscribe,e.nostrPublish,e.storage||new ot,r,n,s,i,o),a={ephemeralPubkey:s,sharedSecret:o,deviceId:e.deviceId,deviceLabel:e.deviceLabel,identityPubkey:r};return{manager:c,payload:a}}static restore(e){return new Ut(e.deviceId,e.nostrSubscribe,e.nostrPublish,e.storage||new ot,e.devicePublicKey,e.devicePrivateKey,e.ephemeralPublicKey,e.ephemeralPrivateKey,e.sharedSecret)}async init(){if(this.initialized)return;this.initialized=!0;const e=await this.storage.get(this.ownerPubkeyKey());e&&(this.ownerPubkeyFromActivation=e)}getDeviceId(){return this.deviceId}getIdentityPublicKey(){return this.devicePublicKey}getIdentityKey(){return this.devicePrivateKey}getEphemeralKeypair(){return{publicKey:this.ephemeralPublicKey,privateKey:this.ephemeralPrivateKey}}getSharedSecret(){return this.sharedSecret}getOwnerPublicKey(){return this.ownerPubkeyFromActivation||null}async waitForActivation(e=6e4){return this.ownerPubkeyFromActivation?this.ownerPubkeyFromActivation:new Promise((n,r)=>{const i=setTimeout(()=>{s(),r(new Error("Activation timeout"))},e),s=this.nostrSubscribe({kinds:[Te],"#d":["double-ratchet/invite-list"]},async o=>{try{const a=ne.fromEvent(o).getDevice(this.deviceId);a&&a.ephemeralPublicKey===this.ephemeralPublicKey&&(clearTimeout(i),s(),this.ownerPubkeyFromActivation=o.pubkey,await this.storage.put(this.ownerPubkeyKey(),o.pubkey),n(o.pubkey))}catch{}});this.subscriptions.push(s)})}async isRevoked(){const e=this.getOwnerPublicKey();if(!e)return!1;const n=await this.fetchInviteList(e);if(!n)return!0;const r=n.getDevice(this.deviceId);return!r||r.ephemeralPublicKey!==this.ephemeralPublicKey}close(){for(const e of this.subscriptions)e();this.subscriptions=[]}createSessionManager(e){if(!this.initialized)throw new Error("DeviceManager must be initialized before creating SessionManager");const n=this.getOwnerPublicKey();if(!n)throw new Error("Owner public key required for SessionManager - device must be activated first");return new Hn(this.devicePublicKey,this.devicePrivateKey,this.deviceId,this.nostrSubscribe,this.nostrPublish,n,{ephemeralKeypair:{publicKey:this.ephemeralPublicKey,privateKey:this.ephemeralPrivateKey},sharedSecret:this.sharedSecret},e||this.storage)}ownerPubkeyKey(){return`${this.versionPrefix}/device-manager/owner-pubkey`}fetchInviteList(e,n=500){return new Promise(r=>{let i=null,s=!1;setTimeout(()=>{s||(s=!0,o(),r((i==null?void 0:i.inviteList)??null))},n);let o=()=>{};o=this.nostrSubscribe({kinds:[Te],authors:[e],"#d":["double-ratchet/invite-list"]},c=>{if(!s)try{const a=ne.fromEvent(c);(!i||c.created_at>=i.event.created_at)&&(i={event:c,inviteList:a})}catch{}}),s&&o()})}}L.CHAT_MESSAGE_KIND=$n,L.DelegateDeviceManager=Ut,L.INVITE_EVENT_KIND=Pt,L.INVITE_LIST_EVENT_KIND=Te,L.INVITE_RESPONSE_KIND=Ct,L.InMemoryStorageAdapter=ot,L.Invite=Oe,L.InviteList=ne,L.LocalStorageAdapter=Pu,L.MAX_SKIP=gu,L.MESSAGE_EVENT_KIND=$e,L.OwnerDeviceManager=Cu,L.Session=We,L.SessionManager=Hn,L.createEventStream=bu,L.createSessionFromAccept=Ze,L.decryptInviteResponse=Lt,L.deepCopyState=Bi,L.deserializeSessionState=Mn,L.encryptInviteResponse=Dn,L.generateDeviceId=_i,L.generateEphemeralKeypair=st,L.generateSharedSecret=On,L.getMillisecondTimestamp=mu,L.kdf=Me,L.serializeSessionState=Tn,L.skippedMessageIndexKey=wu,Object.defineProperty(L,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(I,Y){typeof exports=="object"&&typeof module<"u"?Y(exports):typeof define=="function"&&define.amd?define(["exports"],Y):(I=typeof globalThis<"u"?globalThis:I||self,Y(I["nostr-double-ratchet"]={}))})(this,(function(I){"use strict";var ul=Object.defineProperty;var ll=(I,Y,Be)=>Y in I?ul(I,Y,{enumerable:!0,configurable:!0,writable:!0,value:Be}):I[Y]=Be;var E=(I,Y,Be)=>ll(I,typeof Y!="symbol"?Y+"":Y,Be);function Y(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Be(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function ss(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Y(t.outputLen),Y(t.blockLen)}function dt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function os(t,e){Be(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Ot=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wn=t=>t instanceof Uint8Array,$t=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ae=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function as(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Dt(t){if(typeof t=="string"&&(t=as(t)),!Wn(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function cs(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!Wn(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}let Zn=class{clone(){return this._cloneInto()}};function us(t){const e=r=>t().update(Dt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Jn(t=32){if(Ot&&typeof Ot.getRandomValues=="function")return Ot.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ls(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,u=r?0:4;t.setUint32(e+a,o,r),t.setUint32(e+u,c,r)}let hs=class extends Zn{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=$t(this.buffer)}update(e){dt(this);const{view:n,buffer:r,blockLen:i}=this;e=Dt(e);const s=e.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=$t(e);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(e.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dt(this),os(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;ls(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=$t(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,h[l],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return e.length=i,e.pos=c,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}};const ds=(t,e,n)=>t&e^~t&n,fs=(t,e,n)=>t&e^t&n^e&n,ys=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Se=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ke=new Uint32Array(64);let ps=class extends hs{constructor(){super(64,32,8,!1),this.A=Se[0]|0,this.B=Se[1]|0,this.C=Se[2]|0,this.D=Se[3]|0,this.E=Se[4]|0,this.F=Se[5]|0,this.G=Se[6]|0,this.H=Se[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[e,n,r,i,s,o,c,a]}set(e,n,r,i,s,o,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(e,n){for(let l=0;l<16;l++,n+=4)Ke[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const y=Ke[l-15],p=Ke[l-2],g=ae(y,7)^ae(y,18)^y>>>3,d=ae(p,17)^ae(p,19)^p>>>10;Ke[l]=d+Ke[l-7]+g+Ke[l-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:u,H:h}=this;for(let l=0;l<64;l++){const y=ae(c,6)^ae(c,11)^ae(c,25),p=h+y+ds(c,a,u)+ys[l]+Ke[l]|0,d=(ae(r,2)^ae(r,13)^ae(r,22))+fs(r,i,s)|0;h=u,u=a,a=c,c=o+p|0,o=s,s=i,i=r,r=p+d|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,i,s,o,c,a,u,h)}roundClean(){Ke.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const Ht=us(()=>new ps);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(0);const gs=BigInt(1),ws=BigInt(2),ft=t=>t instanceof Uint8Array,vs=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function je(t){if(!ft(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=vs[t[n]];return e}function Vt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function rt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const i=r*2,s=t.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Q(t){return Vt(je(t))}function zt(t){if(!ft(t))throw new Error("Uint8Array expected");return Vt(je(Uint8Array.from(t).reverse()))}function Ae(t,e){return rt(t.toString(16).padStart(e*2,"0"))}function qt(t,e){return Ae(t,e).reverse()}function Z(t,e,n){let r;if(typeof e=="string")try{r=rt(e)}catch(s){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${s}`)}else if(ft(e))r=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${t} expected ${n} bytes, got ${i}`);return r}function Te(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!ft(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}const Ft=t=>(ws<<BigInt(t-1))-gs,jt=t=>new Uint8Array(t),Xn=t=>Uint8Array.from(t);function Yn(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=jt(t),i=jt(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},c=(...l)=>n(i,r,...l),a=(l=jt())=>{i=c(Xn([0]),l),r=c(),l.length!==0&&(i=c(Xn([1]),l),r=c())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const y=[];for(;l<e;){r=c();const p=r.slice();y.push(p),l+=r.length}return Te(...y)};return(l,y)=>{o(),a(l);let p;for(;!(p=y(u()));)a();return o(),p}}const bs={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function it(t,e,n={}){const r=(i,s,o)=>{const c=bs[s];if(typeof c!="function")throw new Error(`Invalid validator "${s}", expected function`);const a=t[i];if(!(o&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${s}`)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}const ms=Object.freeze(Object.defineProperty({__proto__:null,bitMask:Ft,bytesToHex:je,bytesToNumberBE:Q,bytesToNumberLE:zt,concatBytes:Te,createHmacDrbg:Yn,ensureBytes:Z,hexToBytes:rt,hexToNumber:Vt,numberToBytesBE:Ae,numberToBytesLE:qt,validateObject:it},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const G=BigInt(0),j=BigInt(1),Le=BigInt(2),Es=BigInt(3),Gt=BigInt(4),Qn=BigInt(5),er=BigInt(8);BigInt(9),BigInt(16);function W(t,e){const n=t%e;return n>=G?n:e+n}function xs(t,e,n){if(n<=G||e<G)throw new Error("Expected power/modulo > 0");if(n===j)return G;let r=j;for(;e>G;)e&j&&(r=r*t%n),t=t*t%n,e>>=j;return r}function te(t,e,n){let r=t;for(;e-- >G;)r*=r,r%=n;return r}function Wt(t,e){if(t===G||e<=G)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=W(t,e),r=e,i=G,s=j;for(;n!==G;){const c=r/n,a=r%n,u=i-s*c;r=n,n=a,i=s,s=u}if(r!==j)throw new Error("invert: does not exist");return W(i,e)}function Ss(t){const e=(t-j)/Le;let n,r,i;for(n=t-j,r=0;n%Le===G;n/=Le,r++);for(i=Le;i<t&&xs(i,e,t)!==t-j;i++);if(r===1){const o=(t+j)/Gt;return function(a,u){const h=a.pow(u,o);if(!a.eql(a.sqr(h),u))throw new Error("Cannot find square root");return h}}const s=(n+j)/Le;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=r,h=c.pow(c.mul(c.ONE,i),n),l=c.pow(a,s),y=c.pow(a,n);for(;!c.eql(y,c.ONE);){if(c.eql(y,c.ZERO))return c.ZERO;let p=1;for(let d=c.sqr(y);p<u&&!c.eql(d,c.ONE);p++)d=c.sqr(d);const g=c.pow(h,j<<BigInt(u-p-1));h=c.sqr(g),l=c.mul(l,g),y=c.mul(y,h),u=p}return l}}function Ks(t){if(t%Gt===Es){const e=(t+j)/Gt;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%er===Qn){const e=(t-Qn)/er;return function(r,i){const s=r.mul(i,Le),o=r.pow(s,e),c=r.mul(i,o),a=r.mul(r.mul(c,Le),o),u=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(u),i))throw new Error("Cannot find square root");return u}}return Ss(t)}const As=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ns(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=As.reduce((r,i)=>(r[i]="function",r),e);return it(t,n)}function Is(t,e,n){if(n<G)throw new Error("Expected power > 0");if(n===G)return t.ONE;if(n===j)return e;let r=t.ONE,i=e;for(;n>G;)n&j&&(r=t.mul(r,i)),i=t.sqr(i),n>>=j;return r}function ks(t,e){const n=new Array(e.length),r=e.reduce((s,o,c)=>t.is0(o)?s:(n[c]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,c)=>t.is0(o)?s:(n[c]=t.mul(s,n[c]),t.mul(s,o)),i),n}function tr(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Cs(t,e,n=!1,r={}){if(t<=G)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:i,nByteLength:s}=tr(t,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=Ks(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:s,MASK:Ft(i),ZERO:G,ONE:j,create:a=>W(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return G<=a&&a<t},is0:a=>a===G,isOdd:a=>(a&j)===j,neg:a=>W(-a,t),eql:(a,u)=>a===u,sqr:a=>W(a*a,t),add:(a,u)=>W(a+u,t),sub:(a,u)=>W(a-u,t),mul:(a,u)=>W(a*u,t),pow:(a,u)=>Is(c,a,u),div:(a,u)=>W(a*Wt(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>Wt(a,t),sqrt:r.sqrt||(a=>o(c,a)),invertBatch:a=>ks(c,a),cmov:(a,u,h)=>h?u:a,toBytes:a=>n?qt(a,s):Ae(a,s),fromBytes:a=>{if(a.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${a.length}`);return n?zt(a):Q(a)}});return Object.freeze(c)}function nr(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function rr(t){const e=nr(t);return e+Math.ceil(e/2)}function Ps(t,e,n=!1){const r=t.length,i=nr(e),s=rr(e);if(r<16||r<s||r>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=n?Q(t):zt(t),c=W(o,e-j)+j;return n?qt(c,i):Ae(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=BigInt(0),Zt=BigInt(1);function Us(t,e){const n=(i,s)=>{const o=s.negate();return i?o:s},r=i=>{const s=Math.ceil(e/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:n,unsafeLadder(i,s){let o=t.ZERO,c=i;for(;s>_s;)s&Zt&&(o=o.add(c)),c=c.double(),s>>=Zt;return o},precomputeWindow(i,s){const{windows:o,windowSize:c}=r(s),a=[];let u=i,h=u;for(let l=0;l<o;l++){h=u,a.push(h);for(let y=1;y<c;y++)h=h.add(u),a.push(h);u=h.double()}return a},wNAF(i,s,o){const{windows:c,windowSize:a}=r(i);let u=t.ZERO,h=t.BASE;const l=BigInt(2**i-1),y=2**i,p=BigInt(i);for(let g=0;g<c;g++){const d=g*a;let f=Number(o&l);o>>=p,f>a&&(f-=y,o+=Zt);const w=d,m=d+Math.abs(f)-1,K=g%2!==0,P=f<0;f===0?h=h.add(n(K,s[w])):u=u.add(n(P,s[m]))}return{p:u,f:h}},wNAFCached(i,s,o,c){const a=i._WINDOW_SIZE||1;let u=s.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&s.set(i,c(u))),this.wNAF(a,u,o)}}}function ir(t){return Ns(t.Fp),it(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...tr(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Rs(t){const e=ir(t);it(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Bs,hexToBytes:Ts}=ms,Me={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){const{Err:e}=Me;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Bs(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=Me,n=typeof t=="string"?Ts(t):t;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:i,l:s}=Me._parseInt(n.subarray(2)),{d:o,l:c}=Me._parseInt(s);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(t){const e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,n=u=>{const h=u.toString(16);return h.length&1?`0${h}`:h},r=e(n(t.s)),i=e(n(t.r)),s=r.length/2,o=i.length/2,c=n(s),a=n(o);return`30${n(o+s+4)}02${a}${i}02${c}${r}`}},ye=BigInt(0),ne=BigInt(1);BigInt(2);const sr=BigInt(3);BigInt(4);function Ls(t){const e=Rs(t),{Fp:n}=e,r=e.toBytes||((g,d,f)=>{const w=d.toAffine();return Te(Uint8Array.from([4]),n.toBytes(w.x),n.toBytes(w.y))}),i=e.fromBytes||(g=>{const d=g.subarray(1),f=n.fromBytes(d.subarray(0,n.BYTES)),w=n.fromBytes(d.subarray(n.BYTES,2*n.BYTES));return{x:f,y:w}});function s(g){const{a:d,b:f}=e,w=n.sqr(g),m=n.mul(w,g);return n.add(n.add(m,n.mul(g,d)),f)}if(!n.eql(n.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function o(g){return typeof g=="bigint"&&ye<g&&g<e.n}function c(g){if(!o(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){const{allowedPrivateKeyLengths:d,nByteLength:f,wrapPrivateKey:w,n:m}=e;if(d&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=je(g)),typeof g!="string"||!d.includes(g.length))throw new Error("Invalid key");g=g.padStart(f*2,"0")}let K;try{K=typeof g=="bigint"?g:Q(Z("private key",g,f))}catch{throw new Error(`private key must be ${f} bytes, hex or bigint, not ${typeof g}`)}return w&&(K=W(K,m)),c(K),K}const u=new Map;function h(g){if(!(g instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(d,f,w){if(this.px=d,this.py=f,this.pz=w,d==null||!n.isValid(d))throw new Error("x required");if(f==null||!n.isValid(f))throw new Error("y required");if(w==null||!n.isValid(w))throw new Error("z required")}static fromAffine(d){const{x:f,y:w}=d||{};if(!d||!n.isValid(f)||!n.isValid(w))throw new Error("invalid affine point");if(d instanceof l)throw new Error("projective point not allowed");const m=K=>n.eql(K,n.ZERO);return m(f)&&m(w)?l.ZERO:new l(f,w,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const f=n.invertBatch(d.map(w=>w.pz));return d.map((w,m)=>w.toAffine(f[m])).map(l.fromAffine)}static fromHex(d){const f=l.fromAffine(i(Z("pointHex",d)));return f.assertValidity(),f}static fromPrivateKey(d){return l.BASE.multiply(a(d))}_setWindowSize(d){this._WINDOW_SIZE=d,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:d,y:f}=this.toAffine();if(!n.isValid(d)||!n.isValid(f))throw new Error("bad point: x or y not FE");const w=n.sqr(f),m=s(d);if(!n.eql(w,m))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:d}=this.toAffine();if(n.isOdd)return!n.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){h(d);const{px:f,py:w,pz:m}=this,{px:K,py:P,pz:_}=d,x=n.eql(n.mul(f,_),n.mul(K,m)),S=n.eql(n.mul(w,_),n.mul(P,m));return x&&S}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:d,b:f}=e,w=n.mul(f,sr),{px:m,py:K,pz:P}=this;let _=n.ZERO,x=n.ZERO,S=n.ZERO,A=n.mul(m,m),D=n.mul(K,K),R=n.mul(P,P),k=n.mul(m,K);return k=n.add(k,k),S=n.mul(m,P),S=n.add(S,S),_=n.mul(d,S),x=n.mul(w,R),x=n.add(_,x),_=n.sub(D,x),x=n.add(D,x),x=n.mul(_,x),_=n.mul(k,_),S=n.mul(w,S),R=n.mul(d,R),k=n.sub(A,R),k=n.mul(d,k),k=n.add(k,S),S=n.add(A,A),A=n.add(S,A),A=n.add(A,R),A=n.mul(A,k),x=n.add(x,A),R=n.mul(K,P),R=n.add(R,R),A=n.mul(R,k),_=n.sub(_,A),S=n.mul(R,D),S=n.add(S,S),S=n.add(S,S),new l(_,x,S)}add(d){h(d);const{px:f,py:w,pz:m}=this,{px:K,py:P,pz:_}=d;let x=n.ZERO,S=n.ZERO,A=n.ZERO;const D=e.a,R=n.mul(e.b,sr);let k=n.mul(f,K),M=n.mul(w,P),O=n.mul(m,_),F=n.add(f,w),v=n.add(K,P);F=n.mul(F,v),v=n.add(k,M),F=n.sub(F,v),v=n.add(f,m);let b=n.add(K,_);return v=n.mul(v,b),b=n.add(k,O),v=n.sub(v,b),b=n.add(w,m),x=n.add(P,_),b=n.mul(b,x),x=n.add(M,O),b=n.sub(b,x),A=n.mul(D,v),x=n.mul(R,O),A=n.add(x,A),x=n.sub(M,A),A=n.add(M,A),S=n.mul(x,A),M=n.add(k,k),M=n.add(M,k),O=n.mul(D,O),v=n.mul(R,v),M=n.add(M,O),O=n.sub(k,O),O=n.mul(D,O),v=n.add(v,O),k=n.mul(M,v),S=n.add(S,k),k=n.mul(b,v),x=n.mul(F,x),x=n.sub(x,k),k=n.mul(F,M),A=n.mul(b,A),A=n.add(A,k),new l(x,S,A)}subtract(d){return this.add(d.negate())}is0(){return this.equals(l.ZERO)}wNAF(d){return p.wNAFCached(this,u,d,f=>{const w=n.invertBatch(f.map(m=>m.pz));return f.map((m,K)=>m.toAffine(w[K])).map(l.fromAffine)})}multiplyUnsafe(d){const f=l.ZERO;if(d===ye)return f;if(c(d),d===ne)return this;const{endo:w}=e;if(!w)return p.unsafeLadder(this,d);let{k1neg:m,k1:K,k2neg:P,k2:_}=w.splitScalar(d),x=f,S=f,A=this;for(;K>ye||_>ye;)K&ne&&(x=x.add(A)),_&ne&&(S=S.add(A)),A=A.double(),K>>=ne,_>>=ne;return m&&(x=x.negate()),P&&(S=S.negate()),S=new l(n.mul(S.px,w.beta),S.py,S.pz),x.add(S)}multiply(d){c(d);let f=d,w,m;const{endo:K}=e;if(K){const{k1neg:P,k1:_,k2neg:x,k2:S}=K.splitScalar(f);let{p:A,f:D}=this.wNAF(_),{p:R,f:k}=this.wNAF(S);A=p.constTimeNegate(P,A),R=p.constTimeNegate(x,R),R=new l(n.mul(R.px,K.beta),R.py,R.pz),w=A.add(R),m=D.add(k)}else{const{p:P,f:_}=this.wNAF(f);w=P,m=_}return l.normalizeZ([w,m])[0]}multiplyAndAddUnsafe(d,f,w){const m=l.BASE,K=(_,x)=>x===ye||x===ne||!_.equals(m)?_.multiplyUnsafe(x):_.multiply(x),P=K(this,f).add(K(d,w));return P.is0()?void 0:P}toAffine(d){const{px:f,py:w,pz:m}=this,K=this.is0();d==null&&(d=K?n.ONE:n.inv(m));const P=n.mul(f,d),_=n.mul(w,d),x=n.mul(m,d);if(K)return{x:n.ZERO,y:n.ZERO};if(!n.eql(x,n.ONE))throw new Error("invZ was invalid");return{x:P,y:_}}isTorsionFree(){const{h:d,isTorsionFree:f}=e;if(d===ne)return!0;if(f)return f(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:f}=e;return d===ne?this:f?f(l,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return this.assertValidity(),r(l,this,d)}toHex(d=!0){return je(this.toRawBytes(d))}}l.BASE=new l(e.Gx,e.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const y=e.nBitLength,p=Us(l,e.endo?Math.ceil(y/2):y);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:o}}function Ms(t){const e=ir(t);return it(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Os(t){const e=Ms(t),{Fp:n,n:r}=e,i=n.BYTES+1,s=2*n.BYTES+1;function o(v){return ye<v&&v<n.ORDER}function c(v){return W(v,r)}function a(v){return Wt(v,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:y}=Ls({...e,toBytes(v,b,N){const U=b.toAffine(),C=n.toBytes(U.x),T=Te;return N?T(Uint8Array.from([b.hasEvenY()?2:3]),C):T(Uint8Array.from([4]),C,n.toBytes(U.y))},fromBytes(v){const b=v.length,N=v[0],U=v.subarray(1);if(b===i&&(N===2||N===3)){const C=Q(U);if(!o(C))throw new Error("Point is not on curve");const T=l(C);let $=n.sqrt(T);const L=($&ne)===ne;return(N&1)===1!==L&&($=n.neg($)),{x:C,y:$}}else if(b===s&&N===4){const C=n.fromBytes(U.subarray(0,n.BYTES)),T=n.fromBytes(U.subarray(n.BYTES,2*n.BYTES));return{x:C,y:T}}else throw new Error(`Point of length ${b} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),p=v=>je(Ae(v,e.nByteLength));function g(v){const b=r>>ne;return v>b}function d(v){return g(v)?c(-v):v}const f=(v,b,N)=>Q(v.slice(b,N));class w{constructor(b,N,U){this.r=b,this.s=N,this.recovery=U,this.assertValidity()}static fromCompact(b){const N=e.nByteLength;return b=Z("compactSignature",b,N*2),new w(f(b,0,N),f(b,N,2*N))}static fromDER(b){const{r:N,s:U}=Me.toSig(Z("DER",b));return new w(N,U)}assertValidity(){if(!y(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!y(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(b){return new w(this.r,this.s,b)}recoverPublicKey(b){const{r:N,s:U,recovery:C}=this,T=S(Z("msgHash",b));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const $=C===2||C===3?N+e.n:N;if($>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(C&1)===0?"02":"03",se=u.fromHex(L+p($)),Ue=a($),Qe=c(-T*Ue),ht=c(U*Ue),Re=u.BASE.multiplyAndAddUnsafe(se,Qe,ht);if(!Re)throw new Error("point at infinify");return Re.assertValidity(),Re}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return rt(this.toDERHex())}toDERHex(){return Me.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return rt(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(v){try{return h(v),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const v=rr(e.n);return Ps(e.randomBytes(v),e.n)},precompute(v=8,b=u.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}};function K(v,b=!0){return u.fromPrivateKey(v).toRawBytes(b)}function P(v){const b=v instanceof Uint8Array,N=typeof v=="string",U=(b||N)&&v.length;return b?U===i||U===s:N?U===2*i||U===2*s:v instanceof u}function _(v,b,N=!0){if(P(v))throw new Error("first arg must be private key");if(!P(b))throw new Error("second arg must be public key");return u.fromHex(b).multiply(h(v)).toRawBytes(N)}const x=e.bits2int||function(v){const b=Q(v),N=v.length*8-e.nBitLength;return N>0?b>>BigInt(N):b},S=e.bits2int_modN||function(v){return c(x(v))},A=Ft(e.nBitLength);function D(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(ye<=v&&v<A))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ae(v,e.nByteLength)}function R(v,b,N=k){if(["recovered","canonical"].some(Fe=>Fe in N))throw new Error("sign() legacy options not supported");const{hash:U,randomBytes:C}=e;let{lowS:T,prehash:$,extraEntropy:L}=N;T==null&&(T=!0),v=Z("msgHash",v),$&&(v=Z("prehashed msgHash",U(v)));const se=S(v),Ue=h(b),Qe=[D(Ue),D(se)];if(L!=null){const Fe=L===!0?C(n.BYTES):L;Qe.push(Z("extraEntropy",Fe))}const ht=Te(...Qe),Re=se;function Gn(Fe){const et=x(Fe);if(!y(et))return;const ns=a(et),tt=u.BASE.multiply(et).toAffine(),oe=c(tt.x);if(oe===ye)return;const nt=c(ns*c(Re+oe*Ue));if(nt===ye)return;let rs=(tt.x===oe?0:2)|Number(tt.y&ne),is=nt;return T&&g(nt)&&(is=d(nt),rs^=1),new w(oe,is,rs)}return{seed:ht,k2sig:Gn}}const k={lowS:e.lowS,prehash:!1},M={lowS:e.lowS,prehash:!1};function O(v,b,N=k){const{seed:U,k2sig:C}=R(v,b,N),T=e;return Yn(T.hash.outputLen,T.nByteLength,T.hmac)(U,C)}u.BASE._setWindowSize(8);function F(v,b,N,U=M){var tt;const C=v;if(b=Z("msgHash",b),N=Z("publicKey",N),"strict"in U)throw new Error("options.strict was renamed to lowS");const{lowS:T,prehash:$}=U;let L,se;try{if(typeof C=="string"||C instanceof Uint8Array)try{L=w.fromDER(C)}catch(oe){if(!(oe instanceof Me.Err))throw oe;L=w.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:oe,s:nt}=C;L=new w(oe,nt)}else throw new Error("PARSE");se=u.fromHex(N)}catch(oe){if(oe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&L.hasHighS())return!1;$&&(b=e.hash(b));const{r:Ue,s:Qe}=L,ht=S(b),Re=a(Qe),Gn=c(ht*Re),Fe=c(Ue*Re),et=(tt=u.BASE.multiplyAndAddUnsafe(se,Gn,Fe))==null?void 0:tt.toAffine();return et?c(et.x)===Ue:!1}return{CURVE:e,getPublicKey:K,getSharedSecret:_,sign:O,verify:F,ProjectivePoint:u,Signature:w,utils:m}}let or=class extends Zn{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ss(e);const r=Dt(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return dt(this),this.iHash.update(e),this}digestInto(e){dt(this),Be(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:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ar=(t,e,n)=>new or(t,e).update(n).digest();ar.create=(t,e)=>new or(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $s(t){return{hash:t,hmac:(e,...n)=>ar(t,e,cs(...n)),randomBytes:Jn}}function Ds(t,e){const n=r=>Os({...t,...$s(r)});return Object.freeze({...n(e),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),pt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cr=BigInt(1),gt=BigInt(2),ur=(t,e)=>(t+e/gt)/e;function lr(t){const e=yt,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,h=u*u*t%e,l=te(h,n,e)*h%e,y=te(l,n,e)*h%e,p=te(y,gt,e)*u%e,g=te(p,i,e)*p%e,d=te(g,s,e)*g%e,f=te(d,c,e)*d%e,w=te(f,a,e)*f%e,m=te(w,c,e)*d%e,K=te(m,n,e)*h%e,P=te(K,o,e)*g%e,_=te(P,r,e)*u%e,x=te(_,gt,e);if(!Jt.eql(Jt.sqr(x),t))throw new Error("Cannot find square root");return x}const Jt=Cs(yt,void 0,void 0,{sqrt:lr}),Oe=Ds({a:BigInt(0),b:BigInt(7),Fp:Jt,n:pt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=pt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-cr*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),c=ur(s*t,e),a=ur(-r*t,e);let u=W(t-c*n-a*i,e),h=W(-c*r-a*s,e);const l=u>o,y=h>o;if(l&&(u=e-u),y&&(h=e-h),u>o||h>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:y,k2:h}}}},Ht),wt=BigInt(0),hr=t=>typeof t=="bigint"&&wt<t&&t<yt,Hs=t=>typeof t=="bigint"&&wt<t&&t<pt,dr={};function vt(t,...e){let n=dr[t];if(n===void 0){const r=Ht(Uint8Array.from(t,i=>i.charCodeAt(0)));n=Te(r,r),dr[t]=n}return Ht(Te(n,...e))}const Xt=t=>t.toRawBytes(!0).slice(1),Yt=t=>Ae(t,32),Qt=t=>W(t,yt),st=t=>W(t,pt),en=Oe.ProjectivePoint,Vs=(t,e,n)=>en.BASE.multiplyAndAddUnsafe(t,e,n);function tn(t){let e=Oe.utils.normPrivateKeyToScalar(t),n=en.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:st(-e),bytes:Xt(n)}}function fr(t){if(!hr(t))throw new Error("bad x: need 0 < x < p");const e=Qt(t*t),n=Qt(e*t+BigInt(7));let r=lr(n);r%gt!==wt&&(r=Qt(-r));const i=new en(t,r,cr);return i.assertValidity(),i}function yr(...t){return st(Q(vt("BIP0340/challenge",...t)))}function zs(t){return tn(t).bytes}function qs(t,e,n=Jn(32)){const r=Z("message",t),{bytes:i,scalar:s}=tn(e),o=Z("auxRand",n,32),c=Yt(s^Q(vt("BIP0340/aux",o))),a=vt("BIP0340/nonce",c,i,r),u=st(Q(a));if(u===wt)throw new Error("sign failed: k is zero");const{bytes:h,scalar:l}=tn(u),y=yr(h,i,r),p=new Uint8Array(64);if(p.set(h,0),p.set(Yt(st(l+y*s)),32),!pr(p,r,i))throw new Error("sign: Invalid signature produced");return p}function pr(t,e,n){const r=Z("signature",t,64),i=Z("message",e),s=Z("publicKey",n,32);try{const o=fr(Q(s)),c=Q(r.subarray(0,32));if(!hr(c))return!1;const a=Q(r.subarray(32,64));if(!Hs(a))return!1;const u=yr(Yt(c),Xt(o),i),h=Vs(o,a,st(-u));return!(!h||!h.hasEvenY()||h.toAffine().x!==c)}catch{return!1}}const ot={getPublicKey:zs,sign:qs,verify:pr,utils:{randomPrivateKey:Oe.utils.randomPrivateKey,lift_x:fr,pointToBytes:Xt,numberToBytesBE:Ae,bytesToNumberBE:Q,taggedHash:vt,mod:W}},nn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=t=>t instanceof Uint8Array,sn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ce=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const Fs=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function H(t){if(!rn(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Fs[t[n]];return e}function z(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const i=r*2,s=t.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function js(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function at(t){if(typeof t=="string"&&(t=js(t)),!rn(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function bt(...t){const e=new Uint8Array(t.reduce((r,i)=>r+i.length,0));let n=0;return t.forEach(r=>{if(!rn(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}class gr{clone(){return this._cloneInto()}}function wr(t){const e=r=>t().update(at(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function vr(t=32){if(nn&&typeof nn.getRandomValues=="function")return nn.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function on(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function Gs(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}function br(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Ws(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");on(t.outputLen),on(t.blockLen)}function Zs(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Js(t,e){br(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const ue={number:on,bool:Gs,bytes:br,hash:Ws,exists:Zs,output:Js};function Xs(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,u=r?0:4;t.setUint32(e+a,o,r),t.setUint32(e+u,c,r)}class Ys extends gr{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=sn(this.buffer)}update(e){ue.exists(this);const{view:n,buffer:r,blockLen:i}=this;e=at(e);const s=e.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=sn(e);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(e.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ue.exists(this),ue.output(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;Xs(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=sn(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,h[l],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return e.length=i,e.pos=c,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const Qs=(t,e,n)=>t&e^~t&n,eo=(t,e,n)=>t&e^t&n^e&n,to=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ne=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ie=new Uint32Array(64);class mr extends Ys{constructor(){super(64,32,8,!1),this.A=Ne[0]|0,this.B=Ne[1]|0,this.C=Ne[2]|0,this.D=Ne[3]|0,this.E=Ne[4]|0,this.F=Ne[5]|0,this.G=Ne[6]|0,this.H=Ne[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[e,n,r,i,s,o,c,a]}set(e,n,r,i,s,o,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(e,n){for(let l=0;l<16;l++,n+=4)Ie[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const y=Ie[l-15],p=Ie[l-2],g=ce(y,7)^ce(y,18)^y>>>3,d=ce(p,17)^ce(p,19)^p>>>10;Ie[l]=d+Ie[l-7]+g+Ie[l-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:u,H:h}=this;for(let l=0;l<64;l++){const y=ce(c,6)^ce(c,11)^ce(c,25),p=h+y+Qs(c,a,u)+to[l]+Ie[l]|0,d=(ce(r,2)^ce(r,13)^ce(r,22))+eo(r,i,s)|0;h=u,u=a,a=c,c=o+p|0,o=s,s=i,i=r,r=p+d|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,i,s,o,c,a,u,h)}roundClean(){Ie.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class no extends mr{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const le=wr(()=>new mr);wr(()=>new no);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ge(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function pe(...t){const e=(i,s)=>o=>i(s(o)),n=Array.from(t).reverse().reduce((i,s)=>i?e(i,s.encode):s.encode,void 0),r=t.reduce((i,s)=>i?e(i,s.decode):s.decode,void 0);return{encode:n,decode:r}}function ge(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(n=>{if(Ge(n),n<0||n>=t.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${t.length})`);return t[n]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=t.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return r})}}}function we(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of e)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function mt(t,e="="){if(Ge(t),typeof e!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if(!((r-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function Er(t){if(typeof t!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>t(e)}}function xr(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, 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(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let r=0;const i=[],s=Array.from(t);for(s.forEach(o=>{if(Ge(o),o<0||o>=e)throw new Error(`Wrong integer: ${o}`)});;){let o=0,c=!0;for(let a=r;a<s.length;a++){const u=s[a],h=e*o+u;if(!Number.isSafeInteger(h)||e*o/e!==o||h-u!==e*o)throw new Error("convertRadix: carry overflow");if(o=h%n,s[a]=Math.floor(h/n),!Number.isSafeInteger(s[a])||s[a]*n+o!==h)throw new Error("convertRadix: carry overflow");if(c)s[a]?c=!1:r=a;else continue}if(i.push(o),c)break}for(let o=0;o<t.length-1&&t[o]===0;o++)i.push(0);return i.reverse()}const Sr=(t,e)=>e?Sr(e,t%e):t,Et=(t,e)=>t+(e-Sr(t,e));function an(t,e,n,r){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Et(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Et(e,n)}`);let i=0,s=0;const o=2**n-1,c=[];for(const a of t){if(Ge(a),a>=2**e)throw new Error(`convertRadix2: invalid data word=${a} from=${e}`);if(i=i<<e|a,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<<n-s&o,!r&&s>=e)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function ro(t){return Ge(t),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return xr(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(xr(e,t,2**8))}}}function ke(t,e=!1){if(Ge(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Et(8,t)>32||Et(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return an(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(an(n,t,8,e))}}}function Kr(t){if(typeof t!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return t.apply(null,e)}catch{}}}const io=pe(ke(4),ge("0123456789ABCDEF"),we("")),so=pe(ke(5),ge("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),mt(5),we(""));pe(ke(5),ge("0123456789ABCDEFGHIJKLMNOPQRSTUV"),mt(5),we("")),pe(ke(5),ge("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),we(""),Er(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ve=pe(ke(6),ge("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),mt(6),we("")),oo=pe(ke(6),ge("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),mt(6),we("")),cn=t=>pe(ro(58),ge(t),we("")),un=cn("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");cn("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),cn("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const Ar=[0,2,3,5,6,7,9,10,11],ao={encode(t){let e="";for(let n=0;n<t.length;n+=8){const r=t.subarray(n,n+8);e+=un.encode(r).padStart(Ar[r.length],"1")}return e},decode(t){let e=[];for(let n=0;n<t.length;n+=11){const r=t.slice(n,n+11),i=Ar.indexOf(r.length),s=un.decode(r);for(let o=0;o<s.length-i;o++)if(s[o]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(e)}},ln=pe(ge("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),we("")),Nr=[996825010,642813549,513874426,1027748829,705979059];function ct(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Nr.length;r++)(e>>r&1)===1&&(n^=Nr[r]);return n}function Ir(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=ct(i)^o>>5}i=ct(i);for(let s=0;s<r;s++)i=ct(i)^t.charCodeAt(s)&31;for(let s of e)i=ct(i)^s;for(let s=0;s<6;s++)i=ct(i);return i^=n,ln.encode(an([i%2**30],30,5,!1))}function kr(t){const e=t==="bech32"?1:734539939,n=ke(5),r=n.decode,i=n.encode,s=Kr(r);function o(h,l,y=90){if(typeof h!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof h}`);if(!Array.isArray(l)||l.length&&typeof l[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof l}`);const p=h.length+7+l.length;if(y!==!1&&p>y)throw new TypeError(`Length ${p} exceeds limit ${y}`);return h=h.toLowerCase(),`${h}1${ln.encode(l)}${Ir(h,l,e)}`}function c(h,l=90){if(typeof h!="string")throw new Error(`bech32.decode input should be string, not ${typeof h}`);if(h.length<8||l!==!1&&h.length>l)throw new TypeError(`Wrong string length: ${h.length} (${h}). Expected (8..${l})`);const y=h.toLowerCase();if(h!==y&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");h=y;const p=h.lastIndexOf("1");if(p===0||p===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=h.slice(0,p),d=h.slice(p+1);if(d.length<6)throw new Error("Data must be at least 6 characters long");const f=ln.decode(d).slice(0,-6),w=Ir(g,f,e);if(!d.endsWith(w))throw new Error(`Invalid checksum in ${h}: expected "${w}"`);return{prefix:g,words:f}}const a=Kr(c);function u(h){const{prefix:l,words:y}=c(h,!1);return{prefix:l,words:y,bytes:r(y)}}return{encode:o,decode:c,decodeToBytes:u,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:s,toWords:i}}const We=kr("bech32");kr("bech32m");const co={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},uo=pe(ke(4),ge("0123456789abcdef"),we(""),Er(t=>{if(typeof t!="string"||t.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));`${Object.keys({utf8:co,hex:uo,base16:io,base32:so,base64:ve,base64url:oo,base58:un,base58xmr:ao}).join(", ")}`;function hn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function Cr(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function lo(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function he(t,...e){if(!lo(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const J=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const ho=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ze(t){he(t);let e="";for(let n=0;n<t.length;n++)e+=ho[t[n]];return e}const be={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Pr(t){if(t>=be._0&&t<=be._9)return t-be._0;if(t>=be._A&&t<=be._F)return t-(be._A-10);if(t>=be._a&&t<=be._f)return t-(be._a-10)}function _r(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Pr(t.charCodeAt(s)),c=Pr(t.charCodeAt(s+1));if(o===void 0||c===void 0){const a=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+s)}r[i]=o*16+c}return r}function fo(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function yo(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const po=(t,e)=>(Object.assign(e,t),e),Ce=16,go=283;function dn(t){return t<<1^go&-(t>>7)}function Je(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(e&1),t=dn(t);return n}const fn=(()=>{let t=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=dn(r))t[n]=r;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return e})(),wo=fn.map((t,e)=>fn.indexOf(e)),vo=t=>t<<24|t>>>8,yn=t=>t<<8|t>>>24;function Ur(t,e){if(t.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((u,h)=>e(t[h])),r=n.map(yn),i=r.map(yn),s=i.map(yn),o=new Uint32Array(256*256),c=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let u=0;u<256;u++)for(let h=0;h<256;h++){const l=u*256+h;o[l]=n[u]^r[h],c[l]=i[u]^s[h],a[l]=t[u]<<8|t[h]}return{sbox:t,sbox2:a,T0:n,T1:r,T2:i,T3:s,T01:o,T23:c}}const pn=Ur(fn,t=>Je(t,3)<<24|t<<16|t<<8|Je(t,2)),Rr=Ur(wo,t=>Je(t,11)<<24|Je(t,13)<<16|Je(t,9)<<8|Je(t,14)),bo=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=dn(n))t[e]=n;return t})();function Br(t){he(t);const e=t.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:n}=pn,r=J(t),i=r.length,s=c=>de(n,c,c,c,c),o=new Uint32Array(e+28);o.set(r);for(let c=i;c<o.length;c++){let a=o[c-1];c%i===0?a=s(vo(a))^bo[c/i-1]:i>6&&c%i===4&&(a=s(a)),o[c]=o[c-i]^a}return o}function mo(t){const e=Br(t),n=e.slice(),r=e.length,{sbox2:i}=pn,{T0:s,T1:o,T2:c,T3:a}=Rr;for(let u=0;u<r;u+=4)for(let h=0;h<4;h++)n[u+h]=e[r-u-4+h];e.fill(0);for(let u=4;u<r-4;u++){const h=n[u],l=de(i,h,h,h,h);n[u]=s[l&255]^o[l>>>8&255]^c[l>>>16&255]^a[l>>>24]}return n}function Pe(t,e,n,r,i,s){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|s>>>24&255]}function de(t,e,n,r,i){return t[e&255|n&65280]|t[r>>>16&255|i>>>16&65280]<<16}function Tr(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=pn;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const u=t.length/4-2;for(let g=0;g<u;g++){const d=t[a++]^Pe(o,c,e,n,r,i),f=t[a++]^Pe(o,c,n,r,i,e),w=t[a++]^Pe(o,c,r,i,e,n),m=t[a++]^Pe(o,c,i,e,n,r);e=d,n=f,r=w,i=m}const h=t[a++]^de(s,e,n,r,i),l=t[a++]^de(s,n,r,i,e),y=t[a++]^de(s,r,i,e,n),p=t[a++]^de(s,i,e,n,r);return{s0:h,s1:l,s2:y,s3:p}}function Eo(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=Rr;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const u=t.length/4-2;for(let g=0;g<u;g++){const d=t[a++]^Pe(o,c,e,i,r,n),f=t[a++]^Pe(o,c,n,e,i,r),w=t[a++]^Pe(o,c,r,n,e,i),m=t[a++]^Pe(o,c,i,r,n,e);e=d,n=f,r=w,i=m}const h=t[a++]^de(s,e,i,r,n),l=t[a++]^de(s,n,e,i,r),y=t[a++]^de(s,r,n,e,i),p=t[a++]^de(s,i,r,n,e);return{s0:h,s1:l,s2:y,s3:p}}function Lr(t,e){if(!e)return new Uint8Array(t);if(he(e),e.length<t)throw new Error(`aes: wrong destination length, expected at least ${t}, got: ${e.length}`);return e}function xo(t){if(he(t),t.length%Ce!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Ce}`)}function So(t,e,n){let r=t.length;const i=r%Ce;if(!e&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=J(t);if(e){let a=Ce-i;a||(a=Ce),r=r+a}const o=Lr(r,n),c=J(o);return{b:s,o:c,out:o}}function Ko(t,e){if(!e)return t;const n=t.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=t[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=t.subarray(0,-r);for(let s=0;s<r;s++)if(t[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function Ao(t){const e=new Uint8Array(16),n=J(e);e.set(t);const r=Ce-t.length;for(let i=Ce-r;i<Ce;i++)e[i]=r;return n}const Mr=po({blockSize:16,nonceLength:16},function(e,n,r={}){he(e),he(n,16);const i=!r.disablePadding;return{encrypt:(s,o)=>{const c=Br(e),{b:a,o:u,out:h}=So(s,i,o),l=J(n);let y=l[0],p=l[1],g=l[2],d=l[3],f=0;for(;f+4<=a.length;)y^=a[f+0],p^=a[f+1],g^=a[f+2],d^=a[f+3],{s0:y,s1:p,s2:g,s3:d}=Tr(c,y,p,g,d),u[f++]=y,u[f++]=p,u[f++]=g,u[f++]=d;if(i){const w=Ao(s.subarray(f*4));y^=w[0],p^=w[1],g^=w[2],d^=w[3],{s0:y,s1:p,s2:g,s3:d}=Tr(c,y,p,g,d),u[f++]=y,u[f++]=p,u[f++]=g,u[f++]=d}return c.fill(0),h},decrypt:(s,o)=>{xo(s);const c=mo(e),a=J(n),u=Lr(s.length,o),h=J(s),l=J(u);let y=a[0],p=a[1],g=a[2],d=a[3];for(let f=0;f+4<=h.length;){const w=y,m=p,K=g,P=d;y=h[f+0],p=h[f+1],g=h[f+2],d=h[f+3];const{s0:_,s1:x,s2:S,s3:A}=Eo(c,y,p,g,d);l[f++]=_^w,l[f++]=x^m,l[f++]=S^K,l[f++]=A^P}return c.fill(0),Ko(u,i)}}}),Or=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),No=Or("expand 16-byte k"),Io=Or("expand 32-byte k"),ko=J(No),$r=J(Io);$r.slice();function B(t,e){return t<<e|t>>>32-e}function gn(t){return t.byteOffset%4===0}const xt=64,Co=16,Dr=2**32-1,Hr=new Uint32Array;function Po(t,e,n,r,i,s,o,c){const a=i.length,u=new Uint8Array(xt),h=J(u),l=gn(i)&&gn(s),y=l?J(i):Hr,p=l?J(s):Hr;for(let g=0;g<a;o++){if(t(e,n,r,h,o,c),o>=Dr)throw new Error("arx: counter overflow");const d=Math.min(xt,a-g);if(l&&d===xt){const f=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<Co;w++)m=f+w,p[m]=y[m]^h[w];g+=xt;continue}for(let f=0,w;f<d;f++)w=g+f,s[w]=i[w]^u[f];g+=d}}function _o(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=fo({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return hn(i),hn(o),Cr(s),Cr(n),(c,a,u,h,l=0)=>{he(c),he(a),he(u);const y=u.length;if(h||(h=new Uint8Array(y)),he(h),hn(l),l<0||l>=Dr)throw new Error("arx: counter overflow");if(h.length<y)throw new Error(`arx: output (${h.length}) is shorter than data (${y})`);const p=[];let g=c.length,d,f;if(g===32)d=c.slice(),p.push(d),f=$r;else if(g===16&&n)d=new Uint8Array(32),d.set(c),d.set(c,16),f=ko,p.push(d);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);gn(a)||(a=a.slice(),p.push(a));const w=J(d);if(r){if(a.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(f,w,J(a.subarray(0,16)),w),a=a.subarray(16)}const m=16-i;if(m!==a.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const P=new Uint8Array(12);P.set(a,s?0:12-a.length),a=P,p.push(a)}const K=J(a);for(Po(t,f,w,K,u,h,l,o);p.length>0;)p.pop().fill(0);return h}}function Uo(t,e,n,r,i,s=20){let o=t[0],c=t[1],a=t[2],u=t[3],h=e[0],l=e[1],y=e[2],p=e[3],g=e[4],d=e[5],f=e[6],w=e[7],m=i,K=n[0],P=n[1],_=n[2],x=o,S=c,A=a,D=u,R=h,k=l,M=y,O=p,F=g,v=d,b=f,N=w,U=m,C=K,T=P,$=_;for(let se=0;se<s;se+=2)x=x+R|0,U=B(U^x,16),F=F+U|0,R=B(R^F,12),x=x+R|0,U=B(U^x,8),F=F+U|0,R=B(R^F,7),S=S+k|0,C=B(C^S,16),v=v+C|0,k=B(k^v,12),S=S+k|0,C=B(C^S,8),v=v+C|0,k=B(k^v,7),A=A+M|0,T=B(T^A,16),b=b+T|0,M=B(M^b,12),A=A+M|0,T=B(T^A,8),b=b+T|0,M=B(M^b,7),D=D+O|0,$=B($^D,16),N=N+$|0,O=B(O^N,12),D=D+O|0,$=B($^D,8),N=N+$|0,O=B(O^N,7),x=x+k|0,$=B($^x,16),b=b+$|0,k=B(k^b,12),x=x+k|0,$=B($^x,8),b=b+$|0,k=B(k^b,7),S=S+M|0,U=B(U^S,16),N=N+U|0,M=B(M^N,12),S=S+M|0,U=B(U^S,8),N=N+U|0,M=B(M^N,7),A=A+O|0,C=B(C^A,16),F=F+C|0,O=B(O^F,12),A=A+O|0,C=B(C^A,8),F=F+C|0,O=B(O^F,7),D=D+R|0,T=B(T^D,16),v=v+T|0,R=B(R^v,12),D=D+R|0,T=B(T^D,8),v=v+T|0,R=B(R^v,7);let L=0;r[L++]=o+x|0,r[L++]=c+S|0,r[L++]=a+A|0,r[L++]=u+D|0,r[L++]=h+R|0,r[L++]=l+k|0,r[L++]=y+M|0,r[L++]=p+O|0,r[L++]=g+F|0,r[L++]=d+v|0,r[L++]=f+b|0,r[L++]=w+N|0,r[L++]=m+U|0,r[L++]=K+C|0,r[L++]=P+T|0,r[L++]=_+$|0}const Vr=_o(Uo,{counterRight:!1,counterLength:4,allowShortKeys:!1});class zr extends gr{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ue.hash(e);const r=at(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return ue.exists(this),this.iHash.update(e),this}digestInto(e){ue.exists(this),ue.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:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const St=(t,e,n)=>new zr(t,e).update(n).digest();St.create=(t,e)=>new zr(t,e);function wn(t,e,n){return ue.hash(t),n===void 0&&(n=new Uint8Array(t.outputLen)),St(t,at(n),at(e))}const vn=new Uint8Array([0]),qr=new Uint8Array;function Fr(t,e,n,r=32){if(ue.hash(t),ue.number(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);n===void 0&&(n=qr);const s=new Uint8Array(i*t.outputLen),o=St.create(t,e),c=o._cloneInto(),a=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)vn[0]=u+1,c.update(u===0?qr:a).update(n).update(vn).digestInto(a),s.set(a,t.outputLen*u),o._cloneInto(c);return o.destroy(),c.destroy(),a.fill(0),vn.fill(0),s.slice(0,r)}var Ro=Object.defineProperty,V=(t,e)=>{for(var n in e)Ro(t,n,{get:e[n],enumerable:!0})},Xe=Symbol("verified"),Bo=t=>t instanceof Object;function Kt(t){if(!Bo(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var To={};V(To,{Queue:()=>$o,QueueNode:()=>jr,binarySearch:()=>bn,bytesToHex:()=>H,hexToBytes:()=>z,insertEventIntoAscendingList:()=>Oo,insertEventIntoDescendingList:()=>Mo,normalizeURL:()=>Lo,utf8Decoder:()=>me,utf8Encoder:()=>re});var me=new TextDecoder("utf-8"),re=new TextEncoder;function Lo(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}function Mo(t,e){const[n,r]=bn(t,i=>e.id===i.id?0:e.created_at===i.created_at?-1:i.created_at-e.created_at);return r||t.splice(n,0,e),t}function Oo(t,e){const[n,r]=bn(t,i=>e.id===i.id?0:e.created_at===i.created_at?-1:e.created_at-i.created_at);return r||t.splice(n,0,e),t}function bn(t,e){let n=0,r=t.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=e(t[i]);if(s===0)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var jr=class{constructor(t){E(this,"value");E(this,"next",null);E(this,"prev",null);this.value=t}},$o=class{constructor(){E(this,"first");E(this,"last");this.first=null,this.last=null}enqueue(t){const e=new jr(t);return this.last?this.last===this.first?(this.last=e,this.last.prev=this.first,this.first.next=e):(e.prev=this.last,this.last.next=e,this.last=e):(this.first=e,this.last=e),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const e=this.first;return this.first=null,this.last=null,e.value}const t=this.first;return this.first=t.next,this.first&&(this.first.prev=null),t.value}},Do=class{generateSecretKey(){return ot.utils.randomPrivateKey()}getPublicKey(t){return H(ot.getPublicKey(t))}finalizeEvent(t,e){const n=t;return n.pubkey=H(ot.getPublicKey(e)),n.id=$e(n),n.sig=H(ot.sign($e(n),e)),n[Xe]=!0,n}verifyEvent(t){if(typeof t[Xe]=="boolean")return t[Xe];const e=$e(t);if(e!==t.id)return t[Xe]=!1,!1;try{const n=ot.verify(t.sig,e,t.pubkey);return t[Xe]=n,n}catch{return t[Xe]=!1,!1}}};function Ho(t){if(!Kt(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function $e(t){let e=le(re.encode(Ho(t)));return H(e)}var At=new Do,_e=At.generateSecretKey,fe=At.getPublicKey,ee=At.finalizeEvent,ut=At.verifyEvent,Vo={};V(Vo,{Application:()=>ec,BadgeAward:()=>Jo,BadgeDefinition:()=>Ga,BlockedRelaysList:()=>Ca,BlossomServerList:()=>La,BookmarkList:()=>Na,Bookmarksets:()=>qa,Calendar:()=>ac,CalendarEventRSVP:()=>cc,ChannelCreation:()=>Yr,ChannelHideMessage:()=>ti,ChannelMessage:()=>ei,ChannelMetadata:()=>Qr,ChannelMuteUser:()=>ni,ChatMessage:()=>Xo,ClassifiedListing:()=>rc,ClientAuth:()=>ii,Comment:()=>oa,CommunitiesList:()=>Ia,CommunityDefinition:()=>dc,CommunityPostApproval:()=>ya,Contacts:()=>Go,CreateOrUpdateProduct:()=>Ja,CreateOrUpdateStall:()=>Za,Curationsets:()=>Fa,Date:()=>sc,DirectMessageRelaysList:()=>Ba,DraftClassifiedListing:()=>ic,DraftLong:()=>Ya,Emojisets:()=>Qa,EncryptedDirectMessage:()=>Wo,EventDeletion:()=>Zo,FavoriteRelays:()=>_a,FileMessage:()=>Qo,FileMetadata:()=>sa,FileServerPreference:()=>Ta,Followsets:()=>Ha,ForumThread:()=>Yo,GenericRepost:()=>Kn,Genericlists:()=>Va,GiftWrap:()=>ri,GroupMetadata:()=>fc,HTTPAuth:()=>An,Handlerinformation:()=>hc,Handlerrecommendation:()=>lc,Highlights:()=>Ea,InterestsList:()=>Ua,Interestsets:()=>Wa,JobFeedback:()=>wa,JobRequest:()=>pa,JobResult:()=>ga,Label:()=>fa,LightningPubRPC:()=>Oa,LiveChatMessage:()=>aa,LiveEvent:()=>tc,LongFormArticle:()=>Xa,Metadata:()=>Fo,Mutelist:()=>Sa,NWCWalletInfo:()=>Ma,NWCWalletRequest:()=>si,NWCWalletResponse:()=>$a,NormalVideo:()=>ta,NostrConnect:()=>Da,OpenTimestamps:()=>ra,Photo:()=>ea,Pinlist:()=>Ka,Poll:()=>ia,PollResponse:()=>xa,PrivateDirectMessage:()=>Xr,ProblemTracker:()=>la,ProfileBadges:()=>ja,PublicChatsList:()=>ka,Reaction:()=>Sn,RecommendRelay:()=>jo,RelayList:()=>Aa,RelayReview:()=>uc,Relaysets:()=>za,Report:()=>ha,Reporting:()=>da,Repost:()=>xn,Seal:()=>Jr,SearchRelaysList:()=>Pa,ShortTextNote:()=>Zr,ShortVideo:()=>na,Time:()=>oc,UserEmojiList:()=>Ra,UserStatuses:()=>nc,Voice:()=>ca,VoiceComment:()=>ua,Zap:()=>ma,ZapGoal:()=>va,ZapRequest:()=>ba,classifyKind:()=>zo,isAddressableKind:()=>En,isEphemeralKind:()=>Wr,isKind:()=>qo,isRegularKind:()=>Gr,isReplaceableKind:()=>mn});function Gr(t){return t<1e4&&t!==0&&t!==3}function mn(t){return t===0||t===3||1e4<=t&&t<2e4}function Wr(t){return 2e4<=t&&t<3e4}function En(t){return 3e4<=t&&t<4e4}function zo(t){return Gr(t)?"regular":mn(t)?"replaceable":Wr(t)?"ephemeral":En(t)?"parameterized":"unknown"}function qo(t,e){const n=e instanceof Array?e:[e];return Kt(t)&&n.includes(t.kind)||!1}var Fo=0,Zr=1,jo=2,Go=3,Wo=4,Zo=5,xn=6,Sn=7,Jo=8,Xo=9,Yo=11,Jr=13,Xr=14,Qo=15,Kn=16,ea=20,ta=21,na=22,Yr=40,Qr=41,ei=42,ti=43,ni=44,ra=1040,ri=1059,ia=1068,sa=1063,oa=1111,aa=1311,ca=1222,ua=1244,la=1971,ha=1984,da=1984,fa=1985,ya=4550,pa=5999,ga=6999,wa=7e3,va=9041,ba=9734,ma=9735,Ea=9802,xa=1018,Sa=1e4,Ka=10001,Aa=10002,Na=10003,Ia=10004,ka=10005,Ca=10006,Pa=10007,_a=10012,Ua=10015,Ra=10030,Ba=10050,Ta=10096,La=10063,Ma=13194,Oa=21e3,ii=22242,si=23194,$a=23195,Da=24133,An=27235,Ha=3e4,Va=30001,za=30002,qa=30003,Fa=30004,ja=30008,Ga=30009,Wa=30015,Za=30017,Ja=30018,Xa=30023,Ya=30024,Qa=30030,ec=30078,tc=30311,nc=30315,rc=30402,ic=30403,sc=31922,oc=31923,ac=31924,cc=31925,uc=31987,lc=31989,hc=31990,dc=34550,fc=39e3,yc={};V(yc,{getHex64:()=>Nn,getInt:()=>oi,getSubscriptionId:()=>pc,matchEventId:()=>gc,matchEventKind:()=>vc,matchEventPubkey:()=>wc});function Nn(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,i=t.slice(r).indexOf('"')+r+1;return t.slice(i,i+64)}function oi(t,e){let n=e.length,r=t.indexOf(`"${e}":`)+n+3,i=t.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function pc(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,i=t.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return t.slice(r+1,s)}function gc(t,e){return e===Nn(t,"id")}function wc(t,e){return e===Nn(t,"pubkey")}function vc(t,e){return e===oi(t,"kind")}var bc={};V(bc,{makeAuthEvent:()=>mc});function mc(t,e){return{kind:ii,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var Ec;try{Ec=WebSocket}catch{}var xc;try{xc=WebSocket}catch{}var Sc={};V(Sc,{BECH32_REGEX:()=>ai,Bech32MaxSize:()=>In,NostrTypeGuard:()=>Kc,decode:()=>Nt,decodeNostrURI:()=>Nc,encodeBytes:()=>kt,naddrEncode:()=>Uc,neventEncode:()=>_c,noteEncode:()=>Cc,nprofileEncode:()=>Pc,npubEncode:()=>kc,nsecEncode:()=>Ic});var Kc={isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")},In=5e3,ai=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function Ac(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function Nc(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),Nt(t)}catch{return{type:"invalid",data:null}}}function Nt(t){var i,s,o,c,a,u,h;let{prefix:e,words:n}=We.decode(t,In),r=new Uint8Array(We.fromWords(n));switch(e){case"nprofile":{let l=kn(r);if(!((i=l[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:H(l[0][0]),relays:l[1]?l[1].map(y=>me.decode(y)):[]}}}case"nevent":{let l=kn(r);if(!((s=l[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(l[2]&&l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(l[3]&&l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:H(l[0][0]),relays:l[1]?l[1].map(y=>me.decode(y)):[],author:(o=l[2])!=null&&o[0]?H(l[2][0]):void 0,kind:(c=l[3])!=null&&c[0]?parseInt(H(l[3][0]),16):void 0}}}case"naddr":{let l=kn(r);if(!((a=l[0])!=null&&a[0]))throw new Error("missing TLV 0 for naddr");if(!((u=l[2])!=null&&u[0]))throw new Error("missing TLV 2 for naddr");if(l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((h=l[3])!=null&&h[0]))throw new Error("missing TLV 3 for naddr");if(l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:me.decode(l[0][0]),pubkey:H(l[2][0]),kind:parseInt(H(l[3][0]),16),relays:l[1]?l[1].map(y=>me.decode(y)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:H(r)};default:throw new Error(`unknown prefix ${e}`)}}function kn(t){let e={},n=t;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(s)}return e}function Ic(t){return kt("nsec",t)}function kc(t){return kt("npub",z(t))}function Cc(t){return kt("note",z(t))}function It(t,e){let n=We.toWords(e);return We.encode(t,n,In)}function kt(t,e){return It(t,e)}function Pc(t){let e=Cn({0:[z(t.pubkey)],1:(t.relays||[]).map(n=>re.encode(n))});return It("nprofile",e)}function _c(t){let e;t.kind!==void 0&&(e=Ac(t.kind));let n=Cn({0:[z(t.id)],1:(t.relays||[]).map(r=>re.encode(r)),2:t.author?[z(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return It("nevent",n)}function Uc(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let n=Cn({0:[re.encode(t.identifier)],1:(t.relays||[]).map(r=>re.encode(r)),2:[z(t.pubkey)],3:[new Uint8Array(e)]});return It("naddr",n)}function Cn(t){let e=[];return Object.entries(t).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),e.push(s)})}),bt(...e)}var Rc={};V(Rc,{decrypt:()=>Bc,encrypt:()=>ci});function ci(t,e,n){const r=t instanceof Uint8Array?H(t):t,i=Oe.getSharedSecret(r,"02"+e),s=ui(i);let o=Uint8Array.from(vr(16)),c=re.encode(n),a=Mr(s,o).encrypt(c),u=ve.encode(new Uint8Array(a)),h=ve.encode(new Uint8Array(o.buffer));return`${u}?iv=${h}`}function Bc(t,e,n){const r=t instanceof Uint8Array?H(t):t;let[i,s]=n.split("?iv="),o=Oe.getSharedSecret(r,"02"+e),c=ui(o),a=ve.decode(s),u=ve.decode(i),h=Mr(c,a).decrypt(u);return me.decode(h)}function ui(t){return t.slice(1,33)}var Tc={};V(Tc,{NIP05_REGEX:()=>Pn,isNip05:()=>Lc,isValid:()=>$c,queryProfile:()=>li,searchDomain:()=>Oc,useFetchImplementation:()=>Mc});var Pn=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Lc=t=>Pn.test(t||""),Ct;try{Ct=fetch}catch{}function Mc(t){Ct=t}async function Oc(t,e=""){try{const n=`https://${t}/.well-known/nostr.json?name=${e}`,r=await Ct(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function li(t){var i;const e=t.match(Pn);if(!e)return null;const[,n="_",r]=e;try{const s=`https://${r}/.well-known/nostr.json?name=${n}`,o=await Ct(s,{redirect:"manual"});if(o.status!==200)throw Error("Wrong response code");const c=await o.json(),a=c.names[n];return a?{pubkey:a,relays:(i=c.relays)==null?void 0:i[a]}:null}catch{return null}}async function $c(t,e){const n=await li(e);return n?n.pubkey===t:!1}var Dc={};V(Dc,{parse:()=>Hc});function Hc(t){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let i=t.tags.length-1;i>=0;i--){const s=t.tags[i];if(s[0]==="e"&&s[1]){const[o,c,a,u,h]=s,l={id:c,relays:a?[a]:[],author:h};if(u==="root"){e.root=l;continue}if(u==="reply"){e.reply=l;continue}if(u==="mention"){e.mentions.push(l);continue}n?r=l:n=l,e.mentions.push(l);continue}if(s[0]==="q"&&s[1]){const[o,c,a]=s;e.quotes.push({id:c,relays:a?[a]:[]})}if(s[0]==="p"&&s[1]){e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return e.root||(e.root=r||n||e.reply),e.reply||(e.reply=n||e.root),[e.reply,e.root].forEach(i=>{if(!i)return;let s=e.mentions.indexOf(i);if(s!==-1&&e.mentions.splice(s,1),i.author){let o=e.profiles.find(c=>c.pubkey===i.author);o&&o.relays&&(i.relays||(i.relays=[]),o.relays.forEach(c=>{var a;((a=i.relays)==null?void 0:a.indexOf(c))===-1&&i.relays.push(c)}),o.relays=i.relays)}}),e.mentions.forEach(i=>{if(i.author){let s=e.profiles.find(o=>o.pubkey===i.author);s&&s.relays&&(i.relays||(i.relays=[]),s.relays.forEach(o=>{i.relays.indexOf(o)===-1&&i.relays.push(o)}),s.relays=i.relays)}}),e}var Vc={};V(Vc,{fetchRelayInformation:()=>qc,useFetchImplementation:()=>zc});var hi;try{hi=fetch}catch{}function zc(t){hi=t}async function qc(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var Fc={};V(Fc,{fastEventHash:()=>fi,getPow:()=>di,minePow:()=>jc});function di(t){let e=0;for(let n=0;n<64;n+=8){const r=parseInt(t.substring(n,n+8),16);if(r===0)e+=32;else{e+=Math.clz32(r);break}}return e}function jc(t,e){let n=0;const r=t,i=["nonce",n.toString(),e.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);if(s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString(),r.id=fi(r),di(r.id)>=e)break}return r}function fi(t){return H(le(re.encode(JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]))))}var Gc={};V(Gc,{unwrapEvent:()=>iu,unwrapManyEvents:()=>su,wrapEvent:()=>Ii,wrapManyEvents:()=>ru});var Wc={};V(Wc,{createRumor:()=>Si,createSeal:()=>Ki,createWrap:()=>Ai,unwrapEvent:()=>Tn,unwrapManyEvents:()=>Ni,wrapEvent:()=>Pt,wrapManyEvents:()=>tu});var q={};V(q,{decrypt:()=>Bn,encrypt:()=>Rn,getConversationKey:()=>_n,v2:()=>Qc});var yi=1,pi=65535;function _n(t,e){const n=Oe.getSharedSecret(t,"02"+e).subarray(1,33);return wn(le,n,"nip44-v2")}function gi(t,e){const n=Fr(le,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Un(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;const e=1<<Math.floor(Math.log2(t-1))+1,n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function Zc(t){if(!Number.isSafeInteger(t)||t<yi||t>pi)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function Jc(t){const e=re.encode(t),n=e.length,r=Zc(n),i=new Uint8Array(Un(n)-n);return bt(r,e,i)}function Xc(t){const e=new DataView(t.buffer).getUint16(0),n=t.subarray(2,2+e);if(e<yi||e>pi||n.length!==e||t.length!==2+Un(e))throw new Error("invalid padding");return me.decode(n)}function wi(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=bt(n,e);return St(le,t,r)}function Yc(t){if(typeof t!="string")throw new Error("payload must be a valid string");const e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=ve.decode(t)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Rn(t,e,n=vr(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=gi(e,n),o=Jc(t),c=Vr(r,i,o),a=wi(s,c,n);return ve.encode(bt(new Uint8Array([2]),n,c,a))}function Bn(t,e){const{nonce:n,ciphertext:r,mac:i}=Yc(t),{chacha_key:s,chacha_nonce:o,hmac_key:c}=gi(e,n),a=wi(c,r,n);if(!yo(a,i))throw new Error("invalid MAC");const u=Vr(s,o,r);return Xc(u)}var Qc={utils:{getConversationKey:_n,calcPaddedLen:Un},encrypt:Rn,decrypt:Bn},eu=2880*60,vi=()=>Math.round(Date.now()/1e3),bi=()=>Math.round(vi()-Math.random()*eu),mi=(t,e)=>_n(t,e),Ei=(t,e,n)=>Rn(JSON.stringify(t),mi(e,n)),xi=(t,e)=>JSON.parse(Bn(t.content,mi(e,t.pubkey)));function Si(t,e){const n={created_at:vi(),content:"",tags:[],...t,pubkey:fe(e)};return n.id=$e(n),n}function Ki(t,e,n){return ee({kind:Jr,content:Ei(t,e,n),created_at:bi(),tags:[]},e)}function Ai(t,e){const n=_e();return ee({kind:ri,content:Ei(t,n,e),created_at:bi(),tags:[["p",e]]},n)}function Pt(t,e,n){const r=Si(t,e),i=Ki(r,e,n);return Ai(i,n)}function tu(t,e,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");const r=fe(e),i=[Pt(t,e,r)];return n.forEach(s=>{i.push(Pt(t,e,s))}),i}function Tn(t,e){const n=xi(t,e);return xi(n,e)}function Ni(t,e){let n=[];return t.forEach(r=>{n.push(Tn(r,e))}),n.sort((r,i)=>r.created_at-i.created_at),n}function nu(t,e,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:Xr,tags:[],content:e};return(Array.isArray(t)?t:[t]).forEach(({publicKey:o,relayUrl:c})=>{i.tags.push(c?["p",o,c]:["p",o])}),r&&i.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&i.tags.push(["subject",n]),i}function Ii(t,e,n,r,i){const s=nu(e,n,r,i);return Pt(s,t,e.publicKey)}function ru(t,e,n,r,i){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:fe(t)},...e].map(o=>Ii(t,o,n,r,i))}var iu=Tn,su=Ni,ou={};V(ou,{finishRepostEvent:()=>au,getRepostedEvent:()=>cu,getRepostedEventPointer:()=>ki});function au(t,e,n,r){var o;let i;const s=[...t.tags??[],["e",e.id,n],["p",e.pubkey]];return e.kind===Zr?i=xn:(i=Kn,s.push(["k",String(e.kind)])),ee({kind:i,tags:s,content:t.content===""||(o=e.tags)!=null&&o.find(c=>c[0]==="-")?"":JSON.stringify(e),created_at:t.created_at},r)}function ki(t){if(![xn,Kn].includes(t.kind))return;let e,n;for(let r=t.tags.length-1;r>=0&&(e===void 0||n===void 0);r--){const i=t.tags[r];i.length>=2&&(i[0]==="e"&&e===void 0?e=i:i[0]==="p"&&n===void 0&&(n=i))}if(e!==void 0)return{id:e[1],relays:[e[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function cu(t,{skipVerification:e}={}){const n=ki(t);if(n===void 0||t.content==="")return;let r;try{r=JSON.parse(t.content)}catch{return}if(r.id===n.id&&!(!e&&!ut(r)))return r}var uu={};V(uu,{NOSTR_URI_REGEX:()=>Ln,parse:()=>hu,test:()=>lu});var Ln=new RegExp(`nostr:(${ai.source})`);function lu(t){return typeof t=="string"&&new RegExp(`^${Ln.source}$`).test(t)}function hu(t){const e=t.match(new RegExp(`^${Ln.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:Nt(e[1])}}var du={};V(du,{finishReactionEvent:()=>fu,getReactedEventPointer:()=>yu});function fu(t,e,n){const r=e.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return ee({...t,kind:Sn,tags:[...t.tags??[],...r,["e",e.id],["p",e.pubkey]],content:t.content??"+"},n)}function yu(t){if(t.kind!==Sn)return;let e,n;for(let r=t.tags.length-1;r>=0&&(e===void 0||n===void 0);r--){const i=t.tags[r];i.length>=2&&(i[0]==="e"&&e===void 0?e=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(e===void 0||n===void 0))return{id:e[1],relays:[e[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var pu={};V(pu,{parse:()=>wu});var Ci=/\W/m,Pi=/[^\w\/] |[^\w\/]$|$|,| /m,gu=42;function*wu(t){let e=[];if(typeof t!="string"){for(let s=0;s<t.tags.length;s++){const o=t.tags[s];o[0]==="emoji"&&o.length>=3&&e.push({type:"emoji",shortcode:o[1],url:o[2]})}t=t.content}const n=t.length;let r=0,i=0;e:for(;i<n;){const s=t.indexOf(":",i),o=t.indexOf("#",i);if(s===-1&&o===-1)break e;if(s===-1||o>=0&&o<s){if(o===0||t[o-1]===" "){const c=t.slice(o+1,o+gu).match(Ci),a=c?o+1+c.index:n;yield{type:"text",text:t.slice(r,o)},yield{type:"hashtag",value:t.slice(o+1,a)},i=a,r=i;continue e}i=o+1;continue e}if(t.slice(s-5,s)==="nostr"){const c=t.slice(s+60).match(Ci),a=c?s+60+c.index:n;try{let u,{data:h,type:l}=Nt(t.slice(s+1,a));switch(l){case"npub":u={pubkey:h};break;case"note":u={id:h};break;case"nsec":i=a+1;continue;default:u=h}r!==s-5&&(yield{type:"text",text:t.slice(r,s-5)}),yield{type:"reference",pointer:u},i=a,r=i;continue e}catch{i=s+1;continue e}}else if(t.slice(s-5,s)==="https"||t.slice(s-4,s)==="http"){const c=t.slice(s+4).match(Pi),a=c?s+4+c.index:n,u=t[s-1]==="s"?5:4;try{let h=new URL(t.slice(s-u,a));if(h.hostname.indexOf(".")===-1)throw new Error("invalid url");if(r!==s-u&&(yield{type:"text",text:t.slice(r,s-u)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(h.pathname)){yield{type:"image",url:h.toString()},i=a,r=i;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(h.pathname)){yield{type:"video",url:h.toString()},i=a,r=i;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(h.pathname)){yield{type:"audio",url:h.toString()},i=a,r=i;continue e}yield{type:"url",url:h.toString()},i=a,r=i;continue e}catch{i=a+1;continue e}}else if(t.slice(s-3,s)==="wss"||t.slice(s-2,s)==="ws"){const c=t.slice(s+4).match(Pi),a=c?s+4+c.index:n,u=t[s-1]==="s"?3:2;try{let h=new URL(t.slice(s-u,a));if(h.hostname.indexOf(".")===-1)throw new Error("invalid ws url");r!==s-u&&(yield{type:"text",text:t.slice(r,s-u)}),yield{type:"relay",url:h.toString()},i=a,r=i;continue e}catch{i=a+1;continue e}}else{for(let c=0;c<e.length;c++){const a=e[c];if(t[s+a.shortcode.length+1]===":"&&t.slice(s+1,s+a.shortcode.length+1)===a.shortcode){r!==s&&(yield{type:"text",text:t.slice(r,s)}),yield a,i=s+a.shortcode.length+2,r=i;continue e}}i=s+1;continue e}}r!==n&&(yield{type:"text",text:t.slice(r)})}var vu={};V(vu,{channelCreateEvent:()=>bu,channelHideMessageEvent:()=>xu,channelMessageEvent:()=>Eu,channelMetadataEvent:()=>mu,channelMuteUserEvent:()=>Su});var bu=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return ee({kind:Yr,tags:[...t.tags??[]],content:n,created_at:t.created_at},e)},mu=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return ee({kind:Qr,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},Eu=(t,e)=>{const n=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&n.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),ee({kind:ei,tags:[...n,...t.tags??[]],content:t.content,created_at:t.created_at},e)},xu=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return ee({kind:ti,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},Su=(t,e)=>{let n;if(typeof t.content=="object")n=JSON.stringify(t.content);else if(typeof t.content=="string")n=t.content;else return;return ee({kind:ni,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:n,created_at:t.created_at},e)},Ku={};V(Ku,{EMOJI_SHORTCODE_REGEX:()=>_i,matchAll:()=>Au,regex:()=>Mn,replaceAll:()=>Nu});var _i=/:(\w+):/,Mn=()=>new RegExp(`\\B${_i.source}\\B`,"g");function*Au(t){const e=t.matchAll(Mn());for(const n of e)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function Nu(t,e){return t.replaceAll(Mn(),(n,r)=>e({shortcode:n,name:r}))}var Iu={};V(Iu,{useFetchImplementation:()=>ku,validateGithub:()=>Cu});var On;try{On=fetch}catch{}function ku(t){On=t}async function Cu(t,e,n){try{return await(await On(`https://gist.github.com/${e}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch{return!1}}var Pu={};V(Pu,{makeNwcRequestEvent:()=>Uu,parseConnectionString:()=>_u});function _u(t){const{host:e,pathname:n,searchParams:r}=new URL(t),i=n||e,s=r.get("relay"),o=r.get("secret");if(!i||!s||!o)throw new Error("invalid connection string");return{pubkey:i,relay:s,secret:o}}async function Uu(t,e,n){const i=ci(e,t,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:si,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",t]]};return ee(s,e)}var Ru={};V(Ru,{normalizeIdentifier:()=>Bu});function Bu(t){return t=t.trim().toLowerCase(),t=t.normalize("NFKC"),Array.from(t).map(e=>new RegExp("\\p{Letter}","u").test(e)||new RegExp("\\p{Number}","u").test(e)?e:"-").join("")}var Tu={};V(Tu,{getSatoshisAmountFromBolt11:()=>Hu,getZapEndpoint:()=>Mu,makeZapReceipt:()=>Du,makeZapRequest:()=>Ou,useFetchImplementation:()=>Lu,validateZapRequest:()=>$u});var $n;try{$n=fetch}catch{}function Lu(t){$n=t}async function Mu(t){try{let e="",{lud06:n,lud16:r}=JSON.parse(t.content);if(r){let[o,c]=r.split("@");e=new URL(`/.well-known/lnurlp/${o}`,`https://${c}`).toString()}else if(n){let{words:o}=We.decode(n,1e3),c=We.fromWords(o);e=me.decode(c)}else return null;let s=await(await $n(e)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function Ou(t){let e={kind:9734,created_at:Math.round(Date.now()/1e3),content:t.comment||"",tags:[["p","pubkey"in t?t.pubkey:t.event.pubkey],["amount",t.amount.toString()],["relays",...t.relays]]};if("event"in t){if(e.tags.push(["e",t.event.id]),mn(t.event.kind)){const n=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(n)}else if(En(t.event.kind)){let n=t.event.tags.find(([i,s])=>i==="d"&&s);if(!n)throw new Error("d tag not found or is empty");const r=["a",`${t.event.kind}:${t.event.pubkey}:${n[1]}`];e.tags.push(r)}e.tags.push(["k",t.event.kind.toString()])}return e}function $u(t){let e;try{e=JSON.parse(t)}catch{return"Invalid zap request JSON."}if(!Kt(e))return"Zap request is not a valid Nostr event.";if(!ut(e))return"Invalid signature on zap request.";let n=e.tags.find(([s,o])=>s==="p"&&o);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=e.tags.find(([s,o])=>s==="e"&&o);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([s,o])=>s==="relays"&&o)?null:"Zap request doesn't have a 'relays' tag."}function Du({zapRequest:t,preimage:e,bolt11:n,paidAt:r}){let i=JSON.parse(t),s=i.tags.filter(([c])=>c==="e"||c==="p"||c==="a"),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",t]]};return e&&o.tags.push(["preimage",e]),o}function Hu(t){if(t.length<50)return 0;t=t.substring(0,50);const e=t.lastIndexOf("1");if(e===-1)return 0;const n=t.substring(0,e);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const i=r[r.length-1],s=i.charCodeAt(0)-48,o=s>=0&&s<=9;let c=r.length-1;if(o&&c++,c<1)return 0;const a=parseInt(r.substring(0,c));switch(i){case"m":return a*1e5;case"u":return a*100;case"n":return a/10;case"p":return a/1e4;default:return a*1e8}}var Vu={};V(Vu,{Negentropy:()=>Ri,NegentropyStorageVector:()=>Fu,NegentropySync:()=>ju});var Dn=97,Ye=32,Ui=16,De={Skip:0,Fingerprint:1,IdList:2},Ee=class{constructor(t){E(this,"_raw");E(this,"length");typeof t=="number"?(this._raw=new Uint8Array(t),this.length=0):t instanceof Uint8Array?(this._raw=new Uint8Array(t),this.length=t.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof Ee&&(t=t.unwrap()),typeof t.length!="number")throw Error("bad length");const e=t.length+this.length;if(this.capacity<e){const n=this._raw,r=Math.max(this.capacity*2,e);this._raw=new Uint8Array(r),this._raw.set(n)}this._raw.set(t,this.length),this.length+=t.length}shift(){const t=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,t}shiftN(t=1){const e=this._raw.subarray(0,t);return this._raw=this._raw.subarray(t),this.length-=t,e}};function _t(t){let e=0;for(;;){if(t.length===0)throw Error("parse ends prematurely");let n=t.shift();if(e=e<<7|n&127,(n&128)===0)break}return e}function xe(t){if(t===0)return new Ee(new Uint8Array([0]));let e=[];for(;t!==0;)e.push(t&127),t>>>=7;e.reverse();for(let n=0;n<e.length-1;n++)e[n]|=128;return new Ee(new Uint8Array(e))}function zu(t){return Ut(t,1)[0]}function Ut(t,e){if(t.length<e)throw Error("parse ends prematurely");return t.shiftN(e)}var qu=class{constructor(){E(this,"buf");this.setToZero()}setToZero(){this.buf=new Uint8Array(Ye)}add(t){let e=0,n=0,r=new DataView(this.buf.buffer),i=new DataView(t.buffer);for(let s=0;s<8;s++){let o=s*4,c=r.getUint32(o,!0),a=i.getUint32(o,!0),u=c;u+=e,u+=a,u>4294967295&&(n=1),r.setUint32(o,u&4294967295,!0),e=n,n=0}}negate(){let t=new DataView(this.buf.buffer);for(let n=0;n<8;n++){let r=n*4;t.setUint32(r,~t.getUint32(r,!0))}let e=new Uint8Array(Ye);e[0]=1,this.add(e)}getFingerprint(t){let e=new Ee;return e.extend(this.buf),e.extend(xe(t)),le(e.unwrap()).subarray(0,Ui)}},Fu=class{constructor(){E(this,"items");E(this,"sealed");this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");const n=_r(e);if(n.byteLength!==Ye)throw Error("bad id size for added item");this.items.push({timestamp:t,id:n})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(Hn);for(let t=1;t<this.items.length;t++)if(Hn(this.items[t-1],this.items[t])===0)throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(t){if(this._checkSealed(),t>=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,n){this._checkSealed(),this._checkBounds(t,e);for(let r=t;r<e&&n(this.items[r],r);++r);}findLowerBound(t,e,n){return this._checkSealed(),this._checkBounds(t,e),this._binarySearch(this.items,t,e,r=>Hn(r,n)<0)}fingerprint(t,e){let n=new qu;return n.setToZero(),this.iterate(t,e,r=>(n.add(r.id),!0)),n.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,n,r){let i=n-e;for(;i>0;){let s=e,o=Math.floor(i/2);s+=o,r(t[s])?(e=++s,i-=o+1):i=o}return e}},Ri=class{constructor(t,e=6e4){E(this,"storage");E(this,"frameSizeLimit");E(this,"lastTimestampIn");E(this,"lastTimestampOut");if(e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}initiate(){let t=new Ee;return t.extend(new Uint8Array([Dn])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),Ze(t.unwrap())}reconcile(t,e,n){const r=new Ee(_r(t));this.lastTimestampIn=this.lastTimestampOut=0;let i=new Ee;i.extend(new Uint8Array([Dn]));let s=zu(r);if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(s!==Dn)throw Error("unsupported negentropy protocol version requested: "+(s-96));let o=this.storage.size(),c=this._bound(0),a=0,u=!1;for(;r.length!==0;){let h=new Ee,l=()=>{u&&(u=!1,h.extend(this.encodeBound(c)),h.extend(xe(De.Skip)))},y=this.decodeBound(r),p=_t(r),g=a,d=this.storage.findLowerBound(a,o,y);if(p===De.Skip)u=!0;else if(p===De.Fingerprint){let f=Ut(r,Ui),w=this.storage.fingerprint(g,d);Bi(f,w)!==0?(l(),this.splitRange(g,d,y,h)):u=!0}else if(p===De.IdList){let f=_t(r),w={};for(let m=0;m<f;m++){let K=Ut(r,Ye);w[Ze(K)]=K}if(u=!0,this.storage.iterate(g,d,m=>{let K=m.id;const P=Ze(K);return w[P]?delete w[Ze(K)]:e==null||e(P),!0}),n)for(let m of Object.values(w))n(Ze(m))}else throw Error("unexpected mode");if(this.exceededFrameSizeLimit(i.length+h.length)){let f=this.storage.fingerprint(d,o);i.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),i.extend(xe(De.Fingerprint)),i.extend(f);break}else i.extend(h);a=d,c=y}return i.length===1?null:Ze(i.unwrap())}splitRange(t,e,n,r){let i=e-t,s=16;if(i<s*2)r.extend(this.encodeBound(n)),r.extend(xe(De.IdList)),r.extend(xe(i)),this.storage.iterate(t,e,o=>(r.extend(o.id),!0));else{let o=Math.floor(i/s),c=i%s,a=t;for(let u=0;u<s;u++){let h=o+(u<c?1:0),l=this.storage.fingerprint(a,a+h);a+=h;let y;if(a===e)y=n;else{let p,g;this.storage.iterate(a-1,a+1,(d,f)=>(f===a-1?p=d:g=d,!0)),y=this.getMinimalBound(p,g)}r.extend(this.encodeBound(y)),r.extend(xe(De.Fingerprint)),r.extend(l)}}}exceededFrameSizeLimit(t){return t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=_t(t);return e=e===0?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),n=_t(t);if(n>Ye)throw Error("bound key too long");let r=Ut(t,n);return{timestamp:e,id:r}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,xe(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,xe(t+1)}encodeBound(t){let e=new Ee;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(xe(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let n=0,r=e.id,i=t.id;for(let s=0;s<Ye&&r[s]===i[s];s++)n++;return this._bound(e.timestamp,e.id.subarray(0,n+1))}}};function Bi(t,e){for(let n=0;n<t.byteLength;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return t.byteLength>e.byteLength?1:t.byteLength<e.byteLength?-1:0}function Hn(t,e){return t.timestamp===e.timestamp?Bi(t.id,e.id):t.timestamp-e.timestamp}var ju=class{constructor(t,e,n,r={}){E(this,"relay");E(this,"storage");E(this,"neg");E(this,"filter");E(this,"subscription");E(this,"onhave");E(this,"onneed");this.relay=t,this.storage=e,this.neg=new Ri(e),this.onhave=r.onhave,this.onneed=r.onneed,this.filter=n,this.subscription=this.relay.prepareSubscription([{}],{label:r.label||"negentropy"}),this.subscription.oncustom=i=>{var s,o,c,a;switch(i[0]){case"NEG-MSG":{i.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${i}`);try{const u=this.neg.reconcile(i[2],this.onhave,this.onneed);u?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${u}"]`):(this.close(),(s=r.onclose)==null||s.call(r))}catch(u){console.error("negentropy reconcile error:",u),(o=r==null?void 0:r.onclose)==null||o.call(r,`reconcile error: ${u}`)}break}case"NEG-CLOSE":{const u=i[2];console.warn("negentropy error:",u),(c=r.onclose)==null||c.call(r,u);break}case"NEG-ERR":(a=r.onclose)==null||a.call(r)}}}async start(){const t=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${t}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},Gu={};V(Gu,{getToken:()=>Wu,hashPayload:()=>Vn,unpackEventFromToken:()=>Li,validateEvent:()=>Vi,validateEventKind:()=>Oi,validateEventMethodTag:()=>Di,validateEventPayloadTag:()=>Hi,validateEventTimestamp:()=>Mi,validateEventUrlTag:()=>$i,validateToken:()=>Zu});var Ti="Nostr ";async function Wu(t,e,n,r=!1,i){const s={kind:An,tags:[["u",t],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",Vn(i)]);const o=await n(s);return(r?Ti:"")+ve.encode(re.encode(JSON.stringify(o)))}async function Zu(t,e,n){const r=await Li(t).catch(s=>{throw s});return await Vi(r,e,n).catch(s=>{throw s})}async function Li(t){if(!t)throw new Error("Missing token");t=t.replace(Ti,"");const e=me.decode(ve.decode(t));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function Mi(t){return t.created_at?Math.round(new Date().getTime()/1e3)-t.created_at<60:!1}function Oi(t){return t.kind===An}function $i(t,e){const n=t.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===e:!1}function Di(t,e){const n=t.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===e.toLowerCase():!1}function Vn(t){const e=le(re.encode(JSON.stringify(t)));return H(e)}function Hi(t,e){const n=t.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=Vn(e);return n.length>0&&n[1]===r}async function Vi(t,e,n,r){if(!ut(t))throw new Error("Invalid nostr event, signature invalid");if(!Oi(t))throw new Error("Invalid nostr event, kind invalid");if(!Mi(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!$i(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!Di(t,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!Hi(t,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const He=1060,Rt=30078,zn=1059,Ve=30078,qn=14,zi=7,qi=15,Fi=25,Ju=1;function ji(t){return JSON.stringify({version:Ju,rootKey:H(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:H(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:H(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?H(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?H(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys).map(([e,n])=>[e,{headerKeys:n.headerKeys.map(r=>H(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,H(i)]))}]))})}function Gi(t){const e=JSON.parse(t);if(!e.version){const n={};return e.skippedMessageKeys&&Object.entries(e.skippedMessageKeys).forEach(([r,i])=>{var s;n[r]={headerKeys:((s=e.skippedHeaderKeys)==null?void 0:s[r])||[],messageKeys:i}}),{rootKey:z(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:z(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:z(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?z(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?z(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:n}}return{rootKey:z(e.rootKey),theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,theirNextNostrPublicKey:e.theirNextNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:z(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:z(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?z(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?z(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(e.skippedKeys||{}).map(([n,r])=>[n,{headerKeys:r.headerKeys.map(i=>z(i)),messageKeys:Object.fromEntries(Object.entries(r.messageKeys).map(([i,s])=>[i,z(s)]))}]))}}function Wi(t){return{rootKey:new Uint8Array(t.rootKey),theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,theirNextNostrPublicKey:t.theirNextNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:new Uint8Array(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:new Uint8Array(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?new Uint8Array(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?new Uint8Array(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedKeys:Object.fromEntries(Object.entries(t.skippedKeys).map(([e,n])=>[e,{headerKeys:n.headerKeys.map(r=>new Uint8Array(r)),messageKeys:Object.fromEntries(Object.entries(n.messageKeys).map(([r,i])=>[r,new Uint8Array(i)]))}]))}}async function*Xu(t){const e=[];let n=null;const r=t.onEvent(i=>{n?(n(i),n=null):e.push(i)});try{for(;;)e.length>0?yield e.shift():yield new Promise(i=>{n=i})}finally{r()}}function ze(t,e=new Uint8Array(32),n=1){const r=wn(le,t,e),i=[];for(let s=1;s<=n;s++)i.push(Fr(le,r,new Uint8Array([s]),32));return i}function Yu(t){var n;const e=(n=t.tags)==null?void 0:n.find(r=>r[0]==="ms");return e?parseInt(e[1]):t.created_at*1e3}function Zi(t){try{const e=JSON.parse(t);if(e.type==="reaction"&&typeof e.messageId=="string"&&typeof e.emoji=="string")return e}catch{}return null}function Qu(t){return Zi(t)!==null}function Ji(t,e){return JSON.stringify({type:"reaction",messageId:t,emoji:e})}const el=1e3,tl="0000000000000000000000000000000000000000000000000000000000000000";class lt{constructor(e,n){E(this,"skippedSubscription");E(this,"nostrUnsubscribe");E(this,"nostrNextUnsubscribe");E(this,"internalSubscriptions",new Map);E(this,"currentInternalSubscriptionId",0);E(this,"name");this.nostrSubscribe=e,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(e,n,r,i,s,o){const c=_e();let a,u,h,l;i?([a,u]=ze(s,q.getConversationKey(c,n),2),h={publicKey:fe(r),privateKey:r},l={publicKey:fe(c),privateKey:c}):(a=s,u=void 0,h=void 0,l={publicKey:fe(r),privateKey:r});const y={rootKey:a,theirNextNostrPublicKey:n,ourCurrentNostrKey:h,ourNextNostrKey:l,receivingChainKey:void 0,sendingChainKey:u,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedKeys:{}},p=new lt(e,y);return o&&(p.name=o),p}send(e){return this.sendEvent({content:e,kind:qn})}sendReaction(e,n){return this.sendEvent({content:Ji(e,n),kind:zi,tags:[["e",e]]})}sendTyping(){return this.sendEvent({content:"typing",kind:Fi})}sendReceipt(e,n){return this.sendEvent({content:e,kind:qi,tags:n.map(r=>["e",r])})}sendEvent(e){if(!this.state.theirNextNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");if("sig"in e)throw new Error("Event must be unsigned "+JSON.stringify(e));const n=Date.now(),r={...e,content:e.content||"",kind:e.kind||He,created_at:e.created_at||Math.floor(n/1e3),tags:e.tags||[],pubkey:e.pubkey||tl};r.tags.some(([u])=>u==="ms")||r.tags.push(["ms",String(n)]),r.id=$e(r);const[i,s]=this.ratchetEncrypt(JSON.stringify(r)),o=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNextNostrPublicKey),c=q.encrypt(JSON.stringify(i),o);return{event:ee({content:s,kind:He,tags:[["header",c]],created_at:Math.floor(n/1e3)},this.state.ourCurrentNostrKey.privateKey),innerEvent:r}}onEvent(e){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,e),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var e,n,r;(e=this.nostrUnsubscribe)==null||e.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this),(r=this.skippedSubscription)==null||r.call(this),this.internalSubscriptions.clear()}ratchetEncrypt(e){const[n,r]=ze(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,previousChainLength:this.state.previousSendingChainMessageCount},q.encrypt(e,r)]}ratchetDecrypt(e,n,r){const i=this.trySkippedMessageKeys(e,n,r);if(i)return i;this.skipMessageKeys(e.number,r);const[s,o]=ze(this.state.receivingChainKey,new Uint8Array([1]),2);return this.state.receivingChainKey=s,this.state.receivingChainMessageNumber++,q.decrypt(n,o)}ratchetStep(){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0;const e=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[n,r]=ze(this.state.rootKey,e,2);this.state.receivingChainKey=r,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const i=_e();this.state.ourNextNostrKey={publicKey:fe(i),privateKey:i};const s=q.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNextNostrPublicKey),[o,c]=ze(n,s,2);this.state.rootKey=o,this.state.sendingChainKey=c}skipMessageKeys(e,n){if(!(e<=this.state.receivingChainMessageNumber)){if(e>this.state.receivingChainMessageNumber+el)throw new Error("Too many skipped messages");if(!this.state.skippedKeys[n]){if(this.state.skippedKeys[n]={headerKeys:[],messageKeys:{}},this.state.ourCurrentNostrKey){const i=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(i)||this.state.skippedKeys[n].headerKeys.push(i)}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,n);this.state.skippedKeys[n].headerKeys.includes(r)||this.state.skippedKeys[n].headerKeys.push(r)}for(;this.state.receivingChainMessageNumber<e;){const[r,i]=ze(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r,this.state.skippedKeys[n].messageKeys[this.state.receivingChainMessageNumber]=i,this.state.receivingChainMessageNumber++}}}trySkippedMessageKeys(e,n,r){const i=this.state.skippedKeys[r];if(!i)return null;const s=i.messageKeys[e.number];return s?(delete i.messageKeys[e.number],Object.keys(i.messageKeys).length===0&&delete this.state.skippedKeys[r],q.decrypt(n,s)):null}decryptHeader(e){const n=e.tags[0][1];if(this.state.ourCurrentNostrKey){const s=q.getConversationKey(this.state.ourCurrentNostrKey.privateKey,e.pubkey);try{return[JSON.parse(q.decrypt(n,s)),!1,!1]}catch{}}const r=q.getConversationKey(this.state.ourNextNostrKey.privateKey,e.pubkey);try{return[JSON.parse(q.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedKeys[e.pubkey];if(i!=null&&i.headerKeys)for(const s of i.headerKeys)try{return[JSON.parse(q.decrypt(n,s)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(e){var i,s;const n=Wi(this.state);let r=!1;try{const[o,c,a]=this.decryptHeader(e);if(!a&&this.state.theirNextNostrPublicKey!==o.nextPublicKey&&(this.state.theirCurrentNostrPublicKey=this.state.theirNextNostrPublicKey,this.state.theirNextNostrPublicKey=o.nextPublicKey,r=!0),!a)c&&(this.skipMessageKeys(o.previousChainLength,e.pubkey),this.ratchetStep());else if(!((i=this.state.skippedKeys[e.pubkey])!=null&&i.messageKeys[o.number]))return;const u=this.ratchetDecrypt(o,e.content,e.pubkey),h=JSON.parse(u);if(!Kt(h)){this.state=n;return}if(h.id!==$e(h)){this.state=n;return}r&&((s=this.nostrUnsubscribe)==null||s.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[He]},l=>this.handleNostrEvent(l))),this.internalSubscriptions.forEach(l=>l(h,e))}catch(o){if(this.state=n,o instanceof Error&&(o.message.includes("Failed to decrypt header")||o.message==="invalid MAC"))return;throw o}}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNextNostrPublicKey],kinds:[He]},n=>this.handleNostrEvent(n)),this.state.theirCurrentNostrPublicKey&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:[this.state.theirCurrentNostrPublicKey],kinds:[He]},n=>this.handleNostrEvent(n)));const e=Object.keys(this.state.skippedKeys);e.length&&(this.skippedSubscription=this.nostrSubscribe({authors:e,kinds:[He]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function Bt(t,e){const n=Oe.getSharedSecret(t,"02"+e).subarray(1,33);return wn(le,n,"nip44-v2")}function Fn(){const t=_e();return{publicKey:fe(t),privateKey:t}}function Xi(){return H(_e())}function nl(){return H(_e()).slice(0,16)}const rl=2880*60,Yi=()=>Math.round(Date.now()/1e3),il=()=>Math.round(Yi()-Math.random()*rl);async function Qi(t){const{inviteeSessionPublicKey:e,inviteePublicKey:n,inviteePrivateKey:r,inviterPublicKey:i,inviterEphemeralPublicKey:s,sharedSecret:o,ownerPublicKey:c,encrypt:a}=t,u=z(o),h=a??(async(m,K)=>{if(!r)throw new Error("inviteePrivateKey is required when encrypt function is not provided");return q.encrypt(m,Bt(r,K))}),l=JSON.stringify({sessionKey:e,...c&&{ownerPublicKey:c}}),y=await h(l,i),p={pubkey:n,content:q.encrypt(y,u),created_at:Yi()},g=_e(),d=fe(g),f=JSON.stringify(p),w={kind:zn,pubkey:d,content:q.encrypt(f,Bt(g,s)),created_at:il(),tags:[["p",s]]};return{innerEvent:p,envelope:w,randomSenderPublicKey:d,randomSenderPrivateKey:g}}async function jn(t){const{envelopeContent:e,envelopeSenderPubkey:n,inviterEphemeralPrivateKey:r,inviterPrivateKey:i,sharedSecret:s,decrypt:o}=t,c=z(s),a=q.decrypt(e,Bt(r,n)),u=JSON.parse(a),h=u.pubkey,l=q.decrypt(u.content,c),p=await(o??(async(f,w)=>{if(!i)throw new Error("inviterPrivateKey is required when decrypt function is not provided");return q.decrypt(f,Bt(i,w))}))(l,h);let g,d;try{const f=JSON.parse(p);g=f.sessionKey,d=f.ownerPublicKey}catch{g=p}return{inviteeIdentity:h,inviteeSessionPublicKey:g,ownerPublicKey:d}}function Tt(t){const{nostrSubscribe:e,theirPublicKey:n,ourSessionPrivateKey:r,sharedSecret:i,isSender:s,name:o}=t,c=z(i);return lt.init(e,n,r,s,c,o)}const sl=()=>Math.round(Date.now()/1e3);class ie{constructor(e,n,r,i,s,o,c=[],a=sl()){this.inviterEphemeralPublicKey=e,this.sharedSecret=n,this.inviter=r,this.inviterEphemeralPrivateKey=i,this.deviceId=s,this.maxUses=o,this.usedBy=c,this.createdAt=a}static createNew(e,n,r){if(!e)throw new Error("Inviter public key is required");const i=Fn(),s=Xi();return new ie(i.publicKey,s,e,i.privateKey,n,r)}static fromUrl(e){const r=new URL(e).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let s;try{s=JSON.parse(i)}catch(u){throw new Error("Invite data in URL hash is not valid JSON: "+u)}const{inviter:o,ephemeralKey:c,sharedSecret:a}=s;if(!o||!c||!a)throw new Error("Missing required fields (inviter, ephemeralKey, sharedSecret) in invite data.");return new ie(c,a,o)}static deserialize(e){const n=JSON.parse(e);return new ie(n.inviterEphemeralPublicKey,n.sharedSecret,n.inviter,n.inviterEphemeralPrivateKey?new Uint8Array(n.inviterEphemeralPrivateKey):void 0,n.deviceId,n.maxUses,n.usedBy,n.createdAt)}static fromEvent(e){var a,u,h,l;if(!e.sig)throw new Error("Event is not signed");if(!ut(e))throw new Error("Event signature is invalid");const{tags:n}=e;if(!n)throw new Error("Invalid invite event: missing tags");const r=(a=n.find(([y])=>y==="ephemeralKey"))==null?void 0:a[1],i=(u=n.find(([y])=>y==="sharedSecret"))==null?void 0:u[1],s=e.pubkey,o=(h=n.find(([y])=>y==="d"))==null?void 0:h[1],c=(l=o==null?void 0:o.split("/"))==null?void 0:l[2];if(!r||!i)throw new Error("Invalid invite event: missing session key or sharedSecret");return new ie(r,i,s,void 0,c)}static fromUser(e,n,r){const i={kinds:[Rt],authors:[e],"#l":["double-ratchet/invites"]},s=new Set;return n(i,c=>{if(c.pubkey!==e){console.error("Got invite event from wrong user",c.pubkey,"expected",e);return}if(!s.has(c.id)){s.add(c.id);try{const a=ie.fromEvent(c);r(a)}catch{}}})}serialize(){return JSON.stringify({inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,inviter:this.inviter,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey?Array.from(this.inviterEphemeralPrivateKey):void 0,deviceId:this.deviceId,maxUses:this.maxUses,usedBy:this.usedBy,createdAt:this.createdAt})}getUrl(e="https://iris.to"){const n={inviter:this.inviter,ephemeralKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret},r=new URL(e);return r.hash=encodeURIComponent(JSON.stringify(n)),r.toString()}getEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Rt,pubkey:this.inviter,content:"",created_at:this.createdAt,tags:[["ephemeralKey",this.inviterEphemeralPublicKey],["sharedSecret",this.sharedSecret],["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}getDeletionEvent(){if(!this.deviceId)throw new Error("Device ID is required");return{kind:Rt,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["d","double-ratchet/invites/"+this.deviceId],["l","double-ratchet/invites"]]}}async accept(e,n,r,i){const s=Fn(),o=this.inviter||this.inviterEphemeralPublicKey,c=Tt({nostrSubscribe:e,theirPublicKey:this.inviterEphemeralPublicKey,ourSessionPrivateKey:s.privateKey,sharedSecret:this.sharedSecret,isSender:!0}),a=typeof r=="function"?r:void 0,u=typeof r=="function"?void 0:r,h=await Qi({inviteeSessionPublicKey:s.publicKey,inviteePublicKey:n,inviteePrivateKey:u,inviterPublicKey:o,inviterEphemeralPublicKey:this.inviterEphemeralPublicKey,sharedSecret:this.sharedSecret,ownerPublicKey:i,encrypt:a});return{session:c,event:ee(h.envelope,h.randomSenderPrivateKey)}}listen(e,n,r){if(!this.inviterEphemeralPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[zn],"#p":[this.inviterEphemeralPublicKey]};return n(i,async s=>{try{if(this.maxUses&&this.usedBy.length>=this.maxUses)return;const o=typeof e=="function"?e:void 0,c=typeof e=="function"?void 0:e,a=await jn({envelopeContent:s.content,envelopeSenderPubkey:s.pubkey,inviterEphemeralPrivateKey:this.inviterEphemeralPrivateKey,inviterPrivateKey:c,sharedSecret:this.sharedSecret,decrypt:o});this.usedBy.push(a.inviteeIdentity);const u=Tt({nostrSubscribe:n,theirPublicKey:a.inviteeSessionPublicKey,ourSessionPrivateKey:this.inviterEphemeralPrivateKey,sharedSecret:this.sharedSecret,isSender:!1,name:s.id});r(u,a.inviteeIdentity)}catch{}})}}const es=()=>Math.round(Date.now()/1e3),ol=t=>t.length>=3&&t[0]==="device"&&typeof t[1]=="string"&&typeof t[2]=="string";class X{constructor(e=[]){E(this,"devices",new Map);e.forEach(n=>this.devices.set(n.identityPubkey,n))}createDeviceEntry(e){return{identityPubkey:e,createdAt:es()}}addDevice(e){this.devices.has(e.identityPubkey)||this.devices.set(e.identityPubkey,e)}removeDevice(e){this.devices.delete(e)}getDevice(e){return this.devices.get(e)}getAllDevices(){return Array.from(this.devices.values())}getEvent(){const e=this.getAllDevices().map(n=>["device",n.identityPubkey,String(n.createdAt)]);return{kind:Ve,pubkey:"",content:"",created_at:es(),tags:[["d","double-ratchet/app-keys"],["version","1"],...e]}}static fromEvent(e){if(!e.sig)throw new Error("Event is not signed");if(!ut(e))throw new Error("Event signature is invalid");const n=e.tags.filter(ol).map(([,r,i])=>({identityPubkey:r,createdAt:parseInt(i,10)||e.created_at}));return new X(n)}serialize(){return JSON.stringify({devices:this.getAllDevices()})}static deserialize(e){const n=JSON.parse(e);return new X(n.devices)}merge(e){const n=[...this.devices.values(),...e.devices.values()].reduce((r,i)=>{const s=r.get(i.identityPubkey);return(!s||i.createdAt<s.createdAt)&&r.set(i.identityPubkey,i),r},new Map);return new X(Array.from(n.values()))}static fromUser(e,n,r){return n({kinds:[Ve],authors:[e],"#d":["double-ratchet/app-keys"]},i=>{if(i.pubkey===e)try{const s=X.fromEvent(i);r(s)}catch{}})}static waitFor(e,n,r=500){return new Promise(i=>{let s=null;setTimeout(()=>{o(),i((s==null?void 0:s.list)??null)},r);const o=n({kinds:[Ve],authors:[e],"#d":["double-ratchet/app-keys"]},c=>{if(c.pubkey===e)try{const a=X.fromEvent(c);(!s||c.created_at>=s.createdAt)&&(s={list:a,createdAt:c.created_at})}catch{}})})}}class Lt{constructor(){E(this,"store",new Map)}async get(e){return this.store.get(e)}async put(e,n){this.store.set(e,n)}async del(e){this.store.delete(e)}async list(e=""){const n=[],r=Array.from(this.store.keys());for(const i of r)i.startsWith(e)&&n.push(i);return n}}class al{constructor(e="session_"){E(this,"keyPrefix");this.keyPrefix=e}getFullKey(e){return`${this.keyPrefix}${e}`}async get(e){try{const n=localStorage.getItem(this.getFullKey(e));return n?JSON.parse(n):void 0}catch{return}}async put(e,n){try{localStorage.setItem(this.getFullKey(e),JSON.stringify(n))}catch(r){throw console.error(`Failed to put key ${e} to localStorage:`,r),r}}async del(e){try{localStorage.removeItem(this.getFullKey(e))}catch{}}async list(e=""){const n=[],r=this.getFullKey(e);try{for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);s&&s.startsWith(r)&&n.push(s.substring(this.keyPrefix.length))}}catch{}return n}}const qe=class qe{constructor(e,n,r,i,s,o,c,a){E(this,"storageVersion","1");E(this,"versionPrefix");E(this,"deviceId");E(this,"storage");E(this,"nostrSubscribe");E(this,"nostrPublish");E(this,"identityKey");E(this,"ourPublicKey");E(this,"ownerPublicKey");E(this,"inviteKeys");E(this,"userRecords",new Map);E(this,"messageHistory",new Map);E(this,"delegateToOwner",new Map);E(this,"processedInviteResponses",new Set);E(this,"ourInviteResponseSubscription",null);E(this,"inviteSubscriptions",new Map);E(this,"sessionSubscriptions",new Map);E(this,"internalSubscriptions",new Set);E(this,"initialized",!1);this.userRecords=new Map,this.nostrSubscribe=i,this.nostrPublish=s,this.ourPublicKey=e,this.identityKey=n,this.deviceId=r,this.ownerPublicKey=o,this.inviteKeys=c,this.storage=a||new Lt,this.versionPrefix=`v${this.storageVersion}`}async init(){if(this.initialized)return;this.initialized=!0,await this.runMigrations().catch(()=>{}),await this.loadAllUserRecords().catch(()=>{});const e=this.getOrCreateUserRecord(this.ownerPublicKey);this.upsertDeviceRecord(e,this.deviceId),this.startInviteResponseListener(),this.setupUser(this.ownerPublicKey)}startInviteResponseListener(){const{publicKey:e,privateKey:n}=this.inviteKeys.ephemeralKeypair,r=this.inviteKeys.sharedSecret;this.ourInviteResponseSubscription=this.nostrSubscribe({kinds:[1059],"#p":[e]},async i=>{var s;if(!this.processedInviteResponses.has(i.id)){this.processedInviteResponses.add(i.id);try{const o=await jn({envelopeContent:i.content,envelopeSenderPubkey:i.pubkey,inviterEphemeralPrivateKey:n,inviterPrivateKey:this.identityKey instanceof Uint8Array?this.identityKey:void 0,sharedSecret:r,decrypt:this.identityKey instanceof Uint8Array?void 0:this.identityKey.decrypt});if(o.inviteeIdentity===this.deviceId)return;const c=o.ownerPublicKey||this.resolveToOwner(o.inviteeIdentity),a=await this.fetchAppKeys(c);if(a){if(!a.getAllDevices().some(g=>g.identityPubkey===o.inviteeIdentity))return;this.updateDelegateMapping(c,a)}else{const g=(((s=this.userRecords.get(c))==null?void 0:s.knownDeviceIdentities)||[]).includes(o.inviteeIdentity),d=o.inviteeIdentity===c;if(!g&&!d)return}const u=c,h=this.getOrCreateUserRecord(u),l=this.upsertDeviceRecord(h,o.inviteeIdentity),y=Tt({nostrSubscribe:this.nostrSubscribe,theirPublicKey:o.inviteeSessionPublicKey,ourSessionPrivateKey:n,sharedSecret:r,isSender:!1,name:i.id});this.attachSessionSubscription(u,l,y,!0),this.storeUserRecord(u).catch(()=>{})}catch{}}})}fetchAppKeys(e,n=2e3){return new Promise(r=>{let i=null,s=!1;const o=()=>{s||(s=!0,a(),r((i==null?void 0:i.appKeys)??null))},c=setTimeout(o,n),a=this.nostrSubscribe({kinds:[Ve],authors:[e],"#d":["double-ratchet/app-keys"]},u=>{if(!s)try{const h=X.fromEvent(u);(!i||u.created_at>=i.created_at)&&(i={created_at:u.created_at,appKeys:h}),clearTimeout(c),setTimeout(o,100)}catch{}})})}getOrCreateUserRecord(e){let n=this.userRecords.get(e);return n||(n={publicKey:e,devices:new Map,knownDeviceIdentities:[]},this.userRecords.set(e,n)),n}upsertDeviceRecord(e,n){if(!n)throw new Error("Device record must include a deviceId");const r=e.devices.get(n);if(r)return r;const i={deviceId:n,inactiveSessions:[],createdAt:Date.now()};return e.devices.set(n,i),i}sessionKey(e,n,r){return`${this.sessionKeyPrefix(e)}${n}/${r}`}sessionKeyPrefix(e){return`${this.versionPrefix}/session/${e}/`}userRecordKey(e){return`${this.userRecordKeyPrefix()}${e}`}userRecordKeyPrefix(){return`${this.versionPrefix}/user/`}versionKey(){return"storage-version"}resolveToOwner(e){return this.delegateToOwner.get(e)||e}updateDelegateMapping(e,n){const r=this.getOrCreateUserRecord(e),i=n.getAllDevices().map(s=>s.identityPubkey).filter(Boolean);r.knownDeviceIdentities=i;for(const s of i)this.delegateToOwner.set(s,e);this.storeUserRecord(e).catch(()=>{})}subscribeToUserAppKeys(e,n){return this.nostrSubscribe({kinds:[Ve],authors:[e],"#d":["double-ratchet/app-keys"]},r=>{try{const i=X.fromEvent(r);this.updateDelegateMapping(e,i),n(i)}catch{}})}attachSessionSubscription(e,n,r,i=!1){const s=this.sessionKey(e,n.deviceId,r.name);if(this.sessionSubscriptions.has(s))return;const o=n,c=u=>{const h=o.activeSession;if(!(h===u||(h==null?void 0:h.name)===u.name)&&(o.inactiveSessions=o.inactiveSessions.filter(l=>l!==u&&l.name!==u.name),h&&o.inactiveSessions.unshift(h),o.activeSession=u,o.inactiveSessions.length>qe.MAX_INACTIVE_SESSIONS)){const l=o.inactiveSessions.splice(qe.MAX_INACTIVE_SESSIONS);for(const y of l)this.removeSessionSubscription(e,o.deviceId,y.name)}};if(i){if(!o.inactiveSessions.some(h=>h===r||h.name===r.name)&&(o.inactiveSessions.unshift(r),o.inactiveSessions.length>qe.MAX_INACTIVE_SESSIONS)){const h=o.inactiveSessions.splice(qe.MAX_INACTIVE_SESSIONS);for(const l of h)this.removeSessionSubscription(e,o.deviceId,l.name)}}else c(r);const a=r.onEvent(u=>{for(const h of this.internalSubscriptions)h(u,e);c(r),this.storeUserRecord(e).catch(()=>{})});this.storeUserRecord(e).catch(()=>{}),this.sessionSubscriptions.set(s,a)}attachAppKeysSubscription(e,n){const r=`appkeys:${e}`;if(this.inviteSubscriptions.has(r))return;const i=this.subscribeToUserAppKeys(e,async s=>{n&&await n(s)});this.inviteSubscriptions.set(r,i)}setupUser(e){const n=this.getOrCreateUserRecord(e),r=new Set,i=new Set,s=async(c,a)=>{const u=n.devices.get(c.identityPubkey);if(u!=null&&u.activeSession)return;const h=this.upsertDeviceRecord(n,c.identityPubkey),l=this.identityKey instanceof Uint8Array?this.identityKey:this.identityKey.encrypt,{session:y,event:p}=await a.accept(this.nostrSubscribe,this.ourPublicKey,l,this.ownerPublicKey);return this.nostrPublish(p).then(()=>{this.attachSessionSubscription(e,h,y)}).then(()=>this.sendMessageHistory(e,c.identityPubkey)).catch(()=>{})},o=c=>{const a=c.identityPubkey;if(r.has(a))return;r.add(a);const u=n.devices.get(c.identityPubkey);if(u!=null&&u.activeSession)return;const h=`invite:${c.identityPubkey}`;if(this.inviteSubscriptions.has(h))return;const l=ie.fromUser(c.identityPubkey,this.nostrSubscribe,async y=>{if(y.deviceId!==c.identityPubkey)return;const p=n.devices.get(c.identityPubkey);if(!(p!=null&&p.activeSession)&&!i.has(c.identityPubkey)){i.add(c.identityPubkey);try{await s(c,y)}finally{i.delete(c.identityPubkey)}}});this.inviteSubscriptions.set(h,l)};this.attachAppKeysSubscription(e,async c=>{const a=c.getAllDevices(),u=new Set(a.map(l=>l.identityPubkey)),h=this.userRecords.get(e);if(h){for(const[l]of h.devices)if(!u.has(l)){r.delete(l);const y=`invite:${l}`,p=this.inviteSubscriptions.get(y);p&&(p(),this.inviteSubscriptions.delete(y)),await this.cleanupDevice(e,l)}}for(const l of a)o(l)})}onEvent(e){return this.internalSubscriptions.add(e),()=>{this.internalSubscriptions.delete(e)}}getDeviceId(){return this.deviceId}getUserRecords(){return this.userRecords}close(){var e;for(const n of this.inviteSubscriptions.values())n();for(const n of this.sessionSubscriptions.values())n();(e=this.ourInviteResponseSubscription)==null||e.call(this)}deactivateCurrentSessions(e){const n=this.userRecords.get(e);if(n){for(const r of n.devices.values())r.activeSession&&(r.inactiveSessions.push(r.activeSession),r.activeSession=void 0);this.storeUserRecord(e).catch(()=>{})}}async deleteUser(e){await this.init();const n=this.userRecords.get(e);if(n){for(const s of n.devices.values()){s.activeSession&&this.removeSessionSubscription(e,s.deviceId,s.activeSession.name);for(const o of s.inactiveSessions)this.removeSessionSubscription(e,s.deviceId,o.name)}this.userRecords.delete(e)}const r=`appkeys:${e}`,i=this.inviteSubscriptions.get(r);i&&(i(),this.inviteSubscriptions.delete(r)),this.messageHistory.delete(e),await Promise.allSettled([this.deleteUserSessionsFromStorage(e),this.storage.del(this.userRecordKey(e))])}removeSessionSubscription(e,n,r){const i=this.sessionKey(e,n,r),s=this.sessionSubscriptions.get(i);s&&(s(),this.sessionSubscriptions.delete(i))}async deleteUserSessionsFromStorage(e){const n=this.sessionKeyPrefix(e),r=await this.storage.list(n);await Promise.all(r.map(i=>this.storage.del(i)))}async sendMessageHistory(e,n){const r=this.messageHistory.get(e)||[],i=this.userRecords.get(e);if(!i)return;const s=i.devices.get(n);if(s)for(const o of r){const{activeSession:c}=s;if(!c)continue;const{event:a}=c.sendEvent(o);await this.nostrPublish(a),await this.storeUserRecord(e)}}async sendEvent(e,n){await this.init();const r=n,i=new Set([e,this.ownerPublicKey]);for(const l of i){const y=this.messageHistory.get(l)||[];this.messageHistory.set(l,[...y,r])}const s=this.getOrCreateUserRecord(e),o=this.getOrCreateUserRecord(this.ownerPublicKey);this.setupUser(e),this.setupUser(this.ownerPublicKey);const c=Array.from(s.devices.values()),a=Array.from(o.devices.values()),u=new Map;for(const l of[...c,...a])l.deviceId!==this.deviceId&&u.set(l.deviceId,l);const h=Array.from(u.values());return await Promise.allSettled(h.map(async l=>{const{activeSession:y}=l;if(!y)return;const{event:p}=y.sendEvent(n);await this.nostrPublish(p).catch(()=>{})})),await this.storeUserRecord(e),this.ownerPublicKey!==e&&await this.storeUserRecord(this.ownerPublicKey),r}async sendMessage(e,n,r={}){const{kind:i=qn,tags:s=[]}=r,o=Date.now(),c=this.buildMessageTags(e,s),a={content:n,kind:i,created_at:Math.floor(o/1e3),tags:c,pubkey:this.ourPublicKey,id:""};return a.tags.some(([u])=>u==="ms")||a.tags.push(["ms",String(o)]),a.id=$e(a),this.sendEvent(e,a).catch(()=>{}),a}async cleanupDevice(e,n){const r=this.userRecords.get(e);if(!r)return;const i=r.devices.get(n);if(i){i.activeSession&&this.removeSessionSubscription(e,n,i.activeSession.name);for(const s of i.inactiveSessions)this.removeSessionSubscription(e,n,s.name);r.devices.delete(n),await this.storeUserRecord(e).catch(()=>{})}}buildMessageTags(e,n){return n.some(s=>s[0]==="p"&&s[1]===e)?[...n]:[["p",e],...n]}storeUserRecord(e){const n=this.userRecords.get(e),r=Array.from((n==null?void 0:n.devices.entries())||[]),i=o=>({name:o.name,state:ji(o.state)}),s={publicKey:e,devices:r.map(([,o])=>({deviceId:o.deviceId,activeSession:o.activeSession?i(o.activeSession):null,inactiveSessions:o.inactiveSessions.map(i),createdAt:o.createdAt})),knownDeviceIdentities:(n==null?void 0:n.knownDeviceIdentities)||[]};return this.storage.put(this.userRecordKey(e),s)}loadUserRecord(e){return this.storage.get(this.userRecordKey(e)).then(n=>{if(!n)return;const r=new Map,i=o=>{const c=new lt(this.nostrSubscribe,Gi(o.state));return c.name=o.name,this.processedInviteResponses.add(o.name),c};for(const o of n.devices){const{deviceId:c,activeSession:a,inactiveSessions:u,createdAt:h}=o;try{const l=a?i(a):void 0,y=u.map(i);r.set(c,{deviceId:c,activeSession:l,inactiveSessions:y,createdAt:h})}catch{}}const s=n.knownDeviceIdentities||[];this.userRecords.set(e,{publicKey:n.publicKey,devices:r,knownDeviceIdentities:s});for(const o of s)this.delegateToOwner.set(o,e);for(const o of r.values()){const{deviceId:c,activeSession:a,inactiveSessions:u}=o;if(c){for(const h of u.reverse())this.attachSessionSubscription(e,o,h,!0);a&&this.attachSessionSubscription(e,o,a)}}}).catch(()=>{})}loadAllUserRecords(){const e=this.userRecordKeyPrefix();return this.storage.list(e).then(n=>Promise.all(n.map(r=>{const i=r.slice(e.length);return this.loadUserRecord(i)})))}async runMigrations(){let e=await this.storage.get(this.versionKey());if(!e){const r=await this.storage.list("invite/");await Promise.all(r.map(o=>this.storage.del(o)));const i="user/",s=await this.storage.list(i);await Promise.all(s.map(async o=>{try{const c=o.slice(i.length),a=await this.storage.get(o);if(a){const u=this.userRecordKey(c),h={publicKey:a.publicKey,devices:a.devices.map(l=>({deviceId:l.deviceId,activeSession:null,createdAt:l.createdAt,inactiveSessions:[]}))};await this.storage.put(u,h),await this.storage.del(o)}}catch{}})),e="1",await this.storage.put(this.versionKey(),e)}}};E(qe,"MAX_INACTIVE_SESSIONS",10);let Mt=qe;class ts{constructor(e){E(this,"nostrPublish");E(this,"storage");E(this,"appKeys",null);E(this,"initialized",!1);E(this,"storageVersion","3");this.nostrPublish=e.nostrPublish,this.storage=e.storage||new Lt}get versionPrefix(){return`v${this.storageVersion}`}async init(){this.initialized||(this.initialized=!0,this.appKeys=await this.loadAppKeys(),this.appKeys||(this.appKeys=new X))}getAppKeys(){return this.appKeys}getOwnDevices(){var e;return((e=this.appKeys)==null?void 0:e.getAllDevices())||[]}addDevice(e){this.appKeys||(this.appKeys=new X);const n={identityPubkey:e.identityPubkey,createdAt:Math.floor(Date.now()/1e3)};this.appKeys.addDevice(n),this.saveAppKeys(this.appKeys).catch(()=>{})}revokeDevice(e){this.appKeys&&(this.appKeys.removeDevice(e),this.saveAppKeys(this.appKeys).catch(()=>{}))}async publish(){this.appKeys||(this.appKeys=new X);const e=this.appKeys.getEvent();await this.nostrPublish(e)}async setAppKeys(e){this.appKeys=e,await this.saveAppKeys(e)}close(){}appKeysKey(){return`${this.versionPrefix}/app-keys-manager/app-keys`}async loadAppKeys(){const e=await this.storage.get(this.appKeysKey());if(!e)return null;try{return X.deserialize(e)}catch{return null}}async saveAppKeys(e){await this.storage.put(this.appKeysKey(),e.serialize())}}class cl{constructor(e){E(this,"nostrSubscribe");E(this,"nostrPublish");E(this,"storage");E(this,"devicePublicKey","");E(this,"devicePrivateKey",new Uint8Array);E(this,"invite",null);E(this,"ownerPubkeyFromActivation");E(this,"initialized",!1);E(this,"subscriptions",[]);E(this,"storageVersion","1");this.nostrSubscribe=e.nostrSubscribe,this.nostrPublish=e.nostrPublish,this.storage=e.storage||new Lt}get versionPrefix(){return`v${this.storageVersion}`}async init(){if(this.initialized)return;this.initialized=!0;const e=await this.storage.get(this.identityPublicKeyKey()),n=await this.storage.get(this.identityPrivateKeyKey());e&&n?(this.devicePublicKey=e,this.devicePrivateKey=new Uint8Array(n)):(this.devicePrivateKey=_e(),this.devicePublicKey=fe(this.devicePrivateKey),await this.storage.put(this.identityPublicKeyKey(),this.devicePublicKey),await this.storage.put(this.identityPrivateKeyKey(),Array.from(this.devicePrivateKey)));const r=await this.storage.get(this.ownerPubkeyKey());r&&(this.ownerPubkeyFromActivation=r);const i=await this.loadInvite();this.invite=i||ie.createNew(this.devicePublicKey,this.devicePublicKey),await this.saveInvite(this.invite);const s=this.invite.getEvent(),o=ee(s,this.devicePrivateKey);await this.nostrPublish(o).catch(()=>{})}getRegistrationPayload(){return{identityPubkey:this.devicePublicKey}}getIdentityPublicKey(){return this.devicePublicKey}getIdentityKey(){return this.devicePrivateKey}getInvite(){return this.invite}getOwnerPublicKey(){return this.ownerPubkeyFromActivation||null}async rotateInvite(){await this.init(),this.invite=ie.createNew(this.devicePublicKey,this.devicePublicKey),await this.saveInvite(this.invite);const e=this.invite.getEvent(),n=ee(e,this.devicePrivateKey);await this.nostrPublish(n)}async activate(e){this.ownerPubkeyFromActivation=e,await this.storage.put(this.ownerPubkeyKey(),e)}async waitForActivation(e=6e4){return this.ownerPubkeyFromActivation?this.ownerPubkeyFromActivation:new Promise((n,r)=>{const i=setTimeout(()=>{s(),r(new Error("Activation timeout"))},e),s=this.nostrSubscribe({kinds:[Ve],"#d":["double-ratchet/app-keys"]},async o=>{try{X.fromEvent(o).getDevice(this.devicePublicKey)&&(clearTimeout(i),s(),this.ownerPubkeyFromActivation=o.pubkey,await this.storage.put(this.ownerPubkeyKey(),o.pubkey),n(o.pubkey))}catch{}});this.subscriptions.push(s)})}async isRevoked(e={}){const{timeoutMs:n=2e3,retries:r=2}=e,i=this.getOwnerPublicKey();if(!i)return!1;for(let s=0;s<=r;s++){const o=await X.waitFor(i,this.nostrSubscribe,n);if(o)return!o.getDevice(this.devicePublicKey)}return!0}close(){for(const e of this.subscriptions)e();this.subscriptions=[]}createSessionManager(e){if(!this.initialized)throw new Error("DelegateManager must be initialized before creating SessionManager");const n=this.getOwnerPublicKey();if(!n)throw new Error("Owner public key required for SessionManager - device must be activated first");if(!this.invite||!this.invite.inviterEphemeralPrivateKey)throw new Error("Invite with ephemeral keys required for SessionManager");const r={publicKey:this.invite.inviterEphemeralPublicKey,privateKey:this.invite.inviterEphemeralPrivateKey},i=this.invite.sharedSecret;return new Mt(this.devicePublicKey,this.devicePrivateKey,this.devicePublicKey,this.nostrSubscribe,this.nostrPublish,n,{ephemeralKeypair:r,sharedSecret:i},e||this.storage)}ownerPubkeyKey(){return`${this.versionPrefix}/device-manager/owner-pubkey`}inviteKey(){return`${this.versionPrefix}/device-manager/invite`}async loadInvite(){const e=await this.storage.get(this.inviteKey());if(!e)return null;try{return ie.deserialize(e)}catch{return null}}async saveInvite(e){await this.storage.put(this.inviteKey(),e.serialize())}identityPublicKeyKey(){return`${this.versionPrefix}/device-manager/identity-public-key`}identityPrivateKeyKey(){return`${this.versionPrefix}/device-manager/identity-private-key`}}I.APP_KEYS_EVENT_KIND=Ve,I.AppKeys=X,I.AppKeysManager=ts,I.ApplicationManager=ts,I.CHAT_MESSAGE_KIND=qn,I.DelegateManager=cl,I.INVITE_EVENT_KIND=Rt,I.INVITE_RESPONSE_KIND=zn,I.InMemoryStorageAdapter=Lt,I.Invite=ie,I.LocalStorageAdapter=al,I.MESSAGE_EVENT_KIND=He,I.REACTION_KIND=zi,I.RECEIPT_KIND=qi,I.Session=lt,I.SessionManager=Mt,I.TYPING_KIND=Fi,I.createEventStream=Xu,I.createReactionPayload=Ji,I.createSessionFromAccept=Tt,I.decryptInviteResponse=jn,I.deepCopyState=Wi,I.deserializeSessionState=Gi,I.encryptInviteResponse=Qi,I.generateDeviceId=nl,I.generateEphemeralKeypair=Fn,I.generateSharedSecret=Xi,I.getMillisecondTimestamp=Yu,I.isReaction=Qu,I.kdf=ze,I.parseReaction=Zi,I.serializeSessionState=ji,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})}));
|