PageSourceSearch

https://iris.to/assets/relay-worker-CBlRc7br.js

js iris.to collected 2026-10-02 14:44:36 UTC 466,455 bytes, 3 lines download raw bytes

1function Va(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zn(t,e=""){if(!Number.isSafeInteger(t)||t<0){const n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function Qe(t,e,n=""){const r=Va(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,c=s?` of length ${e}`:"",u=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+c+", got "+u)}return t}function Ps(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");zn(t.outputLen),zn(t.blockLen)}function vs(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 Xd(t,e){Qe(t,void 0,"digestInto() output");const n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function vi(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function To(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function sn(t,e){return t<<32-e|t>>>e}const Fl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jd=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Je(t){if(Qe(t),Fl)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Jd[t[n]];return e}const yn={_0:48,_9:57,A:65,F:70,a:97,f:102};function mu(t){if(t>=yn._0&&t<=yn._9)return t-yn._0;if(t>=yn.A&&t<=yn.F)return t-(yn.A-10);if(t>=yn.a&&t<=yn.f)return t-(yn.a-10)}function nt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Fl)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=mu(t.charCodeAt(s)),c=mu(t.charCodeAt(s+1));if(o===void 0||c===void 0){const u=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+u+'" at index '+s)}r[i]=o*16+c}return r}function St(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Qe(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}function Qd(t,e={}){const n=(i,s)=>t(s).update(i).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=i=>t(i),Object.assign(n,e),Object.freeze(n)}function zr(t=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}const ep=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function tp(t,e,n){return t&e^~t&n}function np(t,e,n){return t&e^t&n^e&n}class rp{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,i){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=To(this.buffer)}update(e){vs(this),Qe(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const u=To(e);for(;i<=s-o;o+=i)this.process(u,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){vs(this),Xd(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,vi(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)n[d]=0;r.setBigUint64(i-8,BigInt(this.length*8),s),this.process(r,0);const c=To(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const f=u/4,p=this.get();if(f>p.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)c.setUint32(4*d,p[d],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(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.destroyed=o,e.finished=s,e.length=i,e.pos=c,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}
1const On=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ip=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dn=new Uint32Array(64);class sp extends rp{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:c,H:u}=this;return[e,n,r,i,s,o,c,u]}set(e,n,r,i,s,o,c,u){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=u|0}process(e,n){for(let d=0;d<16;d++,n+=4)Dn[d]=e.getUint32(n,!1);for(let d=16;d<64;d++){const g=Dn[d-15],w=Dn[d-2],x=sn(g,7)^sn(g,18)^g>>>3,A=sn(w,17)^sn(w,19)^w>>>10;Dn[d]=A+Dn[d-7]+x+Dn[d-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:u,G:f,H:p}=this;for(let d=0;d<64;d++){const g=sn(c,6)^sn(c,11)^sn(c,25),w=p+g+tp(c,u,f)+ip[d]+Dn[d]|0,A=(sn(r,2)^sn(r,13)^sn(r,22))+np(r,i,s)|0;p=f,f=u,u=c,c=o+w|0,o=s,s=i,i=r,r=w+A|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,u=u+this.F|0,f=f+this.G|0,p=p+this.H|0,this.set(r,i,s,o,c,u,f,p)}roundClean(){vi(Dn)}destroy(){this.set(0,0,0,0,0,0,0,0),vi(this.buffer)}}class op extends sp{A=On[0]|0;B=On[1]|0;C=On[2]|0;D=On[3]|0;E=On[4]|0;F=On[5]|0;G=On[6]|0;H=On[7]|0;constructor(){super(32)}}const Vt=Qd(()=>new op,ep(1));const Ga=BigInt(0),ua=BigInt(1);function bs(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Ul(t){if(typeof t=="bigint"){if(!fs(t))throw new Error("positive bigint expected, got "+t)}else zn(t);return t}function Zi(t){const e=Ul(t).toString(16);return e.length&1?"0"+e:e}function $l(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ga:BigInt("0x"+t)}function Si(t){return $l(Je(t))}function Kl(t){return $l(Je(ap(Qe(t)).reverse()))}function Ya(t,e){zn(e),t=Ul(t);const n=nt(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function zl(t,e){return Ya(t,e).reverse()}function ap(t){return Uint8Array.from(t)}function cp(t){return Uint8Array.from(t,(e,n)=>{const r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}const fs=t=>typeof t=="bigint"&&Ga<=t;function up(t,e,n){return fs(t)&&fs(e)&&fs(n)&&e<=t&&t<n}function lp(t,e,n,r){if(!up(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function fp(t){let e;for(e=0;t>Ga;t>>=ua,e+=1);return e}const Za=t=>(ua<<BigInt(t))-ua;function hp(t,e,n){if(zn(t,"hashLen"),zn(e,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");const r=I=>new Uint8Array(I),i=Uint8Array.of(),s=Uint8Array.of(0),o=Uint8Array.of(1),c=1e3;let u=r(t),f=r(t),p=0;const d=()=>{u.fill(1),f.fill(0),p=0},g=(...I)=>n(f,St(u,...I)),w=(I=i)=>{f=g(s,I),u=g(),I.length!==0&&(f=g(o,I),u=g())},x=()=>{if(p++>=c)throw new Error("drbg: tried max amount of iterations");let I=0;const T=[];for(;I<e;){u=g();const te=u.slice();T.push(te),I+=u.length}return St(...T)};return(I,T)=>{d(),w(I);let te;for(;!(te=T(x()));)w();return d(),te}}function Xa(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,o,c){const u=t[s];if(c&&u===void 0)return;const f=typeof u;if(f!==o||u===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${f}`)}const i=(s,o)=>Object.entries(s).forEach(([c,u])=>r(c,u,o));i(e,!1),i(n,!0)}function wu(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const It=BigInt(0),At=BigInt(1),ar=BigInt(2),Hl=BigInt(3),ql=BigInt(4),Wl=BigInt(5),dp=BigInt(7),jl=BigInt(8),pp=BigInt(9),Vl=BigInt(16);function jt(t,e){const n=t%e;return n>=It?n:e+n}function Nt(t,e,n){let r=t;for(;e-- >It;)r*=r,r%=n;return r}function vu(t,e){if(t===It)throw new Error("invert: expected non-zero number");if(e<=It)throw new Error("invert: expected positive modulus, got "+e);let n=jt(t,e),r=e,i=It,s=At;for(;n!==It;){const c=r/n,u=r%n,f=i-s*c;r=n,n=u,i=s,s=f}if(r!==At)throw new Error("invert: does not exist");return jt(i,e)}function Ja(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Gl(t,e){const n=(t.ORDER+At)/ql,r=t.pow(e,n);return Ja(t,r,e),r}function yp(t,e){const n=(t.ORDER-Wl)/jl,r=t.mul(e,ar),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,ar),i),c=t.mul(s,t.sub(o,t.ONE));return Ja(t,c,e),c}function gp(t){const e=Fs(t),n=Yl(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+dp)/Vl;return(c,u)=>{let f=c.pow(u,o),p=c.mul(f,r);const d=c.mul(f,i),g=c.mul(f,s),w=c.eql(c.sqr(p),u),x=c.eql(c.sqr(d),u);f=c.cmov(f,p,w),p=c.cmov(g,d,x);const A=c.eql(c.sqr(p),u),I=c.cmov(f,p,A);return Ja(c,I,u),I}}function Yl(t){if(t<Hl)throw new Error("sqrt is not defined for small field");let e=t-At,n=0;for(;e%ar===It;)e/=ar,n++;let r=ar;const i=Fs(t);for(;bu(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Gl;let s=i.pow(r,e);const o=(e+At)/ar;return function(u,f){if(u.is0(f))return f;if(bu(u,f)!==1)throw new Error("Cannot find square root");let p=n,d=u.mul(u.ONE,s),g=u.pow(f,e),w=u.pow(f,o);for(;!u.eql(g,u.ONE);){if(u.is0(g))return u.ZERO;let x=1,A=u.sqr(g);for(;!u.eql(A,u.ONE);)if(x++,A=u.sqr(A),x===p)throw new Error("Cannot find square root");const I=At<<BigInt(p-x-1),T=u.pow(d,I);p=x,d=u.sqr(T),g=u.mul(g,d),w=u.mul(w,T)}return w}}function mp(t){return t%ql===Hl?Gl:t%jl===Wl?yp:t%Vl===pp?gp(t):Yl(t)}const wp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vp(t){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=wp.reduce((r,i)=>(r[i]="function",r),e);return Xa(t,n),t}function bp(t,e,n){if(n<It)throw new Error("invalid exponent, negatives unsupported");if(n===It)return t.ONE;if(n===At)return e;let r=t.ONE,i=e;for(;n>It;)n&At&&(r=t.mul(r,i)),i=t.sqr(i),n>>=At;return r}function Zl(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,c,u)=>t.is0(c)?o:(r[u]=o,t.mul(o,c)),t.ONE),s=t.inv(i);return e.reduceRight((o,c,u)=>t.is0(c)?o:(r[u]=t.mul(o,r[u]),t.mul(o,c)),s),r}function bu(t,e){const n=(t.ORDER-At)/ar,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Ep(t,e){e!==void 0&&zn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}class xp{ORDER;BITS;BYTES;isLE;ZERO=It;ONE=At;_lengths;_sqrt;_mod;constructor(e,n={}){if(e<=It)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=n.allowedLengths?.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes)
1);const{nBitLength:i,nByteLength:s}=Ep(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return jt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return It<=e&&e<this.ORDER}is0(e){return e===It}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&At)===At}neg(e){return jt(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return jt(e*e,this.ORDER)}add(e,n){return jt(e+n,this.ORDER)}sub(e,n){return jt(e-n,this.ORDER)}mul(e,n){return jt(e*n,this.ORDER)}pow(e,n){return bp(this,e,n)}div(e,n){return jt(e*vu(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return vu(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=mp(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?zl(e,this.BYTES):Ya(e,this.BYTES)}fromBytes(e,n=!1){Qe(e);const{_lengths:r,BYTES:i,isLE:s,ORDER:o,_mod:c}=this;if(r){if(!r.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const f=new Uint8Array(i);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let u=s?Kl(e):Si(e);if(c&&(u=jt(u,o)),!n&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return Zl(this,e)}cmov(e,n,r){return r?n:e}}function Fs(t,e={}){return new xp(t,e)}function Xl(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 Jl(t){const e=Xl(t);return e+Math.ceil(e/2)}function Ql(t,e,n=!1){Qe(t);const r=t.length,i=Xl(e),s=Jl(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Kl(t):Si(t),c=jt(o,e-At)+At;return n?zl(c,i):Ya(c,i)}const Fr=BigInt(0),cr=BigInt(1);function Es(t,e){const n=e.negate();return t?n:e}function Eu(t,e){const n=Zl(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function ef(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Io(t,e){ef(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Za(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function xu(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let c=Number(t&i),u=t>>o;c>r&&(c-=s,u+=cr);const f=e*r,p=f+Math.abs(c)-1,d=c===0,g=c<0,w=e%2!==0;return{nextN:u,offset:p,isZero:d,isNeg:g,isNegF:w,offsetF:f}}const Bo=new WeakMap,tf=new WeakMap;function Lo(t){return tf.get(t)||1}function _u(t){if(t!==Fr)throw new Error("invalid wNAF")}class _p{BASE;ZERO;Fn;bits;constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>Fr;)n&cr&&(r=r.add(i)),i=i.double(),n>>=cr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=Io(n,this.bits),s=[];let o=e,c=o;for(let u=0;u<r;u++){c=o,s.push(c);for(let f=1;f<i;f++)c=c.add(o),s.push(c);o=c.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=Io(e,this.bits);for(let c=0;c<o.windows;c++){const{nextN:u,offset:f,isZero:p,isNeg:d,isNegF:g,offsetF:w}=xu(r,c,o);r=u,p?s=s.add(Es(g,n[w])):i=i.add(Es(d,n[f]))}return _u(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=Io(e,this.bits);for(let o=0;o<s.windows&&r!==Fr;o++){const{nextN:c,offset:u,isZero:f,isNeg:p}=xu(r,o,s);if(r=c,!f){const d=n[u];i=i.add(p?d.negate():d)}}return _u(r),i}getPrecomputes(e,n,r){let i=Bo.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Bo.set(n,i))),i}cached(e,n,r){const i=Lo(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Lo(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){ef(n,this.bits),tf.set(e,n),Bo.delete(e)}hasCache(e){return Lo(e)!==1}}function kp(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Fr||r>Fr;)n&cr&&(s=s.add(i)),r&cr&&(o=o.add(i)),i=i.double(),n>>=cr,r>>=cr;return{p1:s,p2:o}}function ku(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vp(e),e}else return Fs(t,{isLE:n})}function Sp(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const u of["p","n","h"]){const f=e[u];if(!(typeof f=="bigint"&&f>Fr))throw new Error(`CURVE.${u} must be positive bigint`)}const i=ku(e.p,n.Fp,r),s=ku(e.n,n.Fn,r),c=["Gx","Gy","a","b"];for(const u of c)if(!i.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}function nf(t,e){return function(r){const i=t(r);return{secretKey:i,publicKey:e(i)}}}class rf{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,n){if(Ps(e),Qe(n,void 0,"key"),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 r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),vi(i)}update(e){return vs(this),this.iHash.update(e),this}digestInto(e){vs(this),Qe(e,this.outputLen,"output"),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||=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}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ai=(t,e,n)=>new rf(t,e).update(n).digest();Ai.create=(t,e)=>new rf(t,e);const Su=(t,e)=>(t+(t>=0?e:-e)/sf)/e;function Ap(t,e,n){const[[r,i],[s,o]]=e,c=Su(o*t,n),u=Su(-i*t,n);let f=t-c*r-u*s,p=-c*i-u*o;const d=f<bn,g=p<bn;d&&(f=-f),g&&(p=-p);const w=Za(Math.ceil(fp(n)/2))+Lr;if(f<bn||f>=w||p<bn||p>=w)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:f,k2neg:g,k2:p}}function la(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Mo(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return bs(n.lowS,"lowS"),bs(n.prehash,"prehash"),n.format!==void 0&&la(n.format),n}
vendor: 4,353 bytes, line 1
1class Rp extends Error{constructor(e=""){super(e)}}const Pn={Err:Rp,_tlv:{encode:(t,e)=>{const{Err:n}=Pn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Zi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Zi(i.length/2|128):"";return Zi(t)+s+i+e},decode(t,e){const{Err:n}=Pn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const u=i&127;if(!u)throw new n("tlv.decode(long): indefinite length not supported");if(u>4)throw new n("tlv.decode(long): byte length is too big");const f=e.subarray(r,r+u);if(f.length!==u)throw new n("tlv.decode: length bytes not complete");if(f[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const p of f)o=o<<8|p;if(r+=u,o<128)throw new n("tlv.decode(long): not minimal encoding")}const c=e.subarray(r,r+o);if(c.length!==o)throw new n("tlv.decode: wrong value length");return{v:c,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=Pn;if(t<bn)throw new e("integer: negative integers are not allowed");let n=Zi(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=Pn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Si(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Pn,i=Qe(t,void 0,"signature"),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:c,l:u}=r.decode(2,s),{v:f,l:p}=r.decode(2,u);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(c),s:n.decode(f)}},hexFromSig(t){const{_tlv:e,_int:n}=Pn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},bn=BigInt(0),Lr=BigInt(1),sf=BigInt(2),Xi=BigInt(3),Cp=BigInt(4);function Tp(t,e={}){const n=Sp("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:c}=s;Xa(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:u}=e;if(u&&(!r.is0(s.a)||typeof u.beta!="bigint"||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const f=af(r,i);function p(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(H,C,j){const{x:P,y:X}=C.toAffine(),re=r.toBytes(P);if(bs(j,"isCompressed"),j){p();const xe=!r.isOdd(X);return St(of(xe),re)}else return St(Uint8Array.of(4),re,r.toBytes(X))}function g(H){Qe(H,void 0,"Point");const{publicKey:C,publicKeyUncompressed:j}=f,P=H.length,X=H[0],re=H.subarray(1);if(P===C&&(X===2||X===3)){const xe=r.fromBytes(re);if(!r.isValid(xe))throw new Error("bad point: is not on curve, wrong x");const pe=A(xe);let _e;try{_e=r.sqrt(pe)}catch(we){const ke=we instanceof Error?": "+we.message:"";throw new Error("bad point: is not on curve, sqrt error"+ke)}p();const _=r.isOdd(_e);return(X&1)===1!==_&&(_e=r.neg(_e)),{x:xe,y:_e}}else if(P===j&&X===4){const xe=r.BYTES,pe=r.fromBytes(re.subarray(0,xe)),_e=r.fromBytes(re.subarray(xe,xe*2));if(!I(pe,_e))throw new Error("bad point: is not on curve");return{x:pe,y:_e}}else throw new Error(`bad point: got length ${P}, expected compressed=${C} or uncompressed=${j}`)}const w=e.toBytes||d,x=e.fromBytes||g;function A(H){const C=r.sqr(H),j=r.mul(C,H);return r.add(r.add(j,r.mul(H,s.a)),s.b)}function I(H,C){const j=r.sqr(C),P=A(H);return r.eql(j,P)}if(!I(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const T=r.mul(r.pow(s.a,Xi),Cp),te=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(T,te)))throw new Error("bad curve params: a or b");function ae(H,C,j=!1){if(!r.isValid(C)||j&&r.is0(C))throw new Error(`bad point coordinate ${H}`);return C}function Re(H){if(!(H instanceof ee))throw new Error("Weierstrass Point expected")}function le(H){if(!u||!u.basises)throw new Error("no endo");return Ap(H,u.basises,i.ORDER)}const Y=wu((H,C)=>{const{X:j,Y:P,Z:X}=H;if(r.eql(X,r.ONE))return{x:j,y:P};const re=H.is0();C==null&&(C=re?r.ONE:r.inv(X));const xe=r.mul(j,C),pe=r.mul(P,C),_e=r.mul(X,C);if(re)return{x:r.ZERO,y:r.ZERO};
1if(!r.eql(_e,r.ONE))throw new Error("invZ was invalid");return{x:xe,y:pe}}),Q=wu(H=>{if(H.is0()){if(e.allowInfinityPoint&&!r.is0(H.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:j}=H.toAffine();if(!r.isValid(C)||!r.isValid(j))throw new Error("bad point: x or y not field elements");if(!I(C,j))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function ie(H,C,j,P,X){return j=new ee(r.mul(j.X,H),j.Y,j.Z),C=Es(P,C),j=Es(X,j),C.add(j)}class ee{static BASE=new ee(s.Gx,s.Gy,r.ONE);static ZERO=new ee(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(C,j,P){this.X=ae("x",C),this.Y=ae("y",j,!0),this.Z=ae("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(C){const{x:j,y:P}=C||{};if(!C||!r.isValid(j)||!r.isValid(P))throw new Error("invalid affine point");if(C instanceof ee)throw new Error("projective point not allowed");return r.is0(j)&&r.is0(P)?ee.ZERO:new ee(j,P,r.ONE)}static fromBytes(C){const j=ee.fromAffine(x(Qe(C,void 0,"point")));return j.assertValidity(),j}static fromHex(C){return ee.fromBytes(nt(C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,j=!0){return $.createCache(this,C),j||this.multiply(Xi),this}assertValidity(){Q(this)}hasEvenY(){const{y:C}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(C)}equals(C){Re(C);const{X:j,Y:P,Z:X}=this,{X:re,Y:xe,Z:pe}=C,_e=r.eql(r.mul(j,pe),r.mul(re,X)),_=r.eql(r.mul(P,pe),r.mul(xe,X));return _e&&_}negate(){return new ee(this.X,r.neg(this.Y),this.Z)}double(){const{a:C,b:j}=s,P=r.mul(j,Xi),{X,Y:re,Z:xe}=this;let pe=r.ZERO,_e=r.ZERO,_=r.ZERO,W=r.mul(X,X),we=r.mul(re,re),ke=r.mul(xe,xe),ye=r.mul(X,re);return ye=r.add(ye,ye),_=r.mul(X,xe),_=r.add(_,_),pe=r.mul(C,_),_e=r.mul(P,ke),_e=r.add(pe,_e),pe=r.sub(we,_e),_e=r.add(we,_e),_e=r.mul(pe,_e),pe=r.mul(ye,pe),_=r.mul(P,_),ke=r.mul(C,ke),ye=r.sub(W,ke),ye=r.mul(C,ye),ye=r.add(ye,_),_=r.add(W,W),W=r.add(_,W),W=r.add(W,ke),W=r.mul(W,ye),_e=r.add(_e,W),ke=r.mul(re,xe),ke=r.add(ke,ke),W=r.mul(ke,ye),pe=r.sub(pe,W),_=r.mul(ke,we),_=r.add(_,_),_=r.add(_,_),new ee(pe,_e,_)}add(C){Re(C);const{X:j,Y:P,Z:X}=this,{X:re,Y:xe,Z:pe}=C;let _e=r.ZERO,_=r.ZERO,W=r.ZERO;const we=s.a,ke=r.mul(s.b,Xi);let ye=r.mul(j,re),Ce=r.mul(P,xe),Me=r.mul(X,pe),Ve=r.add(j,P),Ue=r.add(re,xe);Ve=r.mul(Ve,Ue),Ue=r.add(ye,Ce),Ve=r.sub(Ve,Ue),Ue=r.add(j,X);let ut=r.add(re,pe);return Ue=r.mul(Ue,ut),ut=r.add(ye,Me),Ue=r.sub(Ue,ut),ut=r.add(P,X),_e=r.add(xe,pe),ut=r.mul(ut,_e),_e=r.add(Ce,Me),ut=r.sub(ut,_e),W=r.mul(we,Ue),_e=r.mul(ke,Me),W=r.add(_e,W),_e=r.sub(Ce,W),W=r.add(Ce,W),_=r.mul(_e,W),Ce=r.add(ye,ye),Ce=r.add(Ce,ye),Me=r.mul(we,Me),Ue=r.mul(ke,Ue),Ce=r.add(Ce,Me),Me=r.sub(ye,Me),Me=r.mul(we,Me),Ue=r.add(Ue,Me),ye=r.mul(Ce,Ue),_=r.add(_,ye),ye=r.mul(ut,Ue),_e=r.mul(Ve,_e),_e=r.sub(_e,ye),ye=r.mul(Ve,Ce),W=r.mul(ut,W),W=r.add(W,ye),new ee(_e,_,W)}subtract(C){return this.add(C.negate())}is0(){return this.equals(ee.ZERO)}multiply(C){const{endo:j}=e;if(!i.isValidNot0(C))throw new Error("invalid scalar: out of range");let P,X;const re=xe=>$.cached(this,xe,pe=>Eu(ee,pe));if(j){const{k1neg:xe,k1:pe,k2neg:_e,k2:_}=le(C),{p:W,f:we}=re(pe),{p:ke,f:ye}=re(_);X=we.add(ye),P=ie(j.beta,W,ke,xe,_e)}else{const{p:xe,f:pe}=re(C);P=xe,X=pe}return Eu(ee,[P,X])[0]}multiplyUnsafe(C){const{endo:j}=e,P=this;if(!i.isValid(C))throw new Error("invalid scalar: out of range");if(C===bn||P.is0())return ee.ZERO;if(C===Lr)return P;if($.hasCache(this))return this.multiply(C);if(j){const{k1neg:X,k1:re,k2neg:xe,k2:pe}=le(C),{p1:_e,p2:_}=kp(ee,P,re,pe);return ie(j.beta,_e,_,X,xe)}else return $.unsafe(P,C)}toAffine(C){return Y(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return o===Lr?!0:C?C(ee,this):$.unsafe(this,c).is0()}clearCofactor(){const{clearCofactor:C}=e;return o===Lr?this:C?C(ee,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(C=!0){return bs(C,"isCompressed"),this.assertValidity(),w(ee,this,C)}toHex(C=!0){return Je(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const ge=i.BITS,$=new _p(ee,e.endo?Math.ceil(ge/2):ge);return ee.BASE.precompute(8),ee}function of(t){return Uint8Array.of(t?2:3)}function af(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ip(t,e={}){const{Fn:n}=t,r=e.randomBytes||zr,i=Object.assign(af(t.Fp,n),{seed:Jl(n.ORDER)});function s(w){try{const x=n.fromBytes(w);return n.isValidNot0(x)}catch{return!1}}function o(w,x){const{publicKey:A,publicKeyUncompressed:I}=i;try{const T=w.length;return x===!0&&T!==A||x===!1&&T!==I?!1:!!t.fromBytes(w)}catch{return!1}}function c(w=r(i.seed)){return Ql(Qe(w,i.seed,"seed"),n.ORDER)}function u(w,x=!0){return t.BASE.multiply(n.fromBytes(w)).toBytes(x)}function f(w){const{secretKey:x,publicKey:A,publicKeyUncompressed:I}=i;if(!Va(w)||"_lengths"in n&&n._lengths||x===A)return;const T=Qe(w,void 0,"key").length;return T===A||T===I}function p(w,x,A=!0){if(f(w)===!0)throw new Error("first arg must be private key");if(f(x)===!1)throw new Error("second arg must be public key");const I=n.fromBytes(w);return t.fromBytes(x).multiply(I).toBytes(A)}const d={isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:c},g=nf(c,u);return Object.freeze({getPublicKey:u,getSharedSecret:p,keygen:g,Point:t,utils:d,lengths:i})}function Bp(t,e,n={}){Ps(e),Xa(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);const r=n.randomBytes||zr,i=n.hmac||((j,P)=>Ai(e,j,P)),{Fp:s,Fn:o}=t,{ORDER:c,BITS:u}=o,{keygen:f,getPublicKey:p,getSharedSecret:d,utils:g,lengths:w}=Ip(t,n),x={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},A=c*sf<s.ORDER;function I(j){const P=c>>Lr;return j>P}function T(j,P){if(!o.isValidNot0(P))throw new Error(`invalid signature ${j}: out of range 1..Point.Fn.ORDER`);return P}function te(){if(A)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function ae(j,P){la(P);
1const X=w.signature,re=P==="compact"?X:P==="recovered"?X+1:void 0;return Qe(j,re)}class Re{r;s;recovery;constructor(P,X,re){if(this.r=T("r",P),this.s=T("s",X),re!=null){if(te(),![0,1,2,3].includes(re))throw new Error("invalid recovery id");this.recovery=re}Object.freeze(this)}static fromBytes(P,X=x.format){ae(P,X);let re;if(X==="der"){const{r:_,s:W}=Pn.toSig(Qe(P));return new Re(_,W)}X==="recovered"&&(re=P[0],X="compact",P=P.subarray(1));const xe=w.signature/2,pe=P.subarray(0,xe),_e=P.subarray(xe,xe*2);return new Re(o.fromBytes(pe),o.fromBytes(_e),re)}static fromHex(P,X){return this.fromBytes(nt(P),X)}assertRecovery(){const{recovery:P}=this;if(P==null)throw new Error("invalid recovery id: must be present");return P}addRecoveryBit(P){return new Re(this.r,this.s,P)}recoverPublicKey(P){const{r:X,s:re}=this,xe=this.assertRecovery(),pe=xe===2||xe===3?X+c:X;if(!s.isValid(pe))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const _e=s.toBytes(pe),_=t.fromBytes(St(of((xe&1)===0),_e)),W=o.inv(pe),we=Y(Qe(P,void 0,"msgHash")),ke=o.create(-we*W),ye=o.create(re*W),Ce=t.BASE.multiplyUnsafe(ke).add(_.multiplyUnsafe(ye));if(Ce.is0())throw new Error("invalid recovery: point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return I(this.s)}toBytes(P=x.format){if(la(P),P==="der")return nt(Pn.hexFromSig(this));const{r:X,s:re}=this,xe=o.toBytes(X),pe=o.toBytes(re);return P==="recovered"?(te(),St(Uint8Array.of(this.assertRecovery()),xe,pe)):St(xe,pe)}toHex(P){return Je(this.toBytes(P))}}const le=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");
1const X=Si(P),re=P.length*8-u;return re>0?X>>BigInt(re):X},Y=n.bits2int_modN||function(P){return o.create(le(P))},Q=Za(u);function ie(j){return lp("num < 2^"+u,j,bn,Q),o.toBytes(j)}function ee(j,P){return Qe(j,void 0,"message"),P?Qe(e(j),void 0,"prehashed message"):j}function ge(j,P,X){const{lowS:re,prehash:xe,extraEntropy:pe}=Mo(X,x);j=ee(j,xe);const _e=Y(j),_=o.fromBytes(P);if(!o.isValidNot0(_))throw new Error("invalid private key");const W=[ie(_),ie(_e)];if(pe!=null&&pe!==!1){const Ce=pe===!0?r(w.secretKey):pe;W.push(Qe(Ce,void 0,"extraEntropy"))}const we=St(...W),ke=_e;function ye(Ce){const Me=le(Ce);if(!o.isValidNot0(Me))return;const Ve=o.inv(Me),Ue=t.BASE.multiply(Me).toAffine(),ut=o.create(Ue.x);if(ut===bn)return;const Be=o.create(Ve*o.create(ke+ut*_));if(Be===bn)return;let Zn=(Ue.x===ut?0:2)|Number(Ue.y&Lr),Ge=Be;return re&&I(Be)&&(Ge=o.neg(Be),Zn^=1),new Re(ut,Ge,A?void 0:Zn)}return{seed:we,k2sig:ye}}function $(j,P,X={}){const{seed:re,k2sig:xe}=ge(j,P,X);return hp(e.outputLen,o.BYTES,i)(re,xe).toBytes(X.format)}function H(j,P,X,re={}){const{lowS:xe,prehash:pe,format:_e}=Mo(re,x);if(X=Qe(X,void 0,"publicKey"),P=ee(P,pe),!Va(j)){const _=j instanceof Re?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+_)}ae(j,_e);try{const _=Re.fromBytes(j,_e),W=t.fromBytes(X);if(xe&&_.hasHighS())return!1;const{r:we,s:ke}=_,ye=Y(P),Ce=o.inv(ke),Me=o.create(ye*Ce),Ve=o.create(we*Ce),Ue=t.BASE.multiplyUnsafe(Me).add(W.multiplyUnsafe(Ve));return Ue.is0()?!1:o.create(Ue.x)===we}catch{return!1}}function C(j,P,X={}){const{prehash:re}=Mo(X,x);return P=ee(P,re),Re.fromBytes(j,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:f,getPublicKey:p,getSharedSecret:d,utils:g,lengths:w,Point:t,sign:$,verify:H,recoverPublicKey:C,Signature:Re,hash:e})}const Us={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Lp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Mp=BigInt(0),fa=BigInt(2);function Op(t){const e=Us.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),c=BigInt(44),u=BigInt(88),f=t*t*t%e,p=f*f*t%e,d=Nt(p,n,e)*p%e,g=Nt(d,n,e)*p%e,w=Nt(g,fa,e)*f%e,x=Nt(w,i,e)*w%e,A=Nt(x,s,e)*x%e,I=Nt(A,c,e)*A%e,T=Nt(I,u,e)*I%e,te=Nt(T,c,e)*A%e,ae=Nt(te,n,e)*p%e,Re=Nt(ae,o,e)*x%e,le=Nt(Re,r,e)*f%e,Y=Nt(le,fa,e);if(!xs.eql(xs.sqr(Y),t))throw new Error("Cannot find square root");return Y}const xs=Fs(Us.p,{sqrt:Op}),hr=Tp(Us,{Fp:xs,endo:Lp}),Qa=Bp(hr,Vt),Au={};function _s(t,...e){let n=Au[t];if(n===void 0){const r=Vt(cp(t));n=St(r,r),Au[t]=n}return Vt(St(n,...e))}const ec=t=>t.toBytes(!0).slice(1),tc=t=>t%fa===Mp;function ha(t){const{Fn:e,BASE:n}=hr,r=e.fromBytes(t),i=n.multiply(r);return{scalar:tc(i.y)?r:e.neg(r),bytes:ec(i)}}function cf(t){const e=xs;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x ≥ p");const n=e.create(t*t),r=e.create(n*t+BigInt(7));let i=e.sqrt(r);tc(i)||(i=e.neg(i));const s=hr.fromAffine({x:t,y:i});return s.assertValidity(),s}const yi=Si;function uf(...t){return hr.Fn.create(yi(_s("BIP0340/challenge",...t)))}function Ru(t){return ha(t).bytes}function Dp(t,e,n=zr(32)){const{Fn:r}=hr,i=Qe(t,void 0,"message"),{bytes:s,scalar:o}=ha(e),c=Qe(n,32,"auxRand"),u=r.toBytes(o^yi(_s("BIP0340/aux",c))),f=_s("BIP0340/nonce",u,s,i),{bytes:p,scalar:d}=ha(f),g=uf(p,s,i),w=new Uint8Array(64);if(w.set(p,0),w.set(r.toBytes(r.create(d+g*o)),32),!lf(w,i,s))throw new Error("sign: Invalid signature produced");return w}function lf(t,e,n){const{Fp:r,Fn:i,BASE:s}=hr,o=Qe(t,64,"signature"),c=Qe(e,void 0,"message"),u=Qe(n,32,"publicKey");try{const f=cf(yi(u)),p=yi(o.subarray(0,32));if(!r.isValidNot0(p))return!1;const d=yi(o.subarray(32,64));if(!i.isValidNot0(d))return!1;const g=uf(i.toBytes(p),ec(f),c),w=s.multiplyUnsafe(d).add(f.multiplyUnsafe(i.neg(g))),{x,y:A}=w.toAffine();return!(w.is0()||!tc(A)||x!==p)}catch{return!1}}const on=(()=>{const n=(r=zr(48))=>Ql(r,Us.n);return{keygen:nf(n,Ru),getPublicKey:Ru,sign:Dp,verify:lf,Point:hr,utils:{randomSecretKey:n,taggedHash:_s,lift_x:cf,pointToBytes:ec},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();new TextDecoder("utf-8");var Np=new TextEncoder;function Pp(t){for(let e=0;e<64;e++){let n=t.charCodeAt(e);if(isNaN(n)||n<48||n>102||n>57&&n<97)return!1}return!0}var Fn=Symbol("verified"),Fp=t=>t instanceof Object;function Up(t){if(!Fp(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!Pp(t.pubkey)||!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 $p=class{generateSecretKey(){return on.utils.randomSecretKey()}getPublicKey(e){return Je(on.getPublicKey(e))}finalizeEvent(e,n){const r=e;
1return r.pubkey=Je(on.getPublicKey(n)),r.id=Oo(r),r.sig=Je(on.sign(nt(Oo(r)),n)),r[Fn]=!0,r}verifyEvent(e){if(typeof e[Fn]=="boolean")return e[Fn];try{const n=Oo(e);if(n!==e.id)return e[Fn]=!1,!1;const r=on.verify(nt(e.sig),nt(n),nt(e.pubkey));return e[Fn]=r,r}catch{return e[Fn]=!1,!1}}};function Kp(t){if(!Up(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 Oo(t){let e=Vt(Np.encode(Kp(t)));return Je(e)}var $s=new $p;$s.generateSecretKey;$s.getPublicKey;$s.finalizeEvent;var ff=$s.verifyEvent;const nc=new WeakSet,Cu=/^[0-9a-f]{64}$/,zp=/^[0-9a-f]{128}$/;function Tu(t){if(t.limit!==void 0&&(!Number.isSafeInteger(t.limit)||t.limit<0))throw new RangeError("Query limit must be a non-negative safe integer");if(t.deadline!==void 0&&!Number.isFinite(t.deadline))throw new RangeError("Query deadline must be a finite Unix timestamp in milliseconds")}class Hn extends Error{kind;constructor(e,n){super(n),this.name="PubsubError",this.kind=e}static validation(e){return new Hn("validation",e)}static storage(e){return new Hn("storage",e)}}function Mr(t,e=ff){if(nc.has(t))return hf(t);const n=df(t);if(!e(n))throw Hn.validation("invalid Nostr event id or signature");const r=n;return r[Fn]=!0,pf(r)}function hf(t){if(!nc.has(t))throw Hn.validation("verified mesh paths require verifyNostrEvent output");const e=df(t);return e[Fn]=!0,pf(e)}function df(t){try{if(typeof t!="object"||t===null)throw new TypeError("invalid event");const e=t.id,n=t.pubkey,r=t.created_at,i=t.kind,s=t.tags,o=t.content,c=t.sig;if(typeof e!="string"||!Cu.test(e)||typeof n!="string"||!Cu.test(n)||!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(i)||i<0||i>65535||!Array.isArray(s)||s.some(u=>!Array.isArray(u)||u.some(f=>typeof f!="string"))||typeof o!="string"||typeof c!="string"||!zp.test(c))throw new TypeError("invalid event");return{id:e,pubkey:n,created_at:r,kind:i,tags:s.map(u=>[...u]),content:o,sig:c}}catch{throw Hn.validation("invalid Nostr event structure")}}function pf(t){if(!Number.isSafeInteger(t.created_at)||t.created_at<0||!Number.isSafeInteger(t.kind)||t.kind<0||t.kind>65535)throw Hn.validation("invalid Nostr event timestamp or kind");for(const e of t.tags)Object.freeze(e);return Object.freeze(t.tags),nc.add(t),Object.freeze(t)}const Hp=300,qp={LocalIndex:"local-index"};function yf(t){return{id:t,kind:qp.LocalIndex}}function gf(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),i=t[`#${r}`];if(i&&!e.tags.find(([s,o])=>s===n.slice(1)&&i.indexOf(o)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function ks(t,e){for(let n=0;n<t.length;n++)if(gf(t[n],e))return!0;return!1}function rc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wp(t){if(!rc(t))throw new Error("Uint8Array expected")}function mf(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function jp(t){if(typeof t!="function")throw new Error("function expected");return!0}function lr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function ic(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function da(t){if(!Array.isArray(t))throw new Error("array expected")}function Ss(t,e){if(!mf(!0,e))throw new Error(`${t}: array of strings expected`)}function wf(t,e){if(!mf(!1,e))throw new Error(`${t}: array of numbers expected`)}function vf(...t){const e=s=>s,n=(s,o)=>c=>s(o(c)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function bf(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Ss("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(da(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(da(i),i.map(s=>{lr("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}
1))}}function Ef(t=""){return lr("join",t),{encode:e=>(Ss("join.decode",e),e.join(t)),decode:e=>(lr("join.decode",e),e.split(t))}}function Vp(t,e="="){return ic(t),lr("padding",e),{encode(n){for(Ss("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Ss("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}const xf=(t,e)=>e===0?t:xf(e,t%e),As=(t,e)=>t+(e-xf(t,e)),hs=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function pa(t,e,n,r){if(da(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(As(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${As(e,n)}`);let i=0,s=0;const o=hs[e],c=hs[n]-1,u=[];for(const f of t){if(ic(f),f>=o)throw new Error(`convertRadix2: invalid data word=${f} from=${e}`);if(i=i<<e|f,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)u.push((i>>s-n&c)>>>0);const p=hs[s];if(p===void 0)throw new Error("invalid carry");i&=p-1}if(i=i<<n-s&c,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&u.push(i>>>0),u}function _f(t,e=!1){if(ic(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(As(8,t)>32||As(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!rc(n))throw new Error("radix2.encode input should be Uint8Array");return pa(Array.from(n),8,t,!e)},decode:n=>(wf("radix2.decode",n),Uint8Array.from(pa(n,t,8,e)))}}function Iu(t){return jp(t),function(...e){try{return t.apply(null,e)}catch{}}}const Gp=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Yp=(t,e)=>{lr("base64",t);const n=/^[A-Za-z0-9=+/]+$/,r="base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},qn=Gp?{encode(t){return Wp(t),t.toBase64()},decode(t){return Yp(t)}}:vf(_f(6),bf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vp(6),Ef("")),ya=vf(bf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ef("")),Bu=[996825010,642813549,513874426,1027748829,705979059];function li(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Bu.length;r++)(e>>r&1)===1&&(n^=Bu[r]);return n}function Lu(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=li(i)^o>>5}i=li(i);for(let s=0;s<r;s++)i=li(i)^t.charCodeAt(s)&31;for(let s of e)i=li(i)^s;for(let s=0;s<6;s++)i=li(i);return i^=n,ya.encode(pa([i%hs[30]],30,5,!1))}function Zp(t){const e=t==="bech32"?1:734539939,n=_f(5),r=n.decode,i=n.encode,s=Iu(r);function o(d,g,w=90){lr("bech32.encode prefix",d),rc(g)&&(g=Array.from(g)),wf("bech32.encode",g);const x=d.length;if(x===0)throw new TypeError(`Invalid prefix length ${x}`);const A=x+7+g.length;if(w!==!1&&A>w)throw new TypeError(`Length ${A} exceeds limit ${w}`);const I=d.toLowerCase(),T=Lu(I,g,e);return`${I}1${ya.encode(g)}${T}`}function c(d,g=90){lr("bech32.decode input",d);const w=d.length;if(w<8||g!==!1&&w>g)throw new TypeError(`invalid string length: ${w} (${d}). Expected (8..${g})`);const x=d.toLowerCase();if(d!==x&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");const A=x.lastIndexOf("1");if(A===0||A===-1)throw new Error('Letter "1" must be present between prefix and data only');const I=x.slice(0,A),T=x.slice(A+1);if(T.length<6)throw new Error("Data must be at least 6 characters long");const te=ya.decode(T).slice(0,-6),ae=Lu(I,te,e);if(!T.endsWith(ae))throw new Error(`Invalid checksum in ${d}: expected "${ae}"`);return{prefix:I,words:te}}const u=Iu(c);function f(d){const{prefix:g,words:w}=c(d,!1);return{prefix:g,words:w,bytes:r(w)}}function p(d,g){return o(d,i(g))}return{encode:o,decode:c,encodeFromBytes:p,decodeToBytes:f,decodeUnsafe:u,fromWords:r,fromWordsUnsafe:s,toWords:i}}const Ur=Zp("bech32");function Xp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mu(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Do(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Tt(t,e,n=""){const r=Xp(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,c=s?` of length ${e}`:"",u=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+c+", got "+u)}return t}function xt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $r(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Jp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qp(t,e){return t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function kf(t,e){if(Qp(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function ey(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function ty(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 ny=(t,e)=>{function n(r,...i){if(Tt(r,void 0,"key"),!Jp)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const p=i[0];Tt(p,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength;s&&i[1]!==void 0&&Tt(i[1],void 0,"AAD");const o=e(r,...i),c=(p,d)=>
1{if(d!==void 0){if(p!==2)throw new Error("cipher output not supported");Tt(d,void 0,"output")}};let u=!1;return{encrypt(p,d){if(u)throw new Error("cannot encrypt() twice with same key + nonce");return u=!0,Tt(p),c(o.encrypt.length,d),o.encrypt(p,d)},decrypt(p,d){if(Tt(p),s&&p.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return c(o.decrypt.length,d),o.decrypt(p,d)}}}return Object.assign(n,t),n};function Sf(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(n&&!Or(e))throw new Error("invalid output, must be aligned");return e}function Or(t){return t.byteOffset%4===0}function ur(t){return Uint8Array.from(t)}const Kn=16,ry=283;function iy(t){if(![16,24,32].includes(t.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+t.length)}function sc(t){return t<<1^ry&-(t>>7)}function Br(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(e&1),t=sc(t);return n}const ga=(()=>{const t=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=sc(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 $r(t),e})(),sy=ga.map((t,e)=>ga.indexOf(e)),oy=t=>t<<24|t>>>8,No=t=>t<<8|t>>>24;function Af(t,e){if(t.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((f,p)=>e(t[p])),r=n.map(No),i=r.map(No),s=i.map(No),o=new Uint32Array(256*256),c=new Uint32Array(256*256),u=new Uint16Array(256*256);for(let f=0;f<256;f++)for(let p=0;p<256;p++){const d=f*256+p;o[d]=n[f]^r[p],c[d]=i[f]^s[p],u[d]=t[f]<<8|t[p]}return{sbox:t,sbox2:u,T0:n,T1:r,T2:i,T3:s,T01:o,T23:c}}const oc=Af(ga,t=>Br(t,3)<<24|t<<16|t<<8|Br(t,2)),Rf=Af(sy,t=>Br(t,11)<<24|Br(t,13)<<16|Br(t,9)<<8|Br(t,14)),ay=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=sc(n))t[e]=n;return t})();function Cf(t){Tt(t);const e=t.length;iy(t);const{sbox2:n}=oc,r=[];Or(t)||r.push(t=ur(t));const i=xt(t),s=i.length,o=u=>an(n,u,u,u,u),c=new Uint32Array(e+28);c.set(i);for(let u=s;u<c.length;u++){let f=c[u-1];u%s===0?f=o(oy(f))^ay[u/s-1]:s>6&&u%s===4&&(f=o(f)),c[u]=c[u-s]^f}return $r(...r),c}function cy(t){const e=Cf(t),n=e.slice(),r=e.length,{sbox2:i}=oc,{T0:s,T1:o,T2:c,T3:u}=Rf;for(let f=0;f<r;f+=4)for(let p=0;p<4;p++)n[f+p]=e[r-f-4+p];$r(e);for(let f=4;f<r-4;f++){const p=n[f],d=an(i,p,p,p,p);n[f]=s[d&255]^o[d>>>8&255]^c[d>>>16&255]^u[d>>>24]}return n}function $n(t,e,n,r,i,s){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|s>>>24&255]}function an(t,e,n,r,i){return t[e&255|n&65280]|t[r>>>16&255|i>>>16&65280]<<16}function Ou(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=oc;let u=0;e^=t[u++],n^=t[u++],r^=t[u++],i^=t[u++];const f=t.length/4-2;for(let x=0;x<f;x++){const A=t[u++]^$n(o,c,e,n,r,i),I=t[u++]^$n(o,c,n,r,i,e),T=t[u++]^$n(o,c,r,i,e,n),te=t[u++]^$n(o,c,i,e,n,r);e=A,n=I,r=T,i=te}const p=t[u++]^an(s,e,n,r,i),d=t[u++]^an(s,n,r,i,e),g=t[u++]^an(s,r,i,e,n),w=t[u++]^an(s,i,e,n,r);return{s0:p,s1:d,s2:g,s3:w}}function uy(t,e,n,r,i){const{sbox2:s,T01:o,T23:c}=Rf;let u=0;e^=t[u++],n^=t[u++],r^=t[u++],i^=t[u++];const f=t.length/4-2;for(let x=0;x<f;x++){const A=t[u++]^$n(o,c,e,i,r,n),I=t[u++]^$n(o,c,n,e,i,r),T=t[u++]^$n(o,c,r,n,e,i),te=t[u++]^$n(o,c,i,r,n,e);e=A,n=I,r=T,i=te}const p=t[u++]^an(s,e,i,r,n),d=t[u++]^an(s,n,e,i,r),g=t[u++]^an(s,r,n,e,i),w=t[u++]^an(s,i,r,n,e);return{s0:p,s1:d,s2:g,s3:w}}function ly(t){if(Tt(t),t.length%Kn!==0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size "+Kn)}function fy(t,e,n){Tt(t);let r=t.length;const i=r%Kn;if(!e&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Or(t)||(t=ur(t));const s=xt(t);if(e){let c=Kn-i;c||(c=Kn),r=r+c}n=Sf(r,n),kf(t,n);const o=xt(n);return{b:s,o,out:n}}function hy(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");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 dy(t){const e=new Uint8Array(16),n=xt(e);e.set(t);const r=Kn-t.length;for(let i=Kn-r;i<Kn;i++)e[i]=r;return n}const Tf=ny({blockSize:16,nonceLength:16},function(e,n,r={}){const i=!r.disablePadding;return{encrypt(s,o){const c=Cf(e),{b:u,o:f,out:p}=fy(s,i,o);let d=n;const g=[c];Or(d)||g.push(d=ur(d));const w=xt(d);let x=w[0],A=w[1],I=w[2],T=w[3],te=0;for(;te+4<=u.length;)x^=u[te+0],A^=u[te+1],I^=u[te+2],T^=u[te+3],{s0:x,s1:A,s2:I,s3:T}=Ou(c,x,A,I,T),f[te++]=x,f[te++]=A,f[te++]=I,f[te++]=T;if(i){const ae=dy(s.subarray(te*4));x^=ae[0],A^=ae[1],I^=ae[2],T^=ae[3],{s0:x,s1:A,s2:I,s3:T}=Ou(c,x,A,I,T),f[te++]=x,f[te++]=A,f[te++]=I,f[te++]=T}return $r(...g),p},decrypt(s,o){ly(s);const c=cy(e);let u=n;const f=[c];Or(u)||f.push(u=ur(u));const p=xt(u);o=Sf(s.length,o),Or(s)||f.push(s=ur(s)),kf(s,o);const d=xt(s),g=xt(o);let w=p[0],x=p[1],A=p[2],I=p[3];for(let T=0;T+4<=d.length;
1){const te=w,ae=x,Re=A,le=I;w=d[T+0],x=d[T+1],A=d[T+2],I=d[T+3];const{s0:Y,s1:Q,s2:ie,s3:ee}=uy(c,w,x,A,I);g[T++]=Y^te,g[T++]=Q^ae,g[T++]=ie^Re,g[T++]=ee^le}return $r(...f),hy(o,i)}}}),If=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),py=If("expand 16-byte k"),yy=If("expand 32-byte k"),gy=xt(py),my=xt(yy);function Ze(t,e){return t<<e|t>>>32-e}function ma(t){return t.byteOffset%4===0}const Ji=64,wy=16,Bf=2**32-1,Du=Uint32Array.of();function vy(t,e,n,r,i,s,o,c){const u=i.length,f=new Uint8Array(Ji),p=xt(f),d=ma(i)&&ma(s),g=d?xt(i):Du,w=d?xt(s):Du;for(let x=0;x<u;o++){if(t(e,n,r,p,o,c),o>=Bf)throw new Error("arx: counter overflow");const A=Math.min(Ji,u-x);if(d&&A===Ji){const I=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let T=0,te;T<wy;T++)te=I+T,w[te]=g[te]^p[T];x+=Ji;continue}for(let I=0,T;I<A;I++)T=x+I,s[T]=i[T]^f[I];x+=A}}function by(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=ey({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Do(i),Do(o),Mu(s),Mu(n),(c,u,f,p,d=0)=>{Tt(c,void 0,"key"),Tt(u,void 0,"nonce"),Tt(f,void 0,"data");const g=f.length;if(p===void 0&&(p=new Uint8Array(g)),Tt(p,void 0,"output"),Do(d),d<0||d>=Bf)throw new Error("arx: counter overflow");if(p.length<g)throw new Error(`arx: output (${p.length}) is shorter than data (${g})`);const w=[];let x=c.length,A,I;if(x===32)w.push(A=ur(c)),I=my;else if(x===16&&n)A=new Uint8Array(32),A.set(c),A.set(c,16),I=gy,w.push(A);else throw Tt(c,32,"arx key"),new Error("invalid key size");ma(u)||w.push(u=ur(u));const T=xt(A);if(r){if(u.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(I,T,xt(u.subarray(0,16)),T),u=u.subarray(16)}const te=16-i;if(te!==u.length)throw new Error(`arx: nonce must be ${te} or 16 bytes`);if(te!==12){const Re=new Uint8Array(12);Re.set(u,s?0:12-u.length),u=Re,w.push(u)}const ae=xt(u);return vy(t,I,T,ae,f,p,d,o),$r(...w),p}}function Ey(t,e,n,r,i,s=20){let o=t[0],c=t[1],u=t[2],f=t[3],p=e[0],d=e[1],g=e[2],w=e[3],x=e[4],A=e[5],I=e[6],T=e[7],te=i,ae=n[0],Re=n[1],le=n[2],Y=o,Q=c,ie=u,ee=f,ge=p,$=d,H=g,C=w,j=x,P=A,X=I,re=T,xe=te,pe=ae,_e=Re,_=le;for(let we=0;we<s;we+=2)Y=Y+ge|0,xe=Ze(xe^Y,16),j=j+xe|0,ge=Ze(ge^j,12),Y=Y+ge|0,xe=Ze(xe^Y,8),j=j+xe|0,ge=Ze(ge^j,7),Q=Q+$|0,pe=Ze(pe^Q,16),P=P+pe|0,$=Ze($^P,12),Q=Q+$|0,pe=Ze(pe^Q,8),P=P+pe|0,$=Ze($^P,7),ie=ie+H|0,_e=Ze(_e^ie,16),X=X+_e|0,H=Ze(H^X,12),ie=ie+H|0,_e=Ze(_e^ie,8),X=X+_e|0,H=Ze(H^X,7),ee=ee+C|0,_=Ze(_^ee,16),re=re+_|0,C=Ze(C^re,12),ee=ee+C|0,_=Ze(_^ee,8),re=re+_|0,C=Ze(C^re,7),Y=Y+$|0,_=Ze(_^Y,16),X=X+_|0,$=Ze($^X,12),Y=Y+$|0,_=Ze(_^Y,8),X=X+_|0,$=Ze($^X,7),Q=Q+H|0,xe=Ze(xe^Q,16),re=re+xe|0,H=Ze(H^re,12),Q=Q+H|0,xe=Ze(xe^Q,8),re=re+xe|0,H=Ze(H^re,7),ie=ie+C|0,pe=Ze(pe^ie,16),j=j+pe|0,C=Ze(C^j,12),ie=ie+C|0,pe=Ze(pe^ie,8),j=j+pe|0,C=Ze(C^j,7),ee=ee+ge|0,_e=Ze(_e^ee,16),P=P+_e|0,ge=Ze(ge^P,12),ee=ee+ge|0,_e=Ze(_e^ee,8),P=P+_e|0,ge=Ze(ge^P,7);let W=0;r[W++]=o+Y|0,r[W++]=c+Q|0,r[W++]=u+ie|0,r[W++]=f+ee|0,r[W++]=p+ge|0,r[W++]=d+$|0,r[W++]=g+H|0,r[W++]=w+C|0,r[W++]=x+j|0,r[W++]=A+P|0,r[W++]=I+X|0,r[W++]=T+re|0,r[W++]=te+xe|0,r[W++]=ae+pe|0,r[W++]=Re+_e|0,r[W++]=le+_|0}const Lf=by(Ey,{counterRight:!1,counterLength:4,allowShortKeys:!1});function xy(t,e,n){return Ps(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ai(t,n,e)}const Po=Uint8Array.of(0),Nu=Uint8Array.of();function _y(t,e,n,r=32){Ps(t),zn(r,"length");const i=t.outputLen;if(r>255*i)throw new Error("Length must be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0?n=Nu:Qe(n,void 0,"info");const o=new Uint8Array(s*i),c=Ai.create(t,e),u=c._cloneInto(),f=new Uint8Array(c.outputLen);for(let p=0;p<s;p++)Po[0]=p+1,u.update(p===0?Nu:f).update(n).update(Po).digestInto(f),o.set(f,i*p),c._cloneInto(u);return c.destroy(),u.destroy(),vi(f,Po),o.slice(0,r)}var ky=Object.defineProperty,rt=(t,e)=>{for(var n in e)ky(t,n,{get:e[n],enumerable:!0})},Sy={};rt(Sy,{binarySearch:()=>ac,bytesToHex:()=>Je,hexToBytes:()=>nt,insertEventIntoAscendingList:()=>Cy,insertEventIntoDescendingList:()=>Ry,isHex32:()=>Bt,mergeReverseSortedLists:()=>Ty,normalizeURL:()=>Ay,utf8Decoder:()=>En,utf8Encoder:()=>Kt});var En=new TextDecoder("utf-8"),Kt=new TextEncoder;function Ay(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 Ry(t,e){const[n,r]=ac(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 Cy(t,e){const[n,r]=ac(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 ac(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]}function Ty(t,e){const n=new Array(t.length+e.length);n.length=0;let r=0,i=0,s=[];for(;r<t.length&&i<e.length;){let o;if(t[r]?.created_at>e[i]?.created_at?(o=t[r],r++):(o=e[i],i++),n.length>0&&n[n.length-1].created_at===o.created_at){if(s.includes(o.id))continue}else s.length=0;n.push(o),s.push(o.id)}for(;r<t.length;){const o=t[r];if(r++,n.length>0&&n[n.length-1].created_at===o.created_at){if(s.includes(o.id))continue}else s.length=0;n.push(o),s.push(o.id)}for(;i<e.length;){const o=e[i];if(i++,n.length>0&&n[n.length-1].created_at===o.created_at){if(s.includes(o.id))continue}else s.length=0;n.push(o),s.push(o.id)}return n}function Bt(t){for(let e=0;e<64;e++){let n=t.charCodeAt(e);if(isNaN(n)||n<48||n>102||n>57&&n<97)return!1}return!0}var Tr=Symbol("verified"),Iy=t=>t instanceof Object;function cc(t){if(!Iy(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!Bt(t.pubkey)||!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 By=class{generateSecretKey(){return on.utils.randomSecretKey()}getPublicKey(t){return Je(on.getPublicKey(t))}finalizeEvent(t,e){const n=t;
1return n.pubkey=Je(on.getPublicKey(e)),n.id=Dr(n),n.sig=Je(on.sign(nt(Dr(n)),e)),n[Tr]=!0,n}verifyEvent(t){if(typeof t[Tr]=="boolean")return t[Tr];try{const e=Dr(t);if(e!==t.id)return t[Tr]=!1,!1;const n=on.verify(nt(t.sig),nt(e),nt(t.pubkey));return t[Tr]=n,n}catch{return t[Tr]=!1,!1}}};function Ly(t){if(!cc(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 Dr(t){let e=Vt(Kt.encode(Ly(t)));return Je(e)}var Ks=new By,My=Ks.generateSecretKey,uc=Ks.getPublicKey,ln=Ks.finalizeEvent,Hr=Ks.verifyEvent,Oy={};rt(Oy,{AIEmbeddings:()=>Cg,AppCurationSet:()=>uw,Application:()=>aw,AuthoredPodcasts:()=>Cm,BadgeAward:()=>zy,BadgeDefinition:()=>Ym,Bid:()=>rg,BidConfirmation:()=>ig,BlobsAuth:()=>$m,BlockedRelaysList:()=>lm,BlossomServerList:()=>_m,BookmarkList:()=>am,Bookmarksets:()=>qm,Calendar:()=>Aw,CalendarEventRSVP:()=>Rw,CashuMintAnnouncement:()=>Fw,CashuWalletEvent:()=>Nm,CashuWalletHistory:()=>$g,CashuWalletTokens:()=>Ug,ChannelCreation:()=>Ff,ChannelHideMessage:()=>Kf,ChannelMessage:()=>$f,ChannelMetadata:()=>Uf,ChannelMuteUser:()=>zf,ChatMessage:()=>Hy,Chess:()=>eg,ClassifiedListing:()=>yw,ClientAuth:()=>qf,CodeSnippet:()=>dg,CoinjoinPool:()=>Bg,Comment:()=>cg,CommunitiesList:()=>cm,CommunityDefinition:()=>Ow,CommunityPostApproval:()=>Og,ConferenceEvent:()=>hw,Contacts:()=>Uy,CreateOrUpdateProduct:()=>Jm,CreateOrUpdateStall:()=>Xm,CuratedVideoSets:()=>jm,Curationsets:()=>Wm,Date:()=>kw,DecoupledEncryptionKeyDistribution:()=>Mg,DecoupledKeyAnnouncement:()=>bm,DecoupledKeyClientAnnouncement:()=>Lg,DirectMessageRelaysList:()=>Em,DraftClassifiedListing:()=>gw,DraftEvent:()=>Ew,DraftLong:()=>nw,Emojisets:()=>rw,EncryptedDirectMessage:()=>$y,EventDeletion:()=>Ky,FavoriteFollowSets:()=>wm,FavoritePodcasts:()=>xm,FavoriteRelays:()=>dm,FedimintAnnouncement:()=>Uw,Feed:()=>_w,FileMessage:()=>Vy,FileMetadata:()=>og,FileServerPreference:()=>km,Followsets:()=>Km,ForumThread:()=>Wy,GenericRepost:()=>pc,Genericlists:()=>zm,GeocacheListing:()=>Nw,GeocacheLog:()=>Kg,GeocacheLogEntry:()=>Pw,GeocacheProofOfFind:()=>zg,GiftWrap:()=>Hf,GitPullRequest:()=>yg,GitPullRequestUpdate:()=>gg,GoodWikiAuthorList:()=>Sm,GoodWikiRelayList:()=>Am,GroupMetadata:()=>Kw,HTTPAuth:()=>yc,Handlerinformation:()=>Iw,Handlerrecommendation:()=>Tw,Highlights:()=>rm,InteractiveRoom:()=>fw,InterestsList:()=>ym,Interestsets:()=>Zm,Issue:()=>mg,JobFeedback:()=>Pg,JobRequest:()=>Dg,JobResult:()=>Ng,Label:()=>Ag,LegacyNsiteFile:()=>Lw,LightningPubRPC:()=>Pm,LinkSet:()=>xw,LiveChatMessage:()=>hg,LiveEvent:()=>lw,LongFormArticle:()=>tw,MarketplaceUI:()=>Qm,MediaFollows:()=>mm,MediaStarterPacks:()=>Vw,MergeRequests:()=>tg,Metadata:()=>Py,ModularArticleContent:()=>sw,ModularArticleHeader:()=>iw,MuteSets:()=>Vm,Mutelist:()=>im,NWCWalletInfo:()=>Om,NWCWalletRequest:()=>Wf,NWCWalletResponse:()=>Fm,NormalVideo:()=>Zy,NostrConnect:()=>Um,NsiteNamed:()=>Dw,NsiteRoot:()=>Dm,NutZap:()=>Qg,NutZapInfo:()=>gm,OpenTimestamps:()=>sg,Patch:()=>pg,PeerToPeerOrderEvents:()=>$w,Photo:()=>Yy,Pinlist:()=>sm,PodcastEpisode:()=>Qy,PodcastMetadata:()=>Rm,Poll:()=>ag,PollResponse:()=>ng,PrivateDirectMessage:()=>Pf,PrivateEventRelayList:()=>pm,ProblemTracker:()=>_g,ProductSoldAsAuction:()=>ew,ProfileBadges:()=>Gm,ProxyAnnouncement:()=>Lm,PublicChatsList:()=>um,PublicMessage:()=>Jy,Reaction:()=>dc,ReactionToWebsite:()=>Gy,RecommendRelay:()=>Fy,Redirects:()=>bw,RelayDiscovery:()=>cw,RelayList:()=>om,RelayMonitorAnnouncement:()=>Tm,RelayReview:()=>Cw,RelayReviews:()=>Rg,Relaysets:()=>Hm,ReleaseArtifactSets:()=>ow,Reply:()=>wg,Report:()=>kg,Reporting:()=>Sg,RepositoryAnnouncement:()=>mw,RepositoryState:()=>ww,Repost:()=>hc,ReservedCashuWalletTokens:()=>Fg,RoomPresence:()=>Im,Scroll:()=>lg,Seal:()=>Nf,SearchRelaysList:()=>fm,ShortTextNote:()=>Df,ShortVideo:()=>Xy,SimpleGroupAdmins:()=>zw,SimpleGroupCreateGroup:()=>Vg,SimpleGroupCreateInvite:()=>Yg,SimpleGroupDeleteEvent:()=>jg,SimpleGroupDeleteGroup:()=>Gg,SimpleGroupEditMetadata:()=>Wg,SimpleGroupJoinRequest:()=>Zg,SimpleGroupLeaveRequest:()=>Xg,SimpleGroupList:()=>hm,SimpleGroupLiveKitParticipants:()=>Ww,SimpleGroupMembers:()=>Hw,SimpleGroupPutUser:()=>Hg,SimpleGroupRemoveUser:()=>qg,SimpleGroupReply:()=>jy,SimpleGroupRoles:()=>qw,SimpleGroupThreadedReply:()=>qy,SlideSet:()=>pw,SoftwareApplication:()=>Bw,StarterPacks:()=>jw,StatusApplied:()=>bg,StatusClosed:()=>Eg,StatusDraft:()=>xg,StatusOpen:()=>vg,TidalLogin:()=>em,Time:()=>Sw,Torrent:()=>Tg,TorrentComment:()=>Ig,TransportMethodAnnouncement:()=>Mm,UserEmojiList:()=>vm,UserGraspList:()=>Bm,UserStatuses:()=>dw,VideoViewEvent:()=>Mw,Voice:()=>ug,VoiceComment:()=>fg,WebBookmarks:()=>Gw,WikiArticle:()=>vw,Zap:()=>nm,ZapGoal:()=>Jg,ZapRequest:()=>tm,classifyKind:()=>Dy,isAddressableKind:()=>fc,isEphemeralKind:()=>Of,isKind:()=>Ny,isRegularKind:()=>Mf,isReplaceableKind:()=>lc});function Mf(t){return t<1e4&&t!==0&&t!==3}function lc(t){return t===0||t===3||1e4<=t&&t<2e4}function Of(t){return 2e4<=t&&t<3e4}function fc(t){return 3e4<=t&&t<4e4}function Dy(t){return Mf(t)?"regular":lc(t)?"replaceable":Of(t)?"ephemeral":fc(t)?"parameterized":"unknown"}function Ny(t,e){const n=e instanceof Array?e:[e];return cc(t)&&n.includes(t.kind)||!1}var Py=0,Df=1,Fy=2,Uy=3,$y=4,Ky=5,hc=6,dc=7,zy=8,Hy=9,qy=10,Wy=11,jy=12,Nf=13,Pf=14,Vy=15,pc=16,Gy=17,Yy=20,Zy=21,Xy=22,Jy=24,Ff=40,Uf=41,$f=42,Kf=43,zf=44,Qy=54,eg=64,tg=818,ng=1018,rg=1021,ig=1022,sg=1040,Hf=1059,og=1063,ag=1068,cg=1111,ug=1222,lg=1227,fg=1244,hg=1311,dg=1337,pg=1617,yg=1618,gg=1619,mg=1621,wg=1622,vg=1630,bg=1631,Eg=1632,xg=1633,_g=1971,kg=1984,Sg=1984,Ag=1985,Rg=1986,Cg=1987,Tg=2003,Ig=2004,Bg=2022,Lg=4454,Mg=4455,Og=4550,Dg=5999,Ng=6999,Pg=7e3,Fg=7374,Ug=7375,$g=7376,Kg=7516,zg=7517,Hg=9e3,qg=9001,Wg=9002,jg=9005,Vg=9007,Gg=9008,Yg=9009,Zg=9021,Xg=9022,Jg=9041,Qg=9321,em=9467,tm=9734,nm=9735,rm=98
102,im=1e4,sm=10001,om=10002,am=10003,cm=10004,um=10005,lm=10006,fm=10007,hm=10009,dm=10012,pm=10013,ym=10015,gm=10019,mm=10020,wm=10021,vm=10030,bm=10044,Em=10050,xm=10054,_m=10063,km=10096,Sm=10101,Am=10102,Rm=10154,Cm=10164,Tm=10166,Im=10312,Bm=10317,Lm=10377,Mm=11111,Om=13194,Dm=15128,Nm=17375,Pm=21e3,qf=22242,Wf=23194,Fm=23195,Um=24133,$m=24242,yc=27235,Km=3e4,zm=30001,Hm=30002,qm=30003,Wm=30004,jm=30005,Vm=30007,Gm=30008,Ym=30009,Zm=30015,Xm=30017,Jm=30018,Qm=30019,ew=30020,tw=30023,nw=30024,rw=30030,iw=30040,sw=30041,ow=30063,aw=30078,cw=30166,uw=30267,lw=30311,fw=30312,hw=30313,dw=30315,pw=30388,yw=30402,gw=30403,mw=30617,ww=30618,vw=30818,bw=30819,Ew=31234,xw=31388,_w=31890,kw=31922,Sw=31923,Aw=31924,Rw=31925,Cw=31987,Tw=31989,Iw=31990,Bw=32267,Lw=34128,Mw=34237,Ow=34550,Dw=35128,Nw=37515,Pw=37516,Fw=38172,Uw=38173,$w=38383,Kw=39e3,zw=39001,Hw=39002,qw=39003,Ww=39004,jw=39089,Vw=39092,Gw=39701;function Yw(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),i=t[`#${r}`];if(i&&!e.tags.find(([s,o])=>s===n.slice(1)&&i.indexOf(o)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function jf(t,e){for(let n=0;n<t.length;n++)if(Yw(t[n],e))return!0;return!1}var Zw={};rt(Zw,{getHex64:()=>gc,getInt:()=>Vf,getSubscriptionId:()=>Xw,matchEventId:()=>Jw,matchEventKind:()=>e0,matchEventPubkey:()=>Qw});function gc(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 Vf(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 Xw(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 Jw(t,e){return e===gc(t,"id")}function Qw(t,e){return e===gc(t,"pubkey")}function e0(t,e){return e===Vf(t,"kind")}var t0={};rt(t0,{makeAuthEvent:()=>n0});function n0(t,e){return{kind:qf,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var r0;try{r0=WebSocket}catch{}new TextEncoder;var i0;try{i0=WebSocket}catch{}var Wn={};rt(Wn,{BECH32_REGEX:()=>Gf,Bech32MaxSize:()=>mc,NostrTypeGuard:()=>s0,decode:()=>zs,decodeNostrURI:()=>a0,encodeBytes:()=>qs,naddrEncode:()=>d0,neventEncode:()=>h0,noteEncode:()=>l0,nprofileEncode:()=>f0,npubEncode:()=>u0,nsecEncode:()=>c0});var s0={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||"")},mc=5e3,Gf=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function o0(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 a0(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),zs(t)}catch{return{type:"invalid",data:null}}}function zs(t){let{prefix:e,words:n}=Ur.decode(t,mc),r=new Uint8Array(Ur.fromWords(n));switch(e){case"nprofile":{let i=Fo(r);if(!i[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(i[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:Je(i[0][0]),relays:i[1]?i[1].map(s=>En.decode(s)):[]}}}case"nevent":{let i=Fo(r);if(!i[0]?.[0])throw new Error("missing TLV 0 for nevent");if(i[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(i[2]&&i[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(i[3]&&i[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:Je(i[0][0]),relays:i[1]?i[1].map(s=>En.decode(s)):[],author:i[2]?.[0]?Je(i[2][0]):void 0,kind:i[3]?.[0]?parseInt(Je(i[3][0]),16):void 0}}}case"naddr":{let i=Fo(r);if(!i[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!i[2]?.[0])throw new Error("missing TLV 2 for naddr");if(i[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!i[3]?.[0])throw new Error("missing TLV 3 for naddr");if(i[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:En.decode(i[0][0]),pubkey:Je
1(i[2][0]),kind:parseInt(Je(i[3][0]),16),relays:i[1]?i[1].map(s=>En.decode(s)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:Je(r)};default:throw new Error(`unknown prefix ${e}`)}}function Fo(t){let e={},n=t;for(;n.length>0;){if(n.length<2)throw new Error("not enough data to read TLV");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 c0(t){return qs("nsec",t)}function u0(t){return qs("npub",nt(t))}function l0(t){return qs("note",nt(t))}function Hs(t,e){let n=Ur.toWords(e);return Ur.encode(t,n,mc)}function qs(t,e){return Hs(t,e)}function f0(t){let e=wc({0:[nt(t.pubkey)],1:(t.relays||[]).map(n=>Kt.encode(n))});return Hs("nprofile",e)}function h0(t){let e;t.kind!==void 0&&(e=o0(t.kind));let n=wc({0:[nt(t.id)],1:(t.relays||[]).map(r=>Kt.encode(r)),2:t.author?[nt(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return Hs("nevent",n)}function d0(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let n=wc({0:[Kt.encode(t.identifier)],1:(t.relays||[]).map(r=>Kt.encode(r)),2:[nt(t.pubkey)],3:[new Uint8Array(e)]});return Hs("naddr",n)}function wc(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)})}),St(...e)}var p0={};rt(p0,{decrypt:()=>y0,encrypt:()=>Yf});function Yf(t,e,n){const r=t instanceof Uint8Array?t:nt(t),i=Qa.getSharedSecret(r,nt("02"+e)),s=Zf(i);let o=Uint8Array.from(zr(16)),c=Kt.encode(n),u=Tf(s,o).encrypt(c),f=qn.encode(new Uint8Array(u)),p=qn.encode(new Uint8Array(o.buffer));return`${f}?iv=${p}`}function y0(t,e,n){const r=t instanceof Uint8Array?t:nt(t);let[i,s]=n.split("?iv="),o=Qa.getSharedSecret(r,nt("02"+e)),c=Zf(o),u=qn.decode(s),f=qn.decode(i),p=Tf(c,u).decrypt(f);return En.decode(p)}function Zf(t){return t.slice(1,33)}var vc={};rt(vc,{NIP05_REGEX:()=>bc,isNip05:()=>g0,isValid:()=>v0,queryProfile:()=>Xf,searchDomain:()=>w0,useFetchImplementation:()=>m0});var bc=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,g0=t=>bc.test(t||""),Ws;try{Ws=fetch}catch{}function m0(t){Ws=t}async function w0(t,e=""){try{const n=`https://${t}/.well-known/nostr.json?name=${e}`,r=await Ws(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function Xf(t){const e=t.match(bc);if(!e)return null;const[,n="_",r]=e;try{const i=`https://${r}/.well-known/nostr.json?name=${n}`,s=await Ws(i,{redirect:"manual"});if(s.status!==200)throw Error("Wrong response code");const o=await s.json(),c=o.names[n];return c?{pubkey:c,relays:o.relays?.[c]}:null}catch{return null}}async function v0(t,e){const n=await Xf(e);return n?n.pubkey===t:!1}var b0={};rt(b0,{parse:()=>E0});function E0(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]&&Bt(s[1])){const[o,c,u,f,p]=s,d={id:c,relays:u?[u]:[],author:p&&Bt(p)?p:void 0};if(f==="root"){e.root=d;continue}if(f==="reply"){e.reply=d;continue}if(f==="mention"){e.mentions.push(d);continue}n?r=d:n=d,e.mentions.push(d);continue}if(s[0]==="q"&&s[1]&&Bt(s[1])){const[o,c,u]=s;e.quotes.push({id:c,relays:u?[u]:[]})}if(s[0]==="p"&&s[1]&&Bt(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=>{i.relays?.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 x0={};rt(x0,{fetchRelayInformation:()=>k0,useFetchImplementation:()=>_0});var Jf;try{Jf=fetch}catch{}function _0(t){Jf=t}async function k0(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var S0={};rt(S0,{getPow:()=>A0,minePow:()=>C0});function A0(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 R0(t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];if(r===0)e+=8;else{e+=Math.clz32(r)-24;break}}return e}function C0(t,e){let n=0;
1const r=t,i=["nonce",n.toString(),e.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString();const o=Vt(Kt.encode(JSON.stringify([0,r.pubkey,r.created_at,r.kind,r.tags,r.content])));if(R0(o)>=e){r.id=Je(o);break}}return r}var T0={};rt(T0,{unwrapEvent:()=>$0,unwrapManyEvents:()=>K0,wrapEvent:()=>fh,wrapManyEvents:()=>U0});var I0={};rt(I0,{createRumor:()=>ah,createSeal:()=>ch,createWrap:()=>uh,unwrapEvent:()=>Cc,unwrapManyEvents:()=>lh,wrapEvent:()=>Rs,wrapManyEvents:()=>P0});var B0={};rt(B0,{decrypt:()=>Rc,encrypt:()=>Ac,getConversationKey:()=>kc,v2:()=>D0});var Ec=1,xc=4294967295,_c=65536;function kc(t,e){const n=Qa.getSharedSecret(t,nt("02"+e)).subarray(1,33);return xy(Vt,n,Kt.encode("nip44-v2"))}function Qf(t,e){const n=_y(Vt,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Sc(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;const e=2**(Math.floor(Math.log2(t-1))+1),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function L0(t){if(!Number.isSafeInteger(t)||t<Ec||t>65535)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 M0(t){if(!Number.isSafeInteger(t)||t<_c||t>xc)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");const e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function eh(t){const e=Kt.encode(t),n=e.length;if(n<Ec||n>xc)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");const r=n>=_c?St(new Uint8Array([0,0]),M0(n)):L0(n),i=new Uint8Array(Sc(n)-n);return St(r,e,i)}function th(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0);let r,i;if(n===0){if(r=e.getUint32(2),r<_c)throw new Error("invalid padding");i=6}else r=n,i=2;const s=t.subarray(i,i+r);if(r<Ec||r>xc||s.length!==r||t.length!==i+Sc(r))throw new Error("invalid padding");return En.decode(s)}function nh(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=St(n,e);return Ai(Vt,t,r)}function O0(t){if(typeof t!="string")throw new Error("payload must be a valid string");const e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=qn.decode(t)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99)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 Ac(t,e,n=zr(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=Qf(e,n),o=eh(t),c=Lf(r,i,o),u=nh(s,c,n);return qn.encode(St(new Uint8Array([2]),n,c,u))}function Rc(t,e){const{nonce:n,ciphertext:r,mac:i}=O0(t),{chacha_key:s,chacha_nonce:o,hmac_key:c}=Qf(e,n),u=nh(c,r,n);if(!ty(u,i))throw new Error("invalid MAC");const f=Lf(s,o,r);return th(f)}var D0={utils:{getConversationKey:kc,calcPaddedLen:Sc,pad:eh,unpad:th},encrypt:Ac,decrypt:Rc},N0=2880*60,rh=()=>Math.round(Date.now()/1e3),ih=()=>Math.round(rh()-Math.random()*N0),sh=(t,e)=>kc(t,e),oh=(t,e,n)=>Ac(JSON.stringify(t),sh(e,n)),Pu=(t,e)=>JSON.parse(Rc(t.content,sh(e,t.pubkey)));function ah(t,e){const n={created_at:rh(),content:"",tags:[],...t,pubkey:uc(e)};return n.id=Dr(n),n}function ch(t,e,n){return ln({kind:Nf,content:oh(t,e,n),created_at:ih(),tags:[]},e)}function uh(t,e){const n=My();return ln({kind:Hf,content:oh(t,n,e),created_at:ih(),tags:[["p",e]]},n)}function Rs(t,e,n){const r=ah(t,e),i=ch(r,e,n);return uh(i,n)}function P0(t,e,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");const r=uc(e),i=[Rs(t,e,r)];return n.forEach(s=>{i.push(Rs(t,e,s))}),i}function Cc(t,e){const n=Pu(t,e);return Pu(n,e)}function lh(t,e){let n=[];return t.forEach(r=>{n.push(Cc(r,e))}),n.sort((r,i)=>r.created_at-i.created_at),n}function F0(t,e,n,r){const i={created_at:Math.ceil(Date.now()/1e3),kind:Pf,tags:[],content:e};
1return(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 fh(t,e,n,r,i){const s=F0(e,n,r,i);return Rs(s,t,e.publicKey)}function U0(t,e,n,r,i){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:uc(t)},...e].map(o=>fh(t,o,n,r,i))}var $0=Cc,K0=lh,z0={};rt(z0,{finishRepostEvent:()=>H0,getRepostedEvent:()=>q0,getRepostedEventPointer:()=>hh});function H0(t,e,n,r){let i;const s=[...t.tags??[],["e",e.id,n],["p",e.pubkey]];return e.kind===Df?i=hc:(i=pc,s.push(["k",String(e.kind)])),ln({kind:i,tags:s,content:t.content===""||e.tags?.find(o=>o[0]==="-")?"":JSON.stringify(e),created_at:t.created_at},r)}function hh(t){if(![hc,pc].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?.[2]].filter(r=>typeof r=="string"),author:n?.[1]}}function q0(t,{skipVerification:e}={}){const n=hh(t);if(n===void 0||t.content==="")return;let r;try{r=JSON.parse(t.content)}catch{return}if(r.id===n.id&&!(!e&&!Hr(r)))return r}var W0={};rt(W0,{NOSTR_URI_REGEX:()=>Tc,parse:()=>V0,test:()=>j0});var Tc=new RegExp(`nostr:(${Gf.source})`);function j0(t){return typeof t=="string"&&new RegExp(`^${Tc.source}$`).test(t)}function V0(t){const e=t.match(new RegExp(`^${Tc.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:zs(e[1])}}var G0={};rt(G0,{parse:()=>Z0});function Fu(t){if(t)return/^\d+$/.test(t)?parseInt(t,10):t}function dh(t,e){const n=t.indexOf(":"),r=t.indexOf(":",n+1);if(n===-1||r===-1)return;const i=parseInt(t.slice(0,n),10);if(Number.isNaN(i))return;const s=t.slice(n+1,r);if(Bt(s))return{kind:i,pubkey:s,identifier:t.slice(r+1),relays:e?[e]:[]}}function Uu(t){switch(t[0]){case"E":case"e":return!t[1]||!Bt(t[1])?void 0:{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&Bt(t[3])?t[3]:void 0};case"A":case"a":return t[1]?dh(t[1],t[2]):void 0;case"I":case"i":return t[1]?{value:t[1],hint:t[2]}:void 0}}function Y0(t){if(t[1]){if(t[1].includes(":"))return dh(t[1],t[2]);if(Bt(t[1]))return{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&Bt(t[3])?t[3]:void 0}}}function $u(t){return t.findLast(e=>e.tagName==="A"||e.tagName==="a")?.pointer||t.findLast(e=>e.tagName==="I"||e.tagName==="i")?.pointer||t.findLast(e=>e.tagName==="E"||e.tagName==="e")?.pointer}function Uo(t,e){if(!t||!("id"in t)||!t.author)return;const n=e.find(r=>r.pubkey===t.author);!n||!n.relays||(t.relays||(t.relays=[]),n.relays.forEach(r=>{t.relays.indexOf(r)===-1&&t.relays.push(r)}),n.relays=t.relays)}function Z0(t){const e={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},n=[],r=[];for(const i of t.tags){if((i[0]==="E"||i[0]==="A"||i[0]==="I")&&i[1]){const s=Uu(i);s&&n.push({tagName:i[0],pointer:s});continue}if((i[0]==="e"||i[0]==="a"||i[0]==="i")&&i[1]){const s=Uu(i);s&&r.push({tagName:i[0],pointer:s});continue}if(i[0]==="K"){e.rootKind=Fu(i[1]);continue}if(i[0]==="k"){e.replyKind=Fu(i[1]);continue}if(i[0]==="q"){const s=Y0(i);s&&e.quotes.push(s);continue}(i[0]==="P"||i[0]==="p")&&i[1]&&Bt(i[1])&&e.profiles.push({pubkey:i[1],relays:i[2]?[i[2]]:[]})}return e.root=$u(n),e.reply=$u(r),Uo(e.root,e.profiles),Uo(e.reply,e.profiles),e.quotes.forEach(i=>Uo(i,e.profiles)),e}var X0={};rt(X0,{finishReactionEvent:()=>J0,getReactedEventPointer:()=>Q0});function J0(t,e,n){const r=e.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return ln({...t,kind:dc,tags:[...t.tags??[],...r,["e",e.id],["p",e.pubkey]],content:t.content??"+"},n)}function Q0(t){if(t.kind!==dc)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 ev={};rt(ev,{parse:()=>nv});var $o=/\W/m,Ku=/[^\w\/] |[^\w\/]$|$|,| /m,tv=42;function*nv(t){let e=[];
1if(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].match($o)){const c=t.slice(o+1,o+tv).match($o),u=c?o+1+c.index:n;yield{type:"text",text:t.slice(r,o)},yield{type:"hashtag",value:t.slice(o+1,u)},i=u,r=i;continue e}i=o+1;continue e}if(t.slice(s-5,s)==="nostr"){const c=t.slice(s+60).match($o),u=c?s+60+c.index:n;try{let f,{data:p,type:d}=zs(t.slice(s+1,u));switch(d){case"npub":f={pubkey:p};break;case"note":f={id:p};break;case"nsec":i=u+1;continue;default:f=p}r!==s-5&&(yield{type:"text",text:t.slice(r,s-5)}),yield{type:"reference",pointer:f},i=u,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(Ku),u=c?s+4+c.index:n,f=t[s-1]==="s"?5:4;try{let p=new URL(t.slice(s-f,u));if(p.hostname.indexOf(".")===-1)throw new Error("invalid url");if(r!==s-f&&(yield{type:"text",text:t.slice(r,s-f)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(p.pathname)){yield{type:"image",url:p.toString()},i=u,r=i;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(p.pathname)){yield{type:"video",url:p.toString()},i=u,r=i;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(p.pathname)){yield{type:"audio",url:p.toString()},i=u,r=i;continue e}yield{type:"url",url:p.toString()},i=u,r=i;continue e}catch{i=u+1;continue e}}else if(t.slice(s-3,s)==="wss"||t.slice(s-2,s)==="ws"){const c=t.slice(s+4).match(Ku),u=c?s+4+c.index:n,f=t[s-1]==="s"?3:2;try{let p=new URL(t.slice(s-f,u));if(p.hostname.indexOf(".")===-1)throw new Error("invalid ws url");r!==s-f&&(yield{type:"text",text:t.slice(r,s-f)}),yield{type:"relay",url:p.toString()},i=u,r=i;continue e}catch{i=u+1;continue e}}else{for(let c=0;c<e.length;c++){const u=e[c];if(t[s+u.shortcode.length+1]===":"&&t.slice(s+1,s+u.shortcode.length+1)===u.shortcode){r!==s&&(yield{type:"text",text:t.slice(r,s)}),yield u,i=s+u.shortcode.length+2,r=i;continue e}}i=s+1;continue e}}r!==n&&(yield{type:"text",text:t.slice(r)})}var rv={};rt(rv,{channelCreateEvent:()=>iv,channelHideMessageEvent:()=>av,channelMessageEvent:()=>ov,channelMetadataEvent:()=>sv,channelMuteUserEvent:()=>cv});var iv=(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 ln({kind:Ff,tags:[...t.tags??[]],content:n,created_at:t.created_at},e)},sv=(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 ln({kind:Uf,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},ov=(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"]),ln({kind:$f,tags:[...n,...t.tags??[]],content:t.content,created_at:t.created_at},e)},av=(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 ln({kind:Kf,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},cv=(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 ln({kind:zf,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:n,created_at:t.created_at},e)},uv={};rt(uv,{EMOJI_SHORTCODE_REGEX:()=>ph,matchAll:()=>lv,regex:()=>Ic,replaceAll:()=>fv});var ph=/:(\w+):/,Ic=()=>new RegExp(`\\B${ph.source}\\B`,"g");function*lv(t){const e=t.matchAll(Ic());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 fv(t,e){return t.replaceAll(Ic(),(n,r)=>e({shortcode:n,name:r}))}var hv={};rt(hv,{useFetchImplementation:()=>dv,validateGithub:()=>pv});var Bc;try{Bc=fetch}catch{}function dv(t){Bc=t}async function pv(t,e,n){try{return await(await Bc(`https://gist.github.com/${e}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch{return!1}}var yv={};rt(yv,{makeNwcRequestEvent:()=>mv,parseConnectionString:()=>gv});
1function gv(t){const{host:e,pathname:n,searchParams:r}=new URL(t),i=n||e,s=r.getAll("relay"),o=r.get("secret");if(!i||s.length===0||!o)throw new Error("invalid connection string");return{pubkey:i,relay:s[0],relays:s,secret:o}}async function mv(t,e,n){const i=Yf(e,t,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:Wf,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",t]]};return ln(s,e)}var wv={};rt(wv,{normalizeIdentifier:()=>vv});function vv(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 bv={};rt(bv,{getSatoshisAmountFromBolt11:()=>Av,getZapEndpoint:()=>xv,makeZapReceipt:()=>Sv,makeZapRequest:()=>_v,useFetchImplementation:()=>Ev,validateZapRequest:()=>kv});var Lc;try{Lc=fetch}catch{}function Ev(t){Lc=t}async function xv(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}=Ur.decode(n,1e3),c=Ur.fromWords(o);e=En.decode(c)}else return null;let s=await(await Lc(e)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function _v(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]),lc(t.event.kind)){const n=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(n)}else if(fc(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 kv(t){let e;try{e=JSON.parse(t)}catch{return"Invalid zap request JSON."}if(!cc(e))return"Zap request is not a valid Nostr event.";if(!Hr(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(!Bt(n[1]))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find(([s,o])=>s==="e"&&o);return r&&!Bt(r[1])?"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 Sv({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 Av(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 u=parseInt(r.substring(0,c));switch(i){case"m":return u*1e5;case"u":return u*100;case"n":return u/10;case"p":return u/1e4;default:return u*1e8}}var Rv={};rt(Rv,{Negentropy:()=>gh,NegentropyStorageVector:()=>Iv,NegentropySync:()=>Bv});var Ko=97,Nr=32,yh=16,or={Skip:0,Fingerprint:1,IdList:2},wn=class{_raw;length;constructor(t){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 wn&&(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 Qi(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 mn(t){if(t===0)return new wn(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 wn(new Uint8Array(e))}function Cv(t){return ds(t,1)[0]}function ds(t,e){if(t.length<e)throw Error("parse ends prematurely");return t.shiftN(e)}var Tv=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(Nr)}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),u=i.getUint32(o,!0),f=c;f+=e,f+=u,f>4294967295&&(n=1),r.setUint32(o,f&4294967295,!0),e=n,n=0}
1}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(Nr);e[0]=1,this.add(e)}getFingerprint(t){let e=new wn;return e.extend(this.buf),e.extend(mn(t)),Vt(e.unwrap()).subarray(0,yh)}},Iv=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");const n=nt(e);if(n.byteLength!==Nr)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(zo);for(let t=1;t<this.items.length;t++)if(zo(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=>zo(r,n)<0)}fingerprint(t,e){let n=new Tv;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}},gh=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(t,e=6e4){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 wn;return t.extend(new Uint8Array([Ko])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),Je(t.unwrap())}reconcile(t,e,n){const r=new wn(nt(t));this.lastTimestampIn=this.lastTimestampOut=0;let i=new wn;i.extend(new Uint8Array([Ko]));let s=Cv(r);if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(s!==Ko)throw Error("unsupported negentropy protocol version requested: "+(s-96));let o=this.storage.size(),c=this._bound(0),u=0,f=!1;for(;r.length!==0;){let p=new wn,d=()=>{f&&(f=!1,p.extend(this.encodeBound(c)),p.extend(mn(or.Skip)))},g=this.decodeBound(r),w=Qi(r),x=u,A=this.storage.findLowerBound(u,o,g);if(w===or.Skip)f=!0;else if(w===or.Fingerprint){let I=ds(r,yh),T=this.storage.fingerprint(x,A);mh(I,T)!==0?(d(),this.splitRange(x,A,g,p)):f=!0}else if(w===or.IdList){let I=Qi(r),T={};for(let te=0;te<I;te++){let ae=ds(r,Nr);T[Je(ae)]=ae}if(f=!0,this.storage.iterate(x,A,te=>{let ae=te.id;const Re=Je(ae);return T[Re]?delete T[Je(ae)]:e?.(Re),!0}),n)for(let te of Object.values(T))n(Je(te))}else throw Error("unexpected mode");if(this.exceededFrameSizeLimit(i.length+p.length)){let I=this.storage.fingerprint(A,o);i.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),i.extend(mn(or.Fingerprint)),i.extend(I);break}else i.extend(p);u=A,c=g}return i.length===1?null:Je(i.unwrap())}splitRange(t,e,n,r){let i=e-t,s=16;if(i<s*2)r.extend(this.encodeBound(n)),r.extend(mn(or.IdList)),r.extend(mn(i)),this.storage.iterate(t,e,o=>(r.extend(o.id),!0));else{let o=Math.floor(i/s),c=i%s,u=t;for(let f=0;f<s;f++){let p=o+(f<c?1:0),d=this.storage.fingerprint(u,u+p);u+=p;let g;if(u===e)g=n;else{let w,x;this.storage.iterate(u-1,u+1,(A,I)=>(I===u-1?w=A:x=A,!0)),g=this.getMinimalBound(w,x)}r.extend(this.encodeBound(g)),r.extend(mn(or.Fingerprint)),r.extend(d)}}}exceededFrameSizeLimit(t){return t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=Qi(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=Qi(t);if(n>Nr)throw Error("bound key too long");let r=ds(t,n);return{timestamp:e,id:r}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,mn(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,mn(t+1)}encodeBound(t){let e=new wn;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(mn(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<Nr&&r[s]===i[s];s++)n++;return this._bound(e.timestamp,e.id.subarray(0,n+1))}}};function mh(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 zo(t,e){return t.timestamp===e.timestamp?mh(t.id,e.id):t.timestamp-e.timestamp}var Bv=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(t,e,n,r={}){this.relay=t,this.storage=e,this.neg=new gh(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=>{switch(i[0]){case"NEG-MSG":{i.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${i}`);try{const s=this.neg.reconcile(i[2],this.onhave,this.onneed);s?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${s}"]`):(this.close(),r.onclose?.())}catch(s){console.error("negentropy reconcile error:",s),r?.onclose?.(`reconcile error: ${s}`)}break}case"NEG-CLOSE":{const s=i[2];console.warn("negentropy error:",s),r.onclose?.(s);break}case"NEG-ERR":r.onclose?.()}}}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()}},Lv={};rt(Lv,{getToken:()=>Mv,hashPayload:()=>Mc,unpackEventFromToken:()=>vh,validateEvent:()=>Sh,validateEventKind:()=>Eh,validateEventMethodTag:()=>_h,validateEventPayloadTag:()=>kh,validateEventTimestamp:()=>bh,validateEventUrlTag:()=>xh,validateToken:()=>Ov});var wh="Nostr ";async function Mv(t,e,n,r=!1,i){const s={kind:yc,tags:[["u",t],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",Mc(i)]);const o=await n(s);return(r?wh:"")+qn.encode(Kt.encode(JSON.stringify(o)))}async function Ov(t,e,n){const r=await vh(t).catch(s=>{throw s});
1return await Sh(r,e,n).catch(s=>{throw s})}async function vh(t){if(!t)throw new Error("Missing token");t=t.replace(wh,"");const e=En.decode(qn.decode(t));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function bh(t){return t.created_at?Math.round(new Date().getTime()/1e3)-t.created_at<60:!1}function Eh(t){return t.kind===yc}function xh(t,e){const n=t.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===e:!1}function _h(t,e){const n=t.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===e.toLowerCase():!1}function Mc(t){const e=Vt(Kt.encode(JSON.stringify(t)));return Je(e)}function kh(t,e){const n=t.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=Mc(e);return n.length>0&&n[1]===r}async function Sh(t,e,n,r){if(!Hr(t))throw new Error("Invalid nostr event, signature invalid");if(!Eh(t))throw new Error("Invalid nostr event, kind invalid");if(!bh(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!xh(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!_h(t,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!kh(t,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const Dv=new WeakSet;function Nv(t){const e=new WeakMap,n=Object.freeze({verifyEvent(r){e.delete(r);try{return e.set(r,Mr(r,t)),!0}catch{return!1}},admitEvent(r){const i=e.get(r);if(!i)throw Hn.validation("relay event was not admitted by the configured SimplePool boundary");return hf(i)}});return Dv.add(n),n}function Ah(t,e,n={}){const r=[...t].filter(s=>!Rh(s)).sort(Cs),i=new Map;for(const s of e){let o=0;for(const c of r){if(n.signal?.aborted)throw wa(n.signal.reason);if(s.limit!==void 0&&o>=s.limit)break;gf(s,c)&&(i.set(c.id,c),o++)}}return[...i.values()].sort(Cs).slice(0,n.limit)}function Cs(t,e){return e.created_at-t.created_at||t.id.localeCompare(e.id)}function Rh(t){const e=t.tags.find(n=>n[0]==="expiration")?.[1];return e!==void 0&&/^\d+$/.test(e)&&Number(e)<=Date.now()/1e3}function wa(t){return new DOMException(typeof t=="string"?t:"Nostr operation cancelled","AbortError")}function Ch(t){if(t.kind===0||t.kind===3||t.kind>=1e4&&t.kind<2e4)return{authors:[t.pubkey],kinds:[t.kind]};if(t.kind>=3e4&&t.kind<4e4){const e=t.tags.find(n=>n[0]==="d")?.[1]??"";return{authors:[t.pubkey],kinds:[t.kind],...e?{"#d":[e]}:{}}}}function pi(t){return Ch(t)?`${t.kind}:${t.pubkey}:${t.tags.find(e=>e[0]==="d")?.[1]??""}`:void 0}function zu(t,e){if(e.kind!==5||e.pubkey!==t.pubkey||e.created_at<t.created_at||t.kind===5)return!1;const n=pi(t);return e.tags.some(r=>r[0]==="e"&&r[1]===t.id||r[0]==="a"&&n!==void 0&&r[1]===n)}async function Pv(t,e){if(Rh(e))return"rejected";if(e.kind>=2e4&&e.kind<3e4)return"admitted";if((await t.query([{authors:[e.pubkey],kinds:[5],"#e":[e.id]},...pi(e)?[{authors:[e.pubkey],kinds:[5],"#a":[pi(e)]}]:[]])).some(i=>zu(e,i)))return"rejected";const r=Ch(e);if(r){const i=(await t.query([r])).filter(s=>pi(s)===pi(e));if(i.some(s=>Cs(s,e)<0))return"superseded";await t.delete(i.filter(s=>s.id!==e.id).map(s=>s.id))}if(e.kind===5){const i=[],s=e.tags.filter(c=>c[0]==="e"&&c[1]).map(c=>c[1]);s.length&&i.push({ids:s,authors:[e.pubkey]});for(const c of e.tags){if(c[0]!=="a"||!c[1])continue;const[u,f,...p]=c[1].split(":");f!==e.pubkey||!/^\d+$/.test(u)||i.push({kinds:[Number(u)],authors:[f],...Number(u)>=3e4&&p.join(":")?{"#d":[p.join(":")]}:{}})}const o=i.length?await t.query(i):[];await t.delete(o.filter(c=>zu(c,e)).map(c=>c.id))}return await t.put(e),"admitted"}class Fv{maxEvents;maxPending;events=new Map;pending=new Map;constructor(e=2e4,n=1e3){if(this.maxEvents=e,this.maxPending=n,!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(n)||n<1)throw new RangeError("Invalid event store bounds")}async query(e,n={}){return Ah(this.events.values(),e,n)}async put(e){if(!this.events.has(e.id)&&this.events.size>=this.maxEvents){const n=[...this.events.values()].filter(r=>r.kind!==5&&!this.pending.has(r.id)).sort(Cs).pop();if(!n)throw new Error("Event store retention capacity exhausted");this.events.delete(n.id)}this.events.set(e.id,structuredClone(e))}async delete(e){for(const n of e)this.events.delete(n)}async listPending(){return[...this.pending.values()].map(e=>structuredClone(e))}
1async putPending(e){if(!this.pending.has(e.event.id)&&this.pending.size>=this.maxPending)throw new Error("Outbox capacity exhausted");this.pending.set(e.event.id,structuredClone(e))}async deletePending(e){this.pending.delete(e)}}class Uv{buckets=new Map;memberships=new Map;add(e,n){const r=new Set(n.flatMap($v));this.memberships.set(e,r);for(const i of r){const s=this.buckets.get(i)??new Set;s.add(e),this.buckets.set(i,s)}}remove(e){for(const n of this.memberships.get(e)??[]){const r=this.buckets.get(n);r.delete(e),r.size||this.buckets.delete(n)}this.memberships.delete(e)}candidates(e){const n=["*",`id:${e.id}`,`author:${e.pubkey}`,`kind:${e.kind}`];for(const i of e.tags)i[0]&&i[1]&&n.push(`tag:${i[0]}:${i[1]}`);const r=new Set;for(const i of n)for(const s of this.buckets.get(i)??[])r.add(s);return r}}function $v(t){if(t.ids?.length&&t.ids.every(n=>n.length===64))return t.ids.map(n=>`id:${n}`);const e=Object.entries(t).filter(([n,r])=>n.startsWith("#")&&Array.isArray(r)&&r.length).sort(([,n],[,r])=>n.length-r.length)[0];return e?e[1].map(n=>`tag:${e[0].slice(1)}:${n}`):t.authors?.length&&t.authors.every(n=>n.length===64)?t.authors.map(n=>`author:${n}`):t.kinds?.length?t.kinds.map(n=>`kind:${n}`):["*"]}new TextDecoder("utf-8");new TextEncoder;function Ir(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}`)}}var Kv=22242;function zv(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),i=t[`#${r}`];if(i&&!e.tags.find(([s,o])=>s===n.slice(1)&&i.indexOf(o)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function Hv(t,e){for(let n=0;n<t.length;n++)if(zv(t[n],e))return!0;return!1}function qv(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 Wv(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 jv(t,e){return{kind:Kv,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var va=class extends Error{constructor(t,e){super(`Tried to send message '${t} on a closed connection to ${e}.`),this.name="SendingOnClosedConnection"}},Th=class{url;_connected=!1;onclose=null;onnotice=t=>console.debug(`NOTICE from ${this.url}: ${t}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleTimeout=0;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;idleTimeoutHandle;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(t,e){this.url=Ir(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,e.idleTimeout&&(this.idleTimeout=e.idleTimeout)}static async connect(t,e){const n=new Th(t,e);return await n.connect(e),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}clearIdleTimeout(){this.idleTimeoutHandle&&(clearTimeout(this.idleTimeoutHandle),this.idleTimeoutHandle=void 0)}scheduleIdleClose(){this.clearIdleTimeout(),this.idleTimeout>0&&(this.idleTimeoutHandle=setTimeout(()=>{this.ongoingOperations===0&&this.idleSince&&this.close()},this.idleTimeout))}async reconnect(){const t=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},t)}handleHardClose(t){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose
1=null),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(t))}async connect(t){let e;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{t?.timeout&&(e=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.reconnectAttempts===0&&(this.skipReconnection=!0),this.handleHardClose("relay connection timed out")},t.timeout)),t?.abort&&(t.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(i){clearTimeout(e),r(i);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(e),this._connected=!0;const i=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const s of this.openSubs.values()){if(s.eosed=!1,i)for(let o=0;o<s.filters.length;o++)s.lastEmitted&&(s.filters[o].since=s.lastEmitted+1);s.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(e),r("connection failed"),this.connectionPromise=void 0,this.reconnectAttempts===0&&(this.skipReconnection=!0),this.handleHardClose("relay connection failed")},this.ws.onclose=i=>{clearTimeout(e),r(i.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(t=>{this.ws.once("pong",()=>t(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((t,e)=>{if(!this.connectionPromise)return e(new Error(`no connection to ${this.url}, can't ping`));try{const n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{t(!0),n.close()},onclose(){t(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){e(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(e=>setTimeout(()=>e(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(t){if(!this.connectionPromise)throw new va(t,this.url);this.connectionPromise.then(()=>{this.ws?.send(t)})}async auth(t){const e=this.challenge;if(!e)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let i=await t(jv(this.url,e)),s=setTimeout(()=>{let o=this.openEventPublishes.get(i.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(i.id))},this.publishTimeout);this.openEventPublishes.set(i.id,{resolve:n,reject:r,timeout:s}),this.send('["AUTH",'+JSON.stringify(i)+"]")}catch(i){console.warn("subscribe auth function failed:",i)}}),this.authPromise)}async publish(t){this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++;const e=new Promise((n,r)=>{const i=setTimeout(()=>{const s=this.openEventPublishes.get(t.id);s&&(s.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))},this.publishTimeout);this.openEventPublishes.set(t.id,{resolve:n,reject:r,timeout:i})});try{await this.send('["EVENT",'+JSON.stringify(t)+"]")}catch(n){const r=this.openEventPublishes.get(t.id);r&&(r.reject(n),this.openEventPublishes.delete(t.id))}return this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now(),this.scheduleIdleClose()),e}async count(t,e){return(await this.countWithHLL(t,e)).count}async countWithHLL(t,e){this.serial++;const n=e?.id||"count:"+this.serial,r=new Promise((i,s)=>{this.openCountRequests.set(n,{resolve:i,reject:s})});try{await this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1))}catch(i){const s=this.openCountRequests.get(n);s&&(s.reject(i),this.openCountRequests.delete(n))}return r}subscribe(t,e){e.label!=="<forced-ping>"&&(this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++);const n=this.prepareSubscription(t,e);return n.fire(),e.abort&&(e.abort.onabort=()=>n.close(String(e.abort.reason||"<aborted>"))),n}prepareSubscription(t,e){this.serial++;const n=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new Vv(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.onclose?.(),this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose
1=null,this.ws.readyState!==this._WebSocket.CLOSING&&this.ws.readyState!==this._WebSocket.CLOSED&&this.ws.close())}_onmessage(t){const e=t.data;if(!e)return;const n=Wv(e);if(n){const r=this.openSubs.get(n);if(!r)return;const i=qv(e,"id"),s=r.alreadyHaveEvent?.(i);if(r.receivedEvent?.(this,i),s)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{const i=this.openSubs.get(r[1]),s=r[2];Hv(i.filters,s)&&this.verifyEvent(s,this.url)?i.onevent(s):i.oninvalidevent?.(s),(!i.lastEmitted||i.lastEmitted<s.created_at)&&(i.lastEmitted=s.created_at);return}case"COUNT":{const i=r[1],s=r[2],o=this.openCountRequests.get(i);o&&(o.resolve(s),this.openCountRequests.delete(i));return}case"EOSE":{const i=this.openSubs.get(r[1]);if(!i)return;i.receivedEose();return}case"OK":{const i=r[1],s=r[2],o=r[3],c=this.openEventPublishes.get(i);c&&(clearTimeout(c.timeout),s?c.resolve(o):c.reject(new Error(o)),this.openEventPublishes.delete(i));return}case"CLOSED":{const i=r[1],s=this.openSubs.get(i);if(!s){const o=this.openCountRequests.get(i);o&&(o.reject(new Error(r[2])),this.openCountRequests.delete(i));return}s.closed=!0,s.close(r[2]);return}case"NOTICE":{this.onnotice(r[1]);return}case"AUTH":{this.challenge=r[1],this.onauth&&this.auth(this.onauth).catch(i=>{if(!(i instanceof va))throw i});return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{const[i,s,o]=JSON.parse(e);console.warn(`[nostr] relay ${this.url} error processing message:`,r,o)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},Vv=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(t,e,n,r){if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(i=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,i)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof va))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now(),this.relay.scheduleIdleClose()),this.onclose?.(t)}},xn=256,Gv=xn*2;new TextEncoder;function Yv(t,e){switch(e){case"reactions":return{"#e":[t],kinds:[7]};case"reposts":return{"#e":[t],kinds:[6]};case"quotes":return{"#q":[t],kinds:[1,1111]};case"replies":return{"#e":[t],kinds:[1]};case"comments":return{"#E":[t],kinds:[1111]};case"followers":return{"#p":[t],kinds:[3]}}}function Zv(){return new Uint8Array(xn)}function Xv(t){if(t.length!==Gv||!/^[0-9a-f]+$/.test(t))return;const e=new Uint8Array(xn);for(let n=0;n<xn;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Jv(t){if(t.length!==xn)throw new Error(`invalid number of registers ${t.length}`);let e="";for(let n=0;n<xn;n++)e+=t[n].toString(16).padStart(2,"0");return e}function Qv(t,e){if(t.length===0&&(t=Zv()),t.length!==xn)throw new Error(`invalid number of registers ${t.length}`);if(e.length!==xn)throw new Error(`invalid number of registers ${e.length}`);for(let n=0;n<xn;n++)e[n]>t[n]&&(t[n]=e[n]);return t}var eb=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;idleTimeout=2e4;automaticallyAuth;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(t){this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,t.idleTimeout&&(this.idleTimeout=t.idleTimeout),this.automaticallyAuth=t.automaticallyAuth,this.onRelayConnectionFailure=t.onRelayConnectionFailure,this.onRelayConnectionSuccess=t.onRelayConnectionSuccess,this.allowConnectingToRelay=t.allowConnectingToRelay,this.maxWaitForConnection=t.maxWaitForConnection||3e3}async ensureRelay(t,e){t=Ir(t);let n=this.relays.get(t);
1if(n||(n=new Th(t,{verifyEvent:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect,idleTimeout:this.idleTimeout}),n.onclose=()=>{this.relays.delete(t)},this.relays.set(t,n)),this.automaticallyAuth){const r=this.automaticallyAuth(t);r&&(n.onauth=r)}try{await n.connect({timeout:e?.connectionTimeout,abort:e?.abort})}catch(r){throw this.relays.delete(t),r}return n}close(t){t.map(Ir).forEach(e=>{this.relays.get(e)?.close(),this.relays.delete(e)})}subscribe(t,e,n){const r=[],i=[];for(let s=0;s<t.length;s++){const o=Ir(t[s]);r.find(c=>c.url===o)||i.indexOf(o)===-1&&(i.push(o),r.push({url:o,filter:e}))}return this.subscribeMap(r,n)}subscribeMany(t,e,n){return this.subscribe(t,e,n)}subscribeMap(t,e){const n=new Map;for(const g of t){const{url:w,filter:x}=g;n.has(w)||n.set(w,[]),n.get(w).push(x)}const r=Array.from(n.entries()).map(([g,w])=>({url:g,filters:w}));this.trackRelays&&(e.receivedEvent=(g,w)=>{let x=this.seenOn.get(w);x||(x=new Set,this.seenOn.set(w,x)),x.add(g)});const i=new Set,s=[],o=[];let c=g=>{o[g]||(o[g]=!0,o.filter(w=>w).length===r.length&&(e.oneose?.(),c=()=>{}))};const u=[];let f=(g,w,x)=>{u[g]||(c(g),u[g]={url:w,reason:x},u.filter(A=>A).length===r.length&&(e.onclose?.(u),f=()=>{}))};const p=g=>{if(e.alreadyHaveEvent?.(g))return!0;const w=i.has(g);return i.add(g),w},d=Promise.all(r.map(async({url:g,filters:w},x)=>{if(this.allowConnectingToRelay?.(g,["read",w])===!1){f(x,g,"connection skipped by allowConnectingToRelay");return}let A;try{A=await this.ensureRelay(g,{connectionTimeout:this.maxWaitForConnection<(e.maxWait||0)?Math.max(e.maxWait*.8,e.maxWait-1e3):this.maxWaitForConnection,abort:e.abort})}catch(T){this.onRelayConnectionFailure?.(g),f(x,g,T?.message||String(T));return}this.onRelayConnectionSuccess?.(g);let I=A.subscribe(w,{...e,oneose:()=>c(x),onclose:T=>{T.startsWith("auth-required: ")&&e.onauth?A.auth(e.onauth).then(()=>{A.subscribe(w,{...e,oneose:()=>c(x),onclose:te=>{f(x,g,te)},alreadyHaveEvent:p,eoseTimeout:e.maxWait,abort:e.abort})}).catch(te=>{f(x,g,`auth was required and attempted, but failed with: ${te}`)}):f(x,g,T)},alreadyHaveEvent:p,eoseTimeout:e.maxWait,abort:e.abort});s.push(I)}));return{async close(g){await d,s.forEach(w=>{w.close(g)})}}}subscribeEose(t,e,n){let r;return r=this.subscribe(t,e,{...n,oneose(){const i="closed automatically on eose";r?r.close(i):n.onclose?.(t.map(s=>({url:s,reason:i})))}}),r}subscribeManyEose(t,e,n){return this.subscribeEose(t,e,n)}async querySync(t,e,n){return new Promise(async r=>{const i=[];this.subscribeEose(t,e,{...n,onevent(s){i.push(s)},onclose(s){r(i)}})})}async get(t,e,n){e.limit=1;const r=await this.querySync(t,e,n);return r.sort((i,s)=>s.created_at-i.created_at),r[0]||null}async countMany(t,e,n,r){const i=Yv(e,n),s=[];for(let f=0;f<t.length;f++){const p=Ir(t[f]);s.indexOf(p)===-1&&s.push(p)}const o=await Promise.all(s.map(async f=>{if(this.allowConnectingToRelay?.(f,["read",[i]])===!1)return null;let p;try{p=await this.ensureRelay(f,{connectionTimeout:this.maxWaitForConnection<(r?.maxWait||0)?Math.max(r.maxWait*.8,r.maxWait-1e3):this.maxWaitForConnection,abort:r?.abort})}catch{return this.onRelayConnectionFailure?.(f),null}return this.onRelayConnectionSuccess?.(f),p.countWithHLL([i],{id:r?.id}).catch(()=>null)}));let c=0,u;for(const f of o){if(!f||(f.count>c&&(c=f.count),!f.hll||f.hll.length!==512))continue;const p=Xv(f.hll);p&&(u=Qv(u||new Uint8Array(0),p))}return u?{count:c,hll:Jv(u)}:{count:c}}publish(t,e,n){return t.map(Ir).map(async(r,i,s)=>{if(s.indexOf(r)!==i)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(r,["write",e])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(c){return this.onRelayConnectionFailure?.(r),"connection failure: "+String(c)}return o.publish(e).catch(async c=>{if(c instanceof Error&&c.message.startsWith("auth-required: ")&&n?.onauth)return await o.auth(n.onauth),o.publish(e);throw c}).then(c=>{if(this.trackRelays){let u=this.seenOn.get(e.id);u||(u=new Set,this.seenOn.set(e.id,u)),u.add(o)}return c})})}listConnectionStatus(){const t=new Map;return this.relays.forEach((e,n)=>t.set(n,e.connected)),t}destroy(){this.relays.forEach(t=>t.close()),this.relays=new Map}pruneIdleRelays(t=1e4){const e=[];for(const[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=t&&(this.relays.delete(n),e.push(n),r.close());return e}};class tb{options;pool;boundary;relays;batches=new Set;pending=[];timer;stopped=!1;serial=0;maxFilters;maxBytes;constructor(e){this.options=e,this.boundary=Nv(nb(e.verifyEvent??ff)),this.relays=e
1s(e.relays??[]),this.maxFilters=Wu(e.maxFiltersPerBatch,20),this.maxBytes=Wu(e.maxFilterBytesPerBatch,32768),this.pool=new eb({maxWaitForConnection:e.historyTimeoutMs??3e3,websocketImplementation:e.websocketImplementation,verifyEvent:n=>this.boundary.verifyEvent(n),enableReconnect:!1,automaticallyAuth:e.signAuthEvent?n=>async r=>{const i=await e.signAuthEvent(n,r);if(!this.boundary.verifyEvent(i))throw new Error("Invalid relay authentication event");return this.boundary.admitEvent(i)}:void 0})}urls(){return[...this.relays]}stats(){const e=this.pool.listConnectionStatus();return this.relays.map(n=>({url:n,connected:e.get(n)??!1}))}count(){return[...this.batches].reduce((e,n)=>e+n.links.size,0)}subscribe(e,n,r,i,s=!1){if(this.stopped)throw new Error("Nostr runtime is closed");if(e.length>this.maxFilters||qu(e)>this.maxBytes)throw new RangeError("Nostr subscription exceeds filter batch bounds");const o={isolated:s,relays:i===void 0?void 0:es(i),filters:structuredClone(e),event:n,state:r,closed:!1};return this.pending.push(o),this.timer||(this.timer=setTimeout(()=>this.flush(),this.options.batchWindowMs??10)),{close:()=>{if(o.closed)return;o.closed=!0;const c=o.batch;if(c){if(c.entries.every(u=>u.closed)){this.closeBatch(c);return}c.reopenTimer||(c.reopenTimer=setTimeout(()=>{c.reopenTimer=void 0,c.closed||this.reopen(c)},this.options.batchWindowMs??10))}}}}setRelays(e){const n=es(e),r=this.relays.filter(s=>!n.includes(s));this.relays=n;for(const s of this.batches)s.entries[0]?.relays===void 0&&this.reopen(s);const i=new Set([...this.batches].flatMap(s=>[...s.entries[0]?.relays??[]]));this.pool.close(r.filter(s=>!i.has(s)))}publishAttempts(e,n){return(n===void 0?this.relays:es(n)).map(r=>({id:r,result:this.publishOne(r,e)}))}async publishOne(e,n){const r=this.options.publishTimeoutMs??5e3,i=await this.pool.ensureRelay(e,{connectionTimeout:r});i.publishTimeout=r;try{await i.publish(n)}catch(s){if(!ju(s).startsWith("auth-required:")||!this.options.signAuthEvent)throw s;await i.auth(async o=>Mr(await this.options.signAuthEvent(e,o))),await i.publish(n)}}close(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.pending=[];for(const e of[...this.batches])this.closeBatch(e);this.pool.destroy()}flush(){this.timer=void 0;const e=this.pending.filter(r=>!r.closed);this.pending=[];let n=[];for(const r of e){const i=Hu([...n,r]);n.length&&(r.isolated||n[0].isolated||JSON.stringify(n[0].relays)!==JSON.stringify(r.relays)||i.length>this.maxFilters||qu(i)>this.maxBytes)&&(this.startBatch(n),n=[]),n.push(r)}n.length&&this.startBatch(n)}startBatch(e){const n={entries:e,links:new Map,closed:!1};for(const r of e)r.batch=n;this.batches.add(n),this.reopen(n)}reopen(e){e.reopenTimer&&clearTimeout(e.reopenTimer),e.reopenTimer=void 0;for(const n of e.links.values())this.closeLink(n);if(e.links.clear(),e.entries=e.entries.filter(n=>!n.closed),!e.entries.length){this.closeBatch(e);return}for(const n of e.entries[0].relays??this.relays){const r={generation:0,attempts:0,eosed:!1,latest:new Map};e.links.set(n,r),this.connect(e,n,r)}}async connect(e,n,r){const i=++r.generation,s=()=>!this.stopped&&!e.closed&&i===r.generation;try{const o=await this.pool.ensureRelay(n);if(!s())return;const c=Hu(e.entries),u=c.map(p=>{const d=r.latest.get(ba(p));return r.eosed&&d!==void 0?{...p,since:Math.max(p.since??0,d-1)}:structuredClone(p)}),f=o.prepareSubscription(u,{id:`pubsub-${++this.serial}`,onevent:p=>{if(!s())return;const d=this.boundary.admitEvent(p);for(const g of c)if(ks([g],d)){const w=ba(g);r.latest.set(w,Math.max(r.latest.get(w)??0,d.created_at))}for(const g of e.entries)!g.closed&&ks(g.filters,d)&&g.event(d,n)},oneose:()=>{if(s()){r.eosed=!0,r.attempts=0;for(const p of e.entries)p.closed||p.state(n,!0)}},onclose:p=>{s()&&this.retry(e,n,r,p)}});o.ongoingOperations++,o.idleSince=void 0,r.close=()=>{o.openSubs.has(f.id)&&f.close("Nostr runtime subscription closed")},await o.send(JSON.stringify(["REQ",f.id,...u]))}catch(o){s()&&this.retry(e,n,r,ju(o))}}retry(e,n,r,i){this.closeLink(r);for(const o of e.entries)o.closed||o.state(n,!1,i);const s=Math.min(3e4,(this.options.reconnectDelayMs??500)*2**Math.min(r.attempts++,6));r.timer=setTimeout(()=>{r.timer=void 0,this.connect(e,n,r)},s)}closeLink(e){e.generation++,e.timer&&clearTimeout(e.timer),e.timer=void 0;const n=e.close;e.close=void 0,n?.()}closeBatch(e){e.closed=!0,e.reopenTimer&&clearTimeout(e.reopenTimer),e.reopenTimer=void 0;for(const n of e.links.values())this.closeLink(n);e.links.clear(),this.batches.delete(e)}}function Hu(t){const e=new Map;for(const n of t)if(!n.closed)for(const r of n.filters)e.set(ba(r),r);return[...e.values()]}function ba(t){return JSON.stringify(Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n))))}function qu(t){return new TextEncoder().encode(JSON.stringify(t)).byteLength}function Wu(t,e){const n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new RangeError("Invalid runtime bounds");return n}function es(t){return[...new Set(t.map(e=>{const n=new URL(e);if(n.protocol!=="ws:"&&n.protocol!=="wss:")throw new Error("Nostr relay must use ws or wss");return n.toString()}))]}function ju(t){return t instanceof Error?t.message:String(t)}function nb(t){const e=new Map;let n=0;return r=>{const i=JSON.stringify([r.id,r.pubkey,r.sig,r.kind,r.created_at,r.tags,r.content]);if(e.get(r.id)===i)return!0;
1if(!t(r))return!1;const s=e.get(r.id);for(s&&(n-=s.length*2),e.delete(r.id),e.set(r.id,i),n+=i.length*2;e.size>2048||n>8*1024*1024;){const o=e.keys().next().value;n-=e.get(o).length*2,e.delete(o)}return!0}}class rb{options;store;relays;sources=new Map;listeners=new Set;interests=new Uv;incoming=new Map;publishing=new Map;writes=Promise.resolve();stopped=!1;retryTimer;retrying=!1;counters={receivedEvents:0,deliveredEvents:0,duplicateEvents:0,verificationFailures:0};constructor(e={}){this.options=e,this.store=e.store??new Fv,this.relays=new tb(e);for(const n of e.sources??[])this.sources.set(n.id,n);this.scheduleRetry()}subscribe(e,n,r={}){if(this.ensureOpen(),!e.length)throw new RangeError("Nostr subscriptions require at least one filter");if(r.includeSuperseded&&r.cache!=="network-only")throw new Error("Historical replaceable versions require network-only queries");if(this.listeners.size>=(this.options.maxSubscriptions??1024))throw new RangeError("Nostr subscription capacity exhausted");Tu({deadline:r.deadline});const i={filters:structuredClone(e),handlers:n,options:r,seen:new Set,closers:new Map,statuses:new Map,pending:new Set,controller:new AbortController,stopped:!1,notified:!1,ready:Promise.resolve()};this.listeners.add(i),this.interests.add(i,i.filters);const s=()=>this.stopListener(i);return i.abort=s,r.signal?.addEventListener("abort",s,{once:!0}),r.signal?.aborted?(s(),{close:s}):(i.ready=this.startListener(i).catch(o=>{this.report(i,o),this.complete(i,"unavailable")}),{close:s})}async query(e,n={}){if(Tu(n),n.signal?.aborted)throw wa(n.signal.reason);return n.deadline!==void 0&&n.deadline<=Date.now()?{events:[],complete:!1,reason:"timeout",sources:[]}:new Promise((r,i)=>{const s=new Map;let o;const c=()=>{o?.close(),i(wa(n.signal?.reason))};n.signal?.addEventListener("abort",c,{once:!0}),o=this.subscribe(e,{onEvent:u=>s.set(u.id,u),onEose:u=>{o?.close(),n.signal?.removeEventListener("abort",c),r({...u,events:Ah(s.values(),e,n)})},onError:u=>this.options.onError?.(u)},n)})}async ingest(e,n="external"){return this.admit(e,n)}async admit(e,n,r){this.ensureOpen();let i;try{i=Mr(e,this.options.verifyEvent)}catch(u){throw this.counters.verificationFailures++,u}let s=this.incoming.get(i.id);const o=!s;if(!s){const u=this.writes.then(()=>Pv(this.store,i)).catch(f=>{for(const p of this.interests.candidates(i))!p.stopped&&ks(p.filters,i)&&(p.admissionError=Nn(f).message);throw f});this.writes=u.catch(()=>{}),s={operation:u,sources:new Set},this.incoming.set(i.id,s)}const c=!s.sources.has(n);s.sources.add(n);try{const u=await s.operation;if(u!=="rejected"&&!this.stopped)for(const f of this.interests.candidates(i))(f.options.isolated?f!==r&&n!=="local-publish":!c)||(u==="admitted"||f.options.includeSuperseded)&&this.deliver(f,i,{source:n,cached:!1});return u==="admitted"}finally{o&&this.incoming.delete(i.id)}}publish(e,n={}){this.ensureOpen();const r=JSON.stringify([e.id,n]),i=this.publishing.get(r);if(i)return i;const s=this.publishOnce(e,n).finally(()=>this.publishing.delete(r));return this.publishing.set(r,s),s}async retryPending(){if(!(this.stopped||this.retrying)){this.retrying=!0;try{const e=await this.store.listPending();for(let n=0;n<e.length&&!this.stopped;n+=4)await Promise.all(e.slice(n,n+4).map(({event:r,relays:i,sources:s})=>this.publish(r,{relays:i,sources:s}).catch(o=>this.options.onError?.(Nn(o)))))}finally{this.retrying=!1}}}setRelays(e){this.ensureOpen(),this.relays.setRelays(e);for(const n of this.listeners)if(n.options.cache!=="cache-only"&&n.options.relays===void 0){for(const r of[...n.statuses.keys()])this.sources.has(r)||n.statuses.delete(r);for(const r of[...n.pending])this.sources.has(r)||n.pending.delete(r);for(const r of this.relays.urls())n.pending.add(r)}this.retryPending().catch(n=>this.options.onError?.(Nn(n)))}getRelayStats(){return this.relays.stats()}metrics(){return{...this.counters,subscriptions:this.listeners.size,relaySubscriptions:this.relays.count()}}addSource(e){this.ensureOpen(),this.removeSource(e.id),this.sources.set(e.id,e);for(const n of this.listeners)this.wantsSource(n,e.id)&&this.attachSource(n,e);this.retryPending().catch(n=>
1this.options.onError?.(Nn(n)))}removeSource(e){this.sources.delete(e);for(const n of this.listeners)n.closers.get(e)?.(),n.closers.delete(e),n.pending.delete(e),n.statuses.delete(e)}async close(){if(!this.stopped){this.stopped=!0,this.retryTimer&&clearTimeout(this.retryTimer);for(const e of[...this.listeners])this.complete(e,"closed"),this.stopListener(e);this.relays.close(),await this.writes,await Promise.allSettled([...this.publishing.values()]),await this.store.close?.()}}async startListener(e){const n=Math.max(0,(e.options.deadline??Date.now()+(this.options.historyTimeoutMs??1e4))-Date.now());if(e.timer=setTimeout(()=>this.complete(e,"timeout"),n),e.options.cache!=="cache-only"){for(const i of e.options.relays?.map(s=>new URL(s).toString())??this.relays.urls())e.pending.add(i);const r=this.relays.subscribe(e.filters,(i,s)=>this.receive(e,i,s),(i,s,o)=>this.sourceState(e,i,s,o),e.options.relays,e.options.isolated);e.closers.set("relay-transport",()=>r.close());for(const i of this.sources.values())this.wantsSource(e,i.id)&&(e.pending.add(i.id),this.attachSource(e,i))}if(e.options.cache!=="network-only"){const r=await this.store.query(e.filters,{signal:e.controller.signal,deadline:e.options.deadline});for(const i of r){if(e.stopped)return;try{this.deliver(e,Mr(i,this.options.verifyEvent),{source:"local-cache",cached:!0})}catch(s){this.report(e,s)}}}if(!e.stopped){if(e.options.cache==="cache-only"){this.complete(e,"cache");return}await this.maybeComplete(e)}}wantsSource(e,n){return e.options.cache!=="cache-only"&&(e.options.sources?e.options.sources.includes(n):e.options.relays===void 0)}async attachSource(e,n){e.pending.add(n.id);try{if(n.subscribe){const r=await n.subscribe(e.filters,({event:i})=>this.receive(e,i,n.id));if(e.stopped||this.sources.get(n.id)!==n){r.close();return}e.closers.set(n.id,()=>r.close())}if(n.query){const r=await n.query(e.filters,{deadline:e.options.deadline??Date.now()+(this.options.historyTimeoutMs??1e4),signal:e.controller.signal});if(e.stopped||this.sources.get(n.id)!==n)return;for(const{event:i}of r.events)await this.admit(i,n.id,e);this.sourceState(e,n.id,r.complete!==!1)}else this.sourceState(e,n.id,!1,"Source has no historical completion")}catch(r){!e.stopped&&this.sources.get(n.id)===n&&(this.sourceState(e,n.id,!1,Nn(r).message),this.report(e,r))}}receive(e,n,r){if(e.stopped)return;this.counters.receivedEvents++;const i=e.options.isolated?`${r}:${n.id}`:n.id;if(e.seen.has(i)||!e.options.isolated&&this.incoming.get(n.id)?.sources.has(r)){this.counters.duplicateEvents++;return}this.admit(n,r,e).catch(s=>this.report(e,s))}deliver(e,n,r){if(e.stopped||!ks(e.filters,n)||!this.acceptsOrigin(e,r))return;const i=e.options.isolated?`${r.source}:${n.id}`:n.id;if(e.seen.has(i)){this.counters.duplicateEvents++;return}e.seen.add(i),e.seen.size>(this.options.maxSeenEventsPerSubscription??4096)&&e.seen.delete(e.seen.values().next().value),this.counters.deliveredEvents++;try{e.handlers.onEvent(n,r)}catch(s){this.report(e,s)}}acceptsOrigin(e,n){if(n.cached)return e.options.cache!=="network-only";if(n.source==="local-publish")return e.options.localEcho!==!1;const{relays:r,sources:i}=e.options;return r===void 0&&i===void 0?!0:(r?.map(o=>new URL(o).toString())??this.relays.urls()).includes(n.source)||(i?.includes(n.source)??!1)}sourceState(e,n,r,i){e.stopped||(e.pending.delete(n),e.statuses.set(n,{complete:r,error:i}),e.ready.then(()=>this.maybeComplete(e)))}async maybeComplete(e){for(;!e.stopped&&!e.notified&&e.pending.size===0;){const n=this.writes;if(await n,n!==this.writes)continue;if(e.stopped||e.notified||e.pending.size)return;const r=[...e.statuses.values()];this.complete(e,r.length&&r.every(i=>i.complete)?"eose":r.some(i=>i.error)||!r.length?"unavailable":"timeout");return}}complete(e,n){if(e.stopped||e.notified)return;e.notified=!0,e.timer&&clearTimeout(e.timer);const r=[...e.statuses].map(([s,o])=>({id:s,...o}));for(const s of e.pending)r.push({id:s,complete:!1,error:"Historical query is incomplete"});e.admissionError&&(n="unavailable",r.push({id:"local-cache",complete:!1,error:e.admissionError}));const i=n==="cache"||n==="eose"&&r.length>0&&r.every(s=>s.complete);try{e.handlers.onEose?.({complete:i,reason:n,sources:r})}catch(s){this.report(e,s)}}stopListener(e){if(!e.stopped){e.stopped=!0,e.controller.abort(),e.timer&&clearTimeout(e.timer),e.options.signal?.removeEventListener("abort",e.abort);for(const n of e.closers.values())n();e.closers.clear(),this.listeners.delete(e),this.interests.remove(e)}}async publishOnce(e,n){const r=Mr(e,this.options.verifyEvent),i=!n.requireAck&&n.queue!==!1,s=!n.requireAck&&n.localEcho!==!1;if(i){const f=(await this.store.listPending()).find(p=>p.event.id===r.id);await this.store.putPending({event:r,attempts:(f?.attempts??0)+1,updatedAt:Date.now(),relays:n.relays,sources:n.sources})}if(s&&!await this.ingest(r,"local-publish"))return i&&await this.store.deletePending(r.id),{accepted:!1,remoteAccepted:!1,queued:!1,sources:[{id:"local-cache",accepted:!1,error:"Event is expired, deleted or superseded"}]};const o=this.relays.publishAttempts(r,n.relays).map(({id:f,result:p})=>({id:f,remote:!0,result:p}));
1for(const f of this.sources.values())!f.publish||(n.sources?!n.sources.includes(f.id):n.relays!==void 0)||o.push({id:f.id,remote:f.publishAcceptance!=="queued",result:sb(f.publish(r,yf("runtime-outbox")).then(p=>{if(!p.accepted)throw new Error(p.reason??"Publication rejected")}),this.options.publishTimeoutMs??5e3)});const c=o.map(({id:f})=>({id:f,accepted:!1,pending:!0})),u=await new Promise(f=>{let p=o.length;p||f(!1),o.forEach(({result:d,remote:g},w)=>{d.then(()=>{c[w]={id:o[w].id,accepted:g,...g?{}:{queued:!0}},g&&f(!0)},x=>{c[w]={id:o[w].id,accepted:!1,error:Nn(x).message}}).finally(()=>{--p===0&&f(!1)})})});return u&&(i&&await this.store.deletePending(r.id),s||await this.ingest(r,"local-publish")),{accepted:u,remoteAccepted:u,queued:i&&!u,sources:c.map(f=>({...f}))}}scheduleRetry(){this.retryTimer=setTimeout(()=>{this.retryPending().catch(e=>this.options.onError?.(Nn(e))).finally(()=>{this.stopped||this.scheduleRetry()})},5e3)}report(e,n){const r=Nn(n);try{(e.handlers.onError??this.options.onError)?.(r)}catch{}}ensureOpen(){if(this.stopped)throw new Error("Nostr runtime is closed")}}function ib(t={}){return new rb(t)}function Nn(t){return t instanceof Error?t:new Error(String(t))}function sb(t,e){return new Promise((n,r)=>{const i=setTimeout(()=>r(new Error("Nostr source publication timed out")),e);t.then(s=>{clearTimeout(i),n(s)},s=>{clearTimeout(i),r(s)})})}function ob(t,e){const n=new Map,r=new Map;let i=!1;return t.onmessage=async({data:s})=>{if(i||!Number.isSafeInteger(s?.id))return;if(s.method==="cancel"){n.get(s.id)?.abort(),n.delete(s.id),r.get(s.id)?.close(),r.delete(s.id);return}const o=new AbortController;n.set(s.id,o);const c=s.args??[];try{let u;if(s.method==="query"){if(!e.query)throw new Error("Nostr source does not support queries");u=await e.query(c[0],{...c[1],signal:o.signal})}else if(s.method==="publish"){if(!e.publish)throw new Error("Nostr source does not support publishing");u=await e.publish(c[0],c[1])}else if(s.method==="subscribe"){if(!e.subscribe)throw new Error("Nostr source does not support subscriptions");const f=await e.subscribe(c[0],p=>{!i&&!o.signal.aborted&&t.postMessage({id:s.id,type:"event",value:p})});o.signal.aborted||i?f.close():r.set(s.id,f)}else return;!i&&!o.signal.aborted&&t.postMessage({id:s.id,type:"result",value:u})}catch(u){n.delete(s.id),!i&&!o.signal.aborted&&t.postMessage({id:s.id,type:"error",error:String(u)})}finally{s.method!=="subscribe"&&n.delete(s.id)}},t.start(),()=>{if(!i){i=!0;for(const s of n.values())s.abort();for(const s of r.values())s.close();n.clear(),r.clear(),t.close()}}}function ab(t,e,n){let r=0,i=!1;const s=new Map,o=new Map;t.onmessage=({data:u})=>{u?.type==="event"?s.get(u.id)?.(u.value):u?.type==="result"?o.get(u.id)?.resolve(u.value):u?.type==="error"&&o.get(u.id)?.reject(new Error(u.error))},t.start();const c=(u,f,p={},d=++r)=>i?Promise.reject(new Error("Nostr source bridge is closed")):p.signal?.aborted?Promise.reject(new DOMException("Nostr source request cancelled","AbortError")):new Promise((g,w)=>{const x=()=>{o.delete(d),I&&clearTimeout(I),p.signal?.removeEventListener("abort",A)},A=()=>{x(),t.postMessage({id:d,method:"cancel"}),w(new DOMException("Nostr source request cancelled","AbortError"))};o.set(d,{resolve:T=>{x(),g(T)},reject:T=>{x(),w(T)}}),p.signal?.addEventListener("abort",A,{once:!0});const I=setTimeout(()=>{x(),t.postMessage({id:d,method:"cancel"}),w(new DOMException("Nostr source request timed out","TimeoutError"))},Math.max(0,(p.deadline??Date.now()+3e4)-Date.now()));t.postMessage({id:d,method:u,args:f})});return{source:{id:e,publishAcceptance:n,query:(u,f={})=>c("query",[u,{limit:f.limit,deadline:f.deadline}],f),publish:(u,f)=>c("publish",[u,f]),subscribe:async(u,f)=>{const p=++r;s.set(p,f);try{await c("subscribe",[u],{},p)}catch(d){throw s.delete(p),d}return{close:()=>{s.delete(p),i||t.postMessage({id:p,method:"cancel"})}}}},close:()=>{if(!i){i=!0;for(const u of new Set([...s.keys(),...o.keys()]))t.postMessage({id:u,method:"cancel"});for(const u of[...o.values()])u.reject(new Error("Nostr source bridge closed"));s.clear(),o.clear(),t.close()}}}}function js(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ts={exports:{}},Ho,Vu;function cb(){if(Vu)return Ho;Vu=1;var t=1e3,e=t*60,n=e*60,r=n*24,i=r*7,s=r*365.25;Ho=function(p,d){d=d||{};var g=typeof p;if(g==="string"&&p.length>0)return o(p);if(g==="number"&&isFinite(p))return d.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var d=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(d){var g=parseFloat(d[1]),w=(d[2]||"ms").toLowerCase();switch(w){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*r;case"hours":case"hour":case"hrs":case"hr":case"h":return g*n;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function c(p){var d=Math.abs(p);return d>=r?Math.round(p/r)+"d":d>=n?Math.round(p/n)+"h":d>=e?Math.round(p/e)+"m":d>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var d=Math.abs(p);return d>=r?f(p,d,r,"day"):d>=n?f(p,d,n,"hour"):d>=e?f(p,d,e,"minute"):d>=t?f(p,d,t,"second"):p+" ms"}function f(p,d,g,w){var x=d>=g*1.5;return Math.round(p/g)+" "+w+(x?"s":"")}return Ho}var qo,Gu;function ub(){if(Gu)return qo;Gu=1;function t(e){r.debug=r,r.default=r,r.coerce=f,r.disable=c,r.enable=s,r.enabled=u,r.humanize=cb(),r.destroy=p,Object.keys(e).forEach(d=>{r[d]=e[d]}),r.names=[],r.skips=[],r.formatters={};function n(d){let g=0;for(let w=0;w<d.length;
vendor: 4,470 bytes, line 1
1w++)g=(g<<5)-g+d.charCodeAt(w),g|=0;return r.colors[Math.abs(g)%r.colors.length]}r.selectColor=n;function r(d){let g,w=null,x,A;function I(...T){if(!I.enabled)return;const te=I,ae=Number(new Date),Re=ae-(g||ae);te.diff=Re,te.prev=g,te.curr=ae,g=ae,T[0]=r.coerce(T[0]),typeof T[0]!="string"&&T.unshift("%O");let le=0;T[0]=T[0].replace(/%([a-zA-Z%])/g,(Q,ie)=>{if(Q==="%%")return"%";le++;const ee=r.formatters[ie];if(typeof ee=="function"){const ge=T[le];Q=ee.call(te,ge),T.splice(le,1),le--}return Q}),r.formatArgs.call(te,T),(te.log||r.log).apply(te,T)}return I.namespace=d,I.useColors=r.useColors(),I.color=r.selectColor(d),I.extend=i,I.destroy=r.destroy,Object.defineProperty(I,"enabled",{enumerable:!0,configurable:!1,get:()=>w!==null?w:(x!==r.namespaces&&(x=r.namespaces,A=r.enabled(d)),A),set:T=>{w=T}}),typeof r.init=="function"&&r.init(I),I}function i(d,g){const w=r(this.namespace+(typeof g>"u"?":":g)+d);return w.log=this.log,w}function s(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];const g=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const w of g)w[0]==="-"?r.skips.push(w.slice(1)):r.names.push(w)}function o(d,g){let w=0,x=0,A=-1,I=0;for(;w<d.length;)if(x<g.length&&(g[x]===d[w]||g[x]==="*"))g[x]==="*"?(A=x,I=w,x++):(w++,x++);else if(A!==-1)x=A+1,I++,w=I;else return!1;for(;x<g.length&&g[x]==="*";)x++;return x===g.length}function c(){const d=[...r.names,...r.skips.map(g=>"-"+g)].join(",");return r.enable(""),d}function u(d){for(const g of r.skips)if(o(d,g))return!1;for(const g of r.names)if(o(d,g))return!0;return!1}function f(d){return d instanceof Error?d.stack||d.message:d}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}return qo=t,qo}var Yu;function lb(){return Yu||(Yu=1,(function(t,e){var n={};e.formatArgs=i,e.save=s,e.load=o,e.useColors=r,e.storage=c(),e.destroy=(()=>{let f=!1;return()=>{f||(f=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let f;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(f=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(f[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(f){if(f[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+f[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;f.splice(1,0,p,"color: inherit");let d=0,g=0;f[0].replace(/%[a-zA-Z%]/g,w=>{w!=="%%"&&(d++,w==="%c"&&(g=d))}),f.splice(g,0,p)}e.log=console.debug||console.log||(()=>{});function s(f){try{f?e.storage.setItem("debug",f):e.storage.removeItem("debug")}catch{}}function o(){let f;try{f=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!f&&typeof process<"u"&&"env"in process&&(f=n.DEBUG),f}function c(){try{return localStorage}catch{}}t.exports=ub()(e);const{formatters:u}=t.exports;u.j=function(f){try{return JSON.stringify(f)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}
vendor: 5,808 bytes, line 1
1)(ts,ts.exports)),ts.exports}var fb=lb(),cn=js(fb);const Zu=t=>{let e;const n=new Set,r=(f,p)=>{const d=typeof f=="function"?f(e):f;if(!Object.is(d,e)){const g=e;e=p??(typeof d!="object"||d===null)?d:Object.assign({},e,d),n.forEach(w=>w(e,g))}},i=()=>e,c={setState:r,getState:i,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f))},u=e=t(r,i,c);return c},hb=(t=>t?Zu(t):Zu);var Wo={exports:{}},Fe={};var Xu;function db(){if(Xu)return Fe;Xu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),g=Symbol.iterator;function w(_){return _===null||typeof _!="object"?null:(_=g&&_[g]||_["@@iterator"],typeof _=="function"?_:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,I={};function T(_,W,we){this.props=_,this.context=W,this.refs=I,this.updater=we||x}T.prototype.isReactComponent={},T.prototype.setState=function(_,W){if(typeof _!="object"&&typeof _!="function"&&_!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,_,W,"setState")},T.prototype.forceUpdate=function(_){this.updater.enqueueForceUpdate(this,_,"forceUpdate")};function te(){}te.prototype=T.prototype;function ae(_,W,we){this.props=_,this.context=W,this.refs=I,this.updater=we||x}var Re=ae.prototype=new te;Re.constructor=ae,A(Re,T.prototype),Re.isPureReactComponent=!0;var le=Array.isArray;function Y(){}var Q={H:null,A:null,T:null,S:null},ie=Object.prototype.hasOwnProperty;function ee(_,W,we){var ke=we.ref;return{$$typeof:t,type:_,key:W,ref:ke!==void 0?ke:null,props:we}}function ge(_,W){return ee(_.type,W,_.props)}function $(_){return typeof _=="object"&&_!==null&&_.$$typeof===t}function H(_){var W={"=":"=0",":":"=2"};return"$"+_.replace(/[=:]/g,function(we){return W[we]})}var C=/\/+/g;function j(_,W){return typeof _=="object"&&_!==null&&_.key!=null?H(""+_.key):W.toString(36)}function P(_){switch(_.status){case"fulfilled":return _.value;case"rejected":throw _.reason;default:switch(typeof _.status=="string"?_.then(Y,Y):(_.status="pending",_.then(function(W){_.status==="pending"&&(_.status="fulfilled",_.value=W)},function(W){_.status==="pending"&&(_.status="rejected",_.reason=W)})),_.status){case"fulfilled":return _.value;case"rejected":throw _.reason}}throw _}function X(_,W,we,ke,ye){var Ce=typeof _;(Ce==="undefined"||Ce==="boolean")&&(_=null);var Me=!1;if(_===null)Me=!0;else switch(Ce){case"bigint":case"string":case"number":Me=!0;break;case"object":switch(_.$$typeof){case t:case e:Me=!0;break;case p:return Me=_._init,X(Me(_._payload),W,we,ke,ye)}}if(Me)return ye=ye(_),Me=ke===""?"."+j(_,0):ke,le(ye)?(we="",Me!=null&&(we=Me.replace(C,"$&/")+"/"),X(ye,W,we,"",function(ut){return ut})):ye!=null&&($(ye)&&(ye=ge(ye,we+(ye.key==null||_&&_.key===ye.key?"":(""+ye.key).replace(C,"$&/")+"/")+Me)),W.push(ye)),1;Me=0;var Ve=ke===""?".":ke+":";if(le(_))for(var Ue=0;Ue<_.length;Ue++)ke=_[Ue],Ce=Ve+j(ke,Ue),Me+=X(ke,W,we,Ce,ye);else if(Ue=w(_),typeof Ue=="function")for(_=Ue.call(_),Ue=0;!(ke=_.next()).done;)ke=ke.value,Ce=Ve+j(ke,Ue++),Me+=X(ke,W,we,Ce,ye);else if(Ce==="object"){if(typeof _.then=="function")return X(P(_),W,we,ke,ye);throw W=String(_),Error("Objects are not valid as a React child (found: "+(W==="[object Object]"?"object with keys {"+Object.keys(_).join(", ")+"}":W)+"). If you meant to render a collection of children, use an array instead.")}return Me}function re(_,W,we){if(_==null)return _;var ke=[],ye=0;return X(_,ke,"","",function(Ce){return W.call(we,Ce,ye++)}),ke}function xe(_){if(_._status===-1){var W=_._result;W=W(),W.then(function(we){(_._status===0||_._status===-1)&&(_._status=1,_._result=we)},function(we){(_._status===0||_._status===-1)&&(_._status=2,_._result=we)}),_._status===-1&&(_._status=0,_._result=W)}if(_._status===1)return _._result.default;throw _._result}var pe=typeof reportError=="function"?reportError:function(_){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var W=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof _=="object"&&_!==null&&typeof _.message=="string"?String(_.message):String(_),error:_});if(!window.dispatchEvent(W))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",_);return}console.error(_)},_e={map:re,forEach:function(_,W,we){re(_,function(){W.apply(this,arguments)},we)},count:function(_){var W=0;return re(_,function(){W++}),W},toArray:function(_){return re(_,function(W){return W})||[]},only:function(_){if(!$(_))throw Error("React.Children.only expected to receive a single React element child.");return _}};return Fe.Activity=d,Fe.Children=_e,Fe.Component=T,Fe.Fragment=n,Fe.Profiler=i,Fe.PureComponent=ae,Fe.StrictMode=r,Fe.Suspense=u,Fe.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Q,Fe.__COMPILER_RUNTIME={__proto__:null,c:function(_){return Q.H.useMemoCache(_)}},Fe.cache=function(_){return function(){return _.apply(null,arguments)}},Fe.cacheSignal=function(){return null},Fe.cloneElement=function(_,W,we){if(_==null)throw Error("The argument must be a React element, but you passed "+_+".");var ke=A({},_.props),ye=_.key;if(W!=null)for(Ce in W.key!==void 0&&(ye=""+W.key),W)!ie.call(W,Ce)||Ce==="key"||Ce==="__self"||Ce==="__source"||Ce==="ref"&&W.ref===void 0||(ke[Ce]=W[Ce]);var Ce=arguments.length-2;if(Ce===1)ke.children=we;else if(1<Ce){for(var Me=Array(Ce),Ve=0;Ve<Ce;
1Ve++)Me[Ve]=arguments[Ve+2];ke.children=Me}return ee(_.type,ye,ke)},Fe.createContext=function(_){return _={$$typeof:o,_currentValue:_,_currentValue2:_,_threadCount:0,Provider:null,Consumer:null},_.Provider=_,_.Consumer={$$typeof:s,_context:_},_},Fe.createElement=function(_,W,we){var ke,ye={},Ce=null;if(W!=null)for(ke in W.key!==void 0&&(Ce=""+W.key),W)ie.call(W,ke)&&ke!=="key"&&ke!=="__self"&&ke!=="__source"&&(ye[ke]=W[ke]);var Me=arguments.length-2;if(Me===1)ye.children=we;else if(1<Me){for(var Ve=Array(Me),Ue=0;Ue<Me;Ue++)Ve[Ue]=arguments[Ue+2];ye.children=Ve}if(_&&_.defaultProps)for(ke in Me=_.defaultProps,Me)ye[ke]===void 0&&(ye[ke]=Me[ke]);return ee(_,Ce,ye)},Fe.createRef=function(){return{current:null}},Fe.forwardRef=function(_){return{$$typeof:c,render:_}},Fe.isValidElement=$,Fe.lazy=function(_){return{$$typeof:p,_payload:{_status:-1,_result:_},_init:xe}},Fe.memo=function(_,W){return{$$typeof:f,type:_,compare:W===void 0?null:W}},Fe.startTransition=function(_){var W=Q.T,we={};Q.T=we;try{var ke=_(),ye=Q.S;ye!==null&&ye(we,ke),typeof ke=="object"&&ke!==null&&typeof ke.then=="function"&&ke.then(Y,pe)}catch(Ce){pe(Ce)}finally{W!==null&&we.types!==null&&(W.types=we.types),Q.T=W}},Fe.unstable_useCacheRefresh=function(){return Q.H.useCacheRefresh()},Fe.use=function(_){return Q.H.use(_)},Fe.useActionState=function(_,W,we){return Q.H.useActionState(_,W,we)},Fe.useCallback=function(_,W){return Q.H.useCallback(_,W)},Fe.useContext=function(_){return Q.H.useContext(_)},Fe.useDebugValue=function(){},Fe.useDeferredValue=function(_,W){return Q.H.useDeferredValue(_,W)},Fe.useEffect=function(_,W){return Q.H.useEffect(_,W)},Fe.useEffectEvent=function(_){return Q.H.useEffectEvent(_)},Fe.useId=function(){return Q.H.useId()},Fe.useImperativeHandle=function(_,W,we){return Q.H.useImperativeHandle(_,W,we)},Fe.useInsertionEffect=function(_,W){return Q.H.useInsertionEffect(_,W)},Fe.useLayoutEffect=function(_,W){return Q.H.useLayoutEffect(_,W)},Fe.useMemo=function(_,W){return Q.H.useMemo(_,W)},Fe.useOptimistic=function(_,W){return Q.H.useOptimistic(_,W)},Fe.useReducer=function(_,W,we){return Q.H.useReducer(_,W,we)},Fe.useRef=function(_){return Q.H.useRef(_)},Fe.useState=function(_){return Q.H.useState(_)},Fe.useSyncExternalStore=function(_,W,we){return Q.H.useSyncExternalStore(_,W,we)},Fe.useTransition=function(){return Q.H.useTransition()},Fe.version="19.2.8",Fe}var Ju;function pb(){return Ju||(Ju=1,Wo.exports=db()),Wo.exports}var yb=pb(),ns=js(yb);const gb=t=>t;function mb(t,e=gb){const n=ns.useSyncExternalStore(t.subscribe,ns.useCallback(()=>e(t.getState()),[t,e]),ns.useCallback(()=>e(t.getInitialState()),[t,e]));return ns.useDebugValue(n),n}const wb=t=>{const e=hb(t),n=r=>mb(e,r);return Object.assign(n,e),n},vb=(t=>wb),bb=t=>(e,n,r)=>{const i=r.subscribe;return r.subscribe=((o,c,u)=>{let f=o;if(c){const p=u?.equalityFn||Object.is;let d=o(r.getState());f=g=>{const w=o(g);if(!p(d,w)){const x=d;c(d=w,x)}},u?.fireImmediately&&c(d,d)}return i(f)}),t(e,n,r)},Eb=bb;var ps={exports:{}},xb=ps.exports,Qu;function _b(){return Qu||(Qu=1,(function(t,e){var n={};((r,i)=>{t.exports=i()})(xb,function(){var r=function(a,l){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(h,y){h.__proto__=y}:function(h,y){for(var m in y)Object.prototype.hasOwnProperty.call(y,m)&&(h[m]=y[m])}))(a,l)},i=function(){return(i=Object.assign||function(a){for(var l,h=1,y=arguments.length;h<y;h++)for(var m in l=arguments[h])Object.prototype.hasOwnProperty.call(l,m)&&(a[m]=l[m]);return a}).apply(this,arguments)};function s(a,l,h){for(var y,m=0,v=l.length;m<v;m++)!y&&m in l||((y=y||Array.prototype.slice.call(l,0,m))[m]=l[m]);return a.concat(y||Array.prototype.slice.call(l))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:n,c=Object.keys,u=Array.isArray;function f(a,l){return typeof l=="object"&&c(l).forEach(function(h){a[h]=l[h]}),a}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var p=Object.getPrototypeOf,d={}.hasOwnProperty;function g(a,l){return d.call(a,l)}function w(a,l){typeof l=="function"&&(l=l(p(a))),(typeof Reflect>"u"?c:Reflect.ownKeys)(l).forEach(function(h){A(a,h,l[h])})}var x=Object.defineProperty;function A(a,l,h,y){x(a,l,f(h&&g(h,"get")&&typeof h.get=="function"?{get:h.get,set:h.set,configurable:!0}:{value:h,configurable:!0,writable:!0},y))}function I(a){return{from:function(l){return a.prototype=Object.create(l.prototype),A(a.prototype,"constructor",a),{extend:w.bind(null,a.prototype)}}}}var T=Object.getOwnPropertyDescriptor,te=[].slice;function ae(a,l,h){return te.call(a,l,h)}function Re(a,l){return l(a)}function le(a){if(!a)throw new Error("Assertion Failed")}function Y(a){o.setImmediate?setImmediate(a):setTimeout(a,0)}function Q(a,l){if(typeof l=="string"&&g(a,l))return a[l];if(!l)return a;
vendor: 85,994 bytes, lines 1-3
1if(typeof l!="string"){for(var h=[],y=0,m=l.length;y<m;++y){var v=Q(a,l[y]);h.push(v)}return h}var E,S=l.indexOf(".");return S===-1||(E=a[l.substr(0,S)])==null?void 0:Q(E,l.substr(S+1))}function ie(a,l,h){if(a&&l!==void 0&&!("isFrozen"in Object&&Object.isFrozen(a)))if(typeof l!="string"&&"length"in l){le(typeof h!="string"&&"length"in h);for(var y=0,m=l.length;y<m;++y)ie(a,l[y],h[y])}else{var v=l.indexOf(".");if(v!==-1){var E=l.substr(0,v),v=l.substr(v+1);if(v==="")h===void 0?u(a)&&!isNaN(parseInt(E))?a.splice(E,1):delete a[E]:a[E]=h;else{var S=a[E];if(!S||!g(a,E)){if(h===void 0)return;S=a[E]={}}ie(S,v,h)}}else h===void 0?u(a)&&!isNaN(parseInt(l))?a.splice(l,1):delete a[l]:a[l]=h}}function ee(a){var l,h={};for(l in a)g(a,l)&&(h[l]=a[l]);return h}var ge=[].concat;function $(a){return ge.apply([],a)}var we="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat($([8,16,32,64].map(function(a){return["Int","Uint","Float"].map(function(l){return l+a+"Array"})}))).filter(function(a){return o[a]}),H=new Set(we.map(function(a){return o[a]})),C=null;function j(a){return C=new WeakMap,a=(function l(h){if(!h||typeof h!="object")return h;var y=C.get(h);if(y)return y;if(u(h)){y=[],C.set(h,y);for(var m=0,v=h.length;m<v;++m)y.push(l(h[m]))}else if(H.has(h.constructor))y=h;else{var E,S=p(h);for(E in y=S===Object.prototype?{}:Object.create(S),C.set(h,y),h)g(h,E)&&(y[E]=l(h[E]))}return y})(a),C=null,a}var P={}.toString;function X(a){return P.call(a).slice(8,-1)}var re=typeof Symbol<"u"?Symbol.iterator:"@@iterator",xe=typeof re=="symbol"?function(a){var l;return a!=null&&(l=a[re])&&l.apply(a)}:function(){return null};function pe(a,l){l=a.indexOf(l),0<=l&&a.splice(l,1)}var _e={};function _(a){var l,h,y,m;if(arguments.length===1){if(u(a))return a.slice();if(this===_e&&typeof a=="string")return[a];if(m=xe(a))for(h=[];!(y=m.next()).done;)h.push(y.value);else{if(a==null)return[a];if(typeof(l=a.length)!="number")return[a];for(h=new Array(l);l--;)h[l]=a[l]}}else for(l=arguments.length,h=new Array(l);l--;)h[l]=arguments[l];return h}var W=typeof Symbol<"u"?function(a){return a[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},we=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],mt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(we),ke={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function ye(a,l){this.name=a,this.message=l}function Ce(a,l){return a+". Errors: "+Object.keys(l).map(function(h){return l[h].toString()}).filter(function(h,y,m){return m.indexOf(h)===y}).join(`
2`)}function Me(a,l,h,y){this.failures=l,this.failedKeys=y,this.successCount=h,this.message=Ce(a,l)}function Ve(a,l){this.name="BulkError",this.failures=Object.keys(l).map(function(h){return l[h]}),this.failuresByPos=l,this.message=Ce(a,this.failures)}I(ye).from(Error).extend({toString:function(){return this.name+": "+this.message}}),I(Me).from(ye),I(Ve).from(ye);var Ue=mt.reduce(function(a,l){return a[l]=l+"Error",a},{}),ut=ye,Be=mt.reduce(function(a,l){var h=l+"Error";function y(m,v){this.name=h,m?typeof m=="string"?(this.message="".concat(m).concat(v?`
3 `+v:""),this.inner=v||null):typeof m=="object"&&(this.message="".concat(m.name," ").concat(m.message),this.inner=m):(this.message=ke[l]||h,this.inner=null)}return I(y).from(ut),a[l]=y,a},{}),Zn=(Be.Syntax=SyntaxError,Be.Type=TypeError,Be.Range=RangeError,we.reduce(function(a,l){return a[l+"Error"]=Be[l],a},{}));we=mt.reduce(function(a,l){return["Syntax","Type","Range"].indexOf(l)===-1&&(a[l+"Error"]=Be[l]),a},{});function Ge(){}function Xn(a){return a}function Qs(a,l){return a==null||a===Xn?l:function(h){return l(a(h))}}function gt(a,l){return function(){a.apply(this,arguments),l.apply(this,arguments)}}function eo(a,l){return a===Ge?l:function(){var h=a.apply(this,arguments),y=(h!==void 0&&(arguments[0]=h),this.onsuccess),m=this.onerror,v=(this.onsuccess=null,this.onerror=null,l.apply(this,arguments));return y&&(this.onsuccess=this.onsuccess?gt(y,this.onsuccess):y),m&&(this.onerror=this.onerror?gt(m,this.onerror):m),v!==void 0?v:h}}function Ti(a,l){return a===Ge?l:function(){a.apply(this,arguments);var h=this.onsuccess,y=this.onerror;this.onsuccess=this.onerror=null,l.apply(this,arguments),h&&(this.onsuccess=this.onsuccess?gt(h,this.onsuccess):h),y&&(this.onerror=this.onerror?gt(y,this.onerror):y)}}function dr(a,l){return a===Ge?l:function(m){var y=a.apply(this,arguments),m=(f(m,y),this.onsuccess),v=this.onerror,E=(this.onsuccess=null,this.onerror=null,l.apply(this,arguments));return m&&(this.onsuccess=this.onsuccess?gt(m,this.onsuccess):m),v&&(this.onerror=this.onerror?gt(v,this.onerror):v),y===void 0?E===void 0?void 0:E:f(y,E)}}function Vr(a,l){return a===Ge?l:function(){return l.apply(this,arguments)!==!1&&a.apply(this,arguments)}}function Jn(a,l){return a===Ge?l:function(){var h=a.apply(this,arguments);if(h&&typeof h.then=="function"){for(var y=this,m=arguments.length,v=new Array(m);m--;)v[m]=arguments[m];return h.then(function(){return l.apply(y,v)})}return l.apply(this,arguments)}}we.ModifyError=Me,we.DexieError=ye,we.BulkError=Ve;var Rt=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Gr(a){Rt=a}var kn={},Yr=100,Sn=typeof Promise>"u"?[]:(mt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[Sn=crypto.subtle.digest("SHA-512",new Uint8Array([0])),p(Sn),mt]:[mt,p(mt),mt]),mt=Sn[0],Rr=Sn[1],Rr=Rr&&Rr.then,Yt=mt&&mt.constructor,pr=!!Sn[2],An=function(a,l){hn.push([a,l]),Qn&&(queueMicrotask(no),Qn=!1)},yr=!0,Qn=!0,Zt=[],er=[],tr=Xn,zt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ge,pgp:!1,env:{},finalize:Ge},Le=zt,hn=[],Xt=0,gr=[];function Se(a){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var l=this._PSD=Le;if(typeof a!="function"){if(a!==kn)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&mr(this,this._value)}else this._state=null,this._value=null,++l.ref,(function h(y,m){try{m(function(v){if(y._state===null){if(v===y)throw new TypeError("A promise cannot be resolved with itself.");var E=y._lib&&Rn();v&&typeof v.then=="function"?h(y,function(S,M){v instanceof Se?v._then(S,M):v.then(S,M)}):(y._state=!0,y._value=v,Bi(y)),E&&Cn()}},mr.bind(null,y))}catch(v){mr(y,v)}})(this,a)}var Zr={get:function(){var a=Le,l=Er;function h(y,m){var v=this,E=!a.global&&(a!==Le||l!==Er),S=E&&!Qt(),M=new Se(function(V,N){Xr(v,new Ii(Oi(y,a,E,S),Oi(m,a,E,S),V,N,a))});return this._consoleTask&&(M._consoleTask=this._consoleTask),M}return h.prototype=kn,h},set:function(a){A(this,"then",a&&a.prototype===kn?Zr:{get:function(){return a},set:Zr.set})}};function Ii(a,l,h,y,m){this.onFulfilled=typeof a=="function"?a:null,this.onRejected=typeof l=="function"?l:null,this.resolve=h,this.reject=y,this.psd=m}function mr(a,l){var h,y;er.push(l),a._state===null&&(h=a._lib&&Rn(),l=tr(l),a._state=!1,a._value=l,y=a,Zt.some(function(m){return m._value===y._value})||Zt.push(y),Bi(a),h)&&Cn()}function Bi(a){var l=a._listeners;a._listeners=[];for(var h=0,y=l.length;h<y;++h)Xr(a,l[h]);var m=a._PSD;--m.ref||m.finalize(),Xt===0&&(++Xt,An(function(){--Xt==0&&Jr()},[]))}function Xr(a,l){if(a._state===null)a._listeners.push(l);else{var h=a._state?l.onFulfilled:l.onRejected;if(h===null)return(a._state?l.resolve:l.reject)(a._value);++l.psd.ref,++Xt,An(to,[h,a,l])}}function to(a,l,h){try{var y,m=l._value;!l._state&&er.length&&(er=[]),y=Rt&&l._consoleTask?l._consoleTask.run(function(){return a(m)}):a(m),l._state||er.indexOf(m)!==-1||(v=>{for(var E=Zt.length;E;)if(Zt[--E]._value===v._value)return Zt.splice(E,1)})(l),h.resolve(y)}catch(v){h.reject(v)}finally{--Xt==0&&Jr(),--h.psd.ref||h.psd.finalize()}}function no(){dn(zt,function(){Rn()&&Cn()})}function Rn(){var a=yr;return Qn=yr=!1,a}function Cn(){var a,l,h;do for(;0<hn.length;)for(a=hn,hn=[],h=a.length,l=0;l<h;++l){var y=a[l];y[0].apply(null,y[1])}while(0<hn.length);Qn=yr=!0}function Jr(){for(var a=Zt,l=(Zt=[],a.forEach(function(y){y._PSD.onunhandled.call(null,y._value,y)}),gr.slice(0)),h=l.length;h;)l[--h]()}function wr(a){return new Se(kn,!1,a)}function et(a,l){var h=Le;return function(){var y=Rn(),m=Le;try{return en(h,!0),a.apply(this,arguments)}catch(v){l&&l(v)}finally{en(m,!1),y&&Cn()}}}w(Se.prototype,{then:Zr,_then:function(a,l){Xr(this,new Ii(null,null,a,l,Le))},catch:function(a){var l,h;return arguments.length===1?this.then(null,a):(l=a,h=arguments[1],typeof l=="function"?this.then(null,function(y){return(y instanceof l?h:wr)(y)}):this.then(null,function(y){return(y&&y.name===l?h:wr)(y)}))},finally:function(a){return this.then(function(l){return Se.resolve(a()).then(function(){return l})},function(l){return Se.resolve(a()).then(function(){return wr(l)})})},timeout:function(a,l){var h=this;return a<1/0?new Se(function(y,m){var v=setTimeout(function(){return m(new Be.Timeout(l))},a);h.then(y,m).finally(clearTimeout.bind(null,v))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&A(Se.prototype,Symbol.toStringTag,"Dexie.Promise"),zt.env=Mi(),w(Se,{all:function(){var a=_.apply(null,arguments).map(xr);return new Se(function(l,h){a.length===0&&l([]);var y=a.length;a.forEach(function(m,v){return Se.resolve(m).then(function(E){a[v]=E,--y||l(a)},h)})})},resolve:function(a){return a instanceof Se?a:a&&typeof a.then=="function"?new Se(function(l,h){a.then(l,h)}):new Se(kn,!0,a)},reject:wr,race:function(){var a=_.apply(null,arguments).map(xr);return new Se(function(l,h){a.map(function(y){return Se.resolve(y).then(l,h)})})},PSD:{get:function(){return Le},set:function(a){return Le=a}},totalEchoes:{get:function(){return Er}},newPSD:Jt,usePSD:dn,scheduler:{get:function(){return An},set:function(a){An=a}},rejectionMapper:{get:function(){return tr},set:function(a){tr=a}},follow:function(a,l){return new Se(function(h,y){return Jt(function(m,v){var E=Le;E.unhandleds=[],E.onunhandled=v,E.finalize=gt(function(){var S,M=this;S=function(){M.unhandleds.length===0?m():v(M.unhandleds[0])},gr.push(function V(){S(),gr.splice(gr.indexOf(V),1)}),++Xt,An(function(){--Xt==0&&Jr()},[])},E.finalize),a()},l,h,y)})}}),Yt&&(Yt.allSettled&&A(Se,"allSettled",function(){var a=_.apply(null,arguments).map(xr);return new Se(function(l){a.length===0&&l([]);var h=a.length,y=new Array(h);a.forEach(function(m,v){return Se.resolve(m).then(function(E){return y[v]={status:"fulfilled",value:E}},function(E){return y[v]={status:"rejected",reason:E}}).then(function(){return--h||l(y)})})})}),Yt.any&&typeof AggregateError<"u"&&A(Se,"any",function(){var a=_.apply(null,arguments).map(xr);return new Se(function(l,h){a.length===0&&h(new AggregateError([]));var y=a.length,m=new Array(y);a.forEach(function(v,E){return Se.resolve(v).then(function(S){return l(S)},function(S){m[E]=S,--y||h(new AggregateError(m))})})})}),Yt.withResolvers)&&(Se.withResolvers=Yt.withResolvers);var ft={awaits:0,echoes:0,id:0},Li=0,vr=[],br=0,Er=0,ro=0;function Jt(a,E,h,y){var m=Le,v=Object.create(m),E=(v.parent=m,v.ref=0,v.global=!1,v.id=++ro,zt.env,v.env=pr?{Promise:Se,PromiseProp:{value:Se,configurable:!0,writable:!0},all:Se.all,race:Se.race,allSettled:Se.allSettled,any:Se.any,resolve:Se.resolve,reject:Se.reject}:{},E&&f(v,E),++m.ref,v.finalize=function(){--this.parent.ref||this.parent.finalize()},dn(v,a,h,y));return v.ref===0&&v.finalize(),E}function Tn(){return ft.id||(ft.id=++Li),++ft.awaits,ft.echoes+=Yr,ft.id}function Qt(){return!!ft.awaits&&(--ft.awaits==0&&(ft.id=0),ft.echoes=ft.awaits*Yr,!0)}function xr(a){return ft.echoes&&a&&a.constructor===Yt?(Tn(),a.then(function(l){return Qt(),l},function(l){return Qt(),st(l)})):a}function io(){var a=vr[vr.length-1];vr.pop(),en(a,!1)}function en(a,l){var h,y,m=Le;(l?!ft.echoes||br++&&a===Le:!br||--br&&a===Le)||queueMicrotask(l?(function(v){++Er,ft.echoes&&--ft.echoes!=0||(ft.echoes=ft.awaits=ft.id=0),vr.push(Le),en(v,!0)}).bind(null,a):io),a!==Le&&(Le=a,m===zt&&(zt.env=Mi()),pr)&&(h=zt.env.Promise,y=a.env,m.global||a.global)&&(Object.defineProperty(o,"Promise",y.PromiseProp),h.all=y.all,h.race=y.race,h.resolve=y.resolve,h.reject=y.reject,y.allSettled&&(h.allSettled=y.allSettled),y.any)&&(h.any=y.any)}function Mi(){var a=o.Promise;return pr?{Promise:a,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:a.all,race:a.race,allSettled:a.allSettled,any:a.any,resolve:a.resolve,reject:a.reject}:{}}function dn(a,l,h,y,m){var v=Le;try{return en(a,!0),l(h,y,m)}finally{en(v,!1)}}function Oi(a,l,h,y){return typeof a!="function"?a:function(){var m=Le;h&&Tn(),en(l,!0);try{return a.apply(this,arguments)}finally{en(m,!1),y&&queueMicrotask(Qt)}}}function Qr(a){Promise===Yt&&ft.echoes===0?br===0?a():enqueueNativeMicroTask(a):setTimeout(a,0)}(""+Rr).indexOf("[native code]")===-1&&(Tn=Qt=Ge);var st=Se.reject,tn="ï¿¿",_t="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",ei="String expected.",Ht="__dbnames",ti="readonly",In="readwrite";function qt(a,l){return a?l?function(){return a.apply(this,arguments)&&l.apply(this,arguments)}:a:l}var Di={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function _r(a){return typeof a!="string"||/\./.test(a)?function(l){return l}:function(l){return l[a]===void 0&&a in l&&delete(l=j(l))[a],l}}function kr(){throw Be.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function qe(a,l){try{var h=Ni(a),y=Ni(l);if(h!==y)return h==="Array"?1:y==="Array"?-1:h==="binary"?1:y==="binary"?-1:h==="string"?1:y==="string"?-1:h==="Date"?1:y!=="Date"?NaN:-1;switch(h){case"number":case"Date":case"string":return l<a?1:a<l?-1:0;case"binary":for(var m=b(a),v=b(l),E=m.length,S=v.length,M=E<S?E:S,V=0;V<M;++V)if(m[V]!==v[V])return m[V]<v[V]?-1:1;return E===S?0:E<S?-1:1;case"Array":for(var N=a,B=l,O=N.length,z=B.length,U=O<z?O:z,F=0;F<U;++F){var K=qe(N[F],B[F]);if(K!==0)return K}return O===z?0:O<z?-1:1}}catch{}return NaN}function Ni(a){var l=typeof a;return l=="object"&&(ArrayBuffer.isView(a)||(l=X(a))==="ArrayBuffer")?"binary":l}function b(a){return a instanceof Uint8Array?a:ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a)}function R(a,l,h){var y=a.schema.yProps;return y?(l&&0<h.numFailures&&(l=l.filter(function(m,v){return!h.failures[v]})),Promise.all(y.map(function(m){return m=m.updatesTable,l?a.db.table(m).where("k").anyOf(l).delete():a.db.table(m).clear()})).then(function(){return h})):h}D.prototype.execute=function(a){var l=this["@@propmod"];if(l.add!==void 0){var h=l.add;if(u(h))return s(s([],u(a)?a:[],!0),h).sort();if(typeof h=="number")return(Number(a)||0)+h;if(typeof h=="bigint")try{return BigInt(a)+h}catch{return BigInt(0)+h}throw new TypeError("Invalid term ".concat(h))}if(l.remove!==void 0){var y=l.remove;if(u(y))return u(a)?a.filter(function(m){return!y.includes(m)}).sort():[];if(typeof y=="number")return Number(a)-y;if(typeof y=="bigint")try{return BigInt(a)-y}catch{return BigInt(0)-y}throw new TypeError("Invalid subtrahend ".concat(y))}return h=(h=l.replacePrefix)==null?void 0:h[0],h&&typeof a=="string"&&a.startsWith(h)?l.replacePrefix[1]+a.substring(h.length):a};var k=D;function D(a){this["@@propmod"]=a}function q(a,l){for(var h=c(l),y=h.length,m=!1,v=0;v<y;++v){var E=h[v],S=l[E],M=Q(a,E);S instanceof k?(ie(a,E,S.execute(M)),m=!0):M!==S&&(ie(a,E,S),m=!0)}return m}J.prototype._trans=function(a,l,h){var y=this._tx||Le.trans,m=this.name,v=Rt&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(a==="readonly"?"read":"write"," ").concat(this.name));function E(V,N,B){if(B.schema[m])return l(B.idbtrans,B);throw new Be.NotFound("Table "+m+" not part of transaction")}var S=Rn();try{var M=y&&y.db._novip===this.db._novip?y===Le.trans?y._promise(a,E,h):Jt(function(){return y._promise(a,E,h)},{trans:y,transless:Le.transless||Le}):(function V(N,B,O,z){if(N.idbdb&&(N._state.openComplete||Le.letThrough||N._vip)){var U=N._createTransaction(B,O,N._dbSchema);try{U.create(),N._state.PR1398_maxLoop=3}catch(F){return F.name===Ue.InvalidState&&N.isOpen()&&0<--N._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),N.close({disableAutoOpen:!1}),N.open().then(function(){return V(N,B,O,z)})):st(F)}return U._promise(B,function(F,K){return Jt(function(){return Le.trans=U,z(F,K,U)})}).then(function(F){if(B==="readwrite")try{U.idbtrans.commit()}catch{}return B==="readonly"?F:U._completion.then(function(){return F})})}if(N._state.openComplete)return st(new Be.DatabaseClosed(N._state.dbOpenError));if(!N._state.isBeingOpened){if(!N._state.autoOpen)return st(new Be.DatabaseClosed);N.open().catch(Ge)}return N._state.dbReadyPromise.then(function(){return V(N,B,O,z)})})(this.db,a,[this.name],E);return v&&(M._consoleTask=v,M=M.catch(function(V){return console.trace(V),st(V)})),M}finally{S&&Cn()}},J.prototype.get=function(a,l){var h=this;return a&&a.constructor===Object?this.where(a).first(l):a==null?st(new Be.Type("Invalid argument to Table.get()")):this._trans("readonly",function(y){return h.core.get({trans:y,key:a}).then(function(m){return h.hook.reading.fire(m)})}).then(l)},J.prototype.where=function(a){if(typeof a=="string")return new this.db.WhereClause(this,a);if(u(a))return new this.db.WhereClause(this,"[".concat(a.join("+"),"]"));var l=c(a);if(l.length===1)return this.where(l[0]).equals(a[l[0]]);var h=this.schema.indexes.concat(this.schema.primKey).filter(function(S){if(S.compound&&l.every(function(V){return 0<=S.keyPath.indexOf(V)})){for(var M=0;M<l.length;++M)if(l.indexOf(S.keyPath[M])===-1)return!1;return!0}return!1}).sort(function(S,M){return S.keyPath.length-M.keyPath.length})[0];if(h&&this.db._maxKey!==tn)return E=h.keyPath.slice(0,l.length),this.where(E).equals(E.map(function(S){return a[S]}));!h&&Rt&&console.warn("The query ".concat(JSON.stringify(a)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(l.join("+"),"]"));var y=this.schema.idxByName;function m(S,M){return qe(S,M)===0}var E=l.reduce(function(N,M){var V=N[0],N=N[1],B=y[M],O=a[M];return[V||B,V||!B?qt(N,B&&B.multi?function(z){return z=Q(z,M),u(z)&&z.some(function(U){return m(O,U)})}:function(z){return m(O,Q(z,M))}):N]},[null,null]),v=E[0],E=E[1];return v?this.where(v.name).equals(a[v.keyPath]).filter(E):h?this.filter(E):this.where(l).equals("")},J.prototype.filter=function(a){return this.toCollection().and(a)},J.prototype.count=function(a){return this.toCollection().count(a)},J.prototype.offset=function(a){return this.toCollection().offset(a)},J.prototype.limit=function(a){return this.toCollection().limit(a)},J.prototype.each=function(a){return this.toCollection().each(a)},J.prototype.toArray=function(a){return this.toCollection().toArray(a)},J.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},J.prototype.orderBy=function(a){return new this.db.Collection(new this.db.WhereClause(this,u(a)?"[".concat(a.join("+"),"]"):a))},J.prototype.reverse=function(){return this.toCollection().reverse()},J.prototype.mapToClass=function(a){for(var l=this.db,h=this.name,y=((this.schema.mappedClass=a).prototype instanceof kr&&(a=(E=>{var S=N,M=E;if(typeof M!="function"&&M!==null)throw new TypeError("Class extends value "+String(M)+" is not a constructor or null");function V(){this.constructor=S}function N(){return E!==null&&E.apply(this,arguments)||this}return r(S,M),S.prototype=M===null?Object.create(M):(V.prototype=M.prototype,new V),Object.defineProperty(N.prototype,"db",{get:function(){return l},enumerable:!1,configurable:!0}),N.prototype.table=function(){return h},N})(a)),new Set),m=a.prototype;m;m=p(m))Object.getOwnPropertyNames(m).forEach(function(E){return y.add(E)});function v(E){if(!E)return E;var S,M=Object.create(a.prototype);for(S in E)if(!y.has(S))try{M[S]=E[S]}catch{}return M}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=v,this.hook("reading",v),a},J.prototype.defineClass=function(){return this.mapToClass(function(a){f(this,a)})},J.prototype.add=function(a,l){var h=this,y=this.schema.primKey,m=y.auto,v=y.keyPath,E=a;return v&&m&&(E=_r(v)(a)),this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"add",keys:l!=null?[l]:null,values:[E]})}).then(function(S){return S.numFailures?Se.reject(S.failures[0]):S.lastResult}).then(function(S){if(v)try{ie(a,v,S)}catch{}return S})},J.prototype.upsert=function(a,l){var h=this,y=this.schema.primKey.keyPath;return this._trans("readwrite",function(m){return h.core.get({trans:m,key:a}).then(function(v){var E=v??{};return q(E,l),y&&ie(E,y,a),h.core.mutate({trans:m,type:"put",values:[E],keys:[a],upsert:!0,updates:{keys:[a],changeSpecs:[l]}}).then(function(S){return S.numFailures?Se.reject(S.failures[0]):!!v})})})},J.prototype.update=function(a,l){return typeof a!="object"||u(a)?this.where(":id").equals(a).modify(l):(a=Q(a,this.schema.primKey.keyPath))===void 0?st(new Be.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(a).modify(l)},J.prototype.put=function(a,l){var h=this,y=this.schema.primKey,m=y.auto,v=y.keyPath,E=a;return v&&m&&(E=_r(v)(a)),this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"put",values:[E],keys:l!=null?[l]:null})}).then(function(S){return S.numFailures?Se.reject(S.failures[0]):S.lastResult}).then(function(S){if(v)try{ie(a,v,S)}catch{}return S})},J.prototype.delete=function(a){var l=this;return this._trans("readwrite",function(h){return l.core.mutate({trans:h,type:"delete",keys:[a]}).then(function(y){return R(l,[a],y)}).then(function(y){return y.numFailures?Se.reject(y.failures[0]):void 0})})},J.prototype.clear=function(){var a=this;return this._trans("readwrite",function(l){return a.core.mutate({trans:l,type:"deleteRange",range:Di}).then(function(h){return R(a,null,h)})}).then(function(l){return l.numFailures?Se.reject(l.failures[0]):void 0})},J.prototype.bulkGet=function(a){var l=this;return this._trans("readonly",function(h){return l.core.getMany({keys:a,trans:h}).then(function(y){return y.map(function(m){return l.hook.reading.fire(m)})})})},J.prototype.bulkAdd=function(a,l,h){var y=this,m=Array.isArray(l)?l:void 0,v=(h=h||(m?void 0:l))?h.allKeys:void 0;return this._trans("readwrite",function(E){var S=y.schema.primKey,V=S.auto,S=S.keyPath;if(S&&m)throw new Be.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(m&&m.length!==a.length)throw new Be.InvalidArgument("Arguments objects and keys must have the same length");var M=a.length,V=S&&V?a.map(_r(S)):a;return y.core.mutate({trans:E,type:"add",keys:m,values:V,wantResults:v}).then(function(N){var B=N.numFailures,O=N.failures;if(B===0)return v?N.results:N.lastResult;throw new Ve("".concat(y.name,".bulkAdd(): ").concat(B," of ").concat(M," operations failed"),O)})})},J.prototype.bulkPut=function(a,l,h){var y=this,m=Array.isArray(l)?l:void 0,v=(h=h||(m?void 0:l))?h.allKeys:void 0;return this._trans("readwrite",function(E){var S=y.schema.primKey,V=S.auto,S=S.keyPath;if(S&&m)throw new Be.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(m&&m.length!==a.length)throw new Be.InvalidArgument("Arguments objects and keys must have the same length");var M=a.length,V=S&&V?a.map(_r(S)):a;return y.core.mutate({trans:E,type:"put",keys:m,values:V,wantResults:v}).then(function(N){var B=N.numFailures,O=N.failures;if(B===0)return v?N.results:N.lastResult;throw new Ve("".concat(y.name,".bulkPut(): ").concat(B," of ").concat(M," operations failed"),O)})})},J.prototype.bulkUpdate=function(a){var l=this,h=this.core,y=a.map(function(E){return E.key}),m=a.map(function(E){return E.changes}),v=[];return this._trans("readwrite",function(E){return h.getMany({trans:E,keys:y,cache:"clone"}).then(function(S){var M=[],V=[],N=(a.forEach(function(B,O){var z=B.key,U=B.changes,F=S[O];if(F){for(var K=0,Z=Object.keys(U);K<Z.length;K++){var G=Z[K],ne=U[G];if(G===l.schema.primKey.keyPath){if(qe(ne,z)!==0)throw new Be.Constraint("Cannot update primary key in bulkUpdate()")}else ie(F,G,ne)}v.push(O),M.push(z),V.push(F)}}),M.length);return h.mutate({trans:E,type:"put",keys:M,values:V,updates:{keys:y,changeSpecs:m}}).then(function(B){var O=B.numFailures,z=B.failures;if(O===0)return N;for(var U=0,F=Object.keys(z);U<F.length;U++){var K,Z=F[U],G=v[Number(Z)];G!=null&&(K=z[Z],delete z[Z],z[G]=K)}throw new Ve("".concat(l.name,".bulkUpdate(): ").concat(O," of ").concat(N," operations failed"),z)})})})},J.prototype.bulkDelete=function(a){var l=this,h=a.length;return this._trans("readwrite",function(y){return l.core.mutate({trans:y,type:"delete",keys:a}).then(function(m){return R(l,a,m)})}).then(function(y){var m=y.numFailures,v=y.failures;if(m===0)return y.lastResult;throw new Ve("".concat(l.name,".bulkDelete(): ").concat(m," of ").concat(h," operations failed"),v)})};var L=J;function J(){}function oe(a){function l(E,S){if(S){for(var M=arguments.length,V=new Array(M-1);--M;)V[M-1]=arguments[M];return h[E].subscribe.apply(null,V),a}if(typeof E=="string")return h[E]}var h={};l.addEventType=v;for(var y=1,m=arguments.length;y<m;++y)v(arguments[y]);return l;function v(E,S,M){var V,N;if(typeof E!="object")return S=S||Vr,N={subscribers:[],fire:M=M||Ge,subscribe:function(B){N.subscribers.indexOf(B)===-1&&(N.subscribers.push(B),N.fire=S(N.fire,B))},unsubscribe:function(B){N.subscribers=N.subscribers.filter(function(O){return O!==B}),N.fire=N.subscribers.reduce(S,M)}},h[E]=l[E]=N;c(V=E).forEach(function(B){var O=V[B];if(u(O))v(B,V[B][0],V[B][1]);else{if(O!=="asap")throw new Be.InvalidArgument("Invalid event config");var z=v(B,Xn,function(){for(var U=arguments.length,F=new Array(U);U--;)F[U]=arguments[U];z.subscribers.forEach(function(K){Y(function(){K.apply(null,F)})})})}})}}function he(a,l){return I(l).from({prototype:a}),l}function de(a,l){return!(a.filter||a.algorithm||a.or)&&(l?a.justLimit:!a.replayFilter)}function be(a,l){a.filter=qt(a.filter,l)}function Te(a,l,h){var y=a.replayFilter;a.replayFilter=y?function(){return qt(y(),l())}:l,a.justLimit=h&&!y}function $e(a,l){if(a.isPrimKey)return l.primaryKey;var h=l.getIndexByKeyPath(a.index);if(h)return h;throw new Be.Schema("KeyPath "+a.index+" on object store "+l.name+" is not indexed")}function Ye(a,l,h){var y=$e(a,l.schema);return l.openCursor({trans:h,values:!a.keysOnly,reverse:a.dir==="prev",unique:!!a.unique,query:{index:y,range:a.range}})}function je(a,l,h,y){var m,v,E=a.replayFilter?qt(a.filter,a.replayFilter()):a.filter;return a.or?(m={},v=function(S,M,V){var N,B;E&&!E(M,V,function(O){return M.stop(O)},function(O){return M.fail(O)})||((B=""+(N=M.primaryKey))=="[object ArrayBuffer]"&&(B=""+new Uint8Array(N)),g(m,B))||(m[B]=!0,l(S,M,V))},Promise.all([a.or._iterate(v,h),ot(Ye(a,y,h),a.algorithm,v,!a.keysOnly&&a.valueMapper)])):ot(Ye(a,y,h),qt(a.algorithm,E),l,!a.keysOnly&&a.valueMapper)}function ot(a,l,h,y){var m=et(y?function(v,E,S){return h(y(v),E,S)}:h);return a.then(function(v){if(v)return v.start(function(){var E=function(){return v.continue()};l&&!l(v,function(S){return E=S},function(S){v.stop(S),E=Ge},function(S){v.fail(S),E=Ge})||m(v.value,v,function(S){return E=S}),E()})})}Pe.prototype._read=function(a,l){var h=this._ctx;return h.error?h.table._trans(null,st.bind(null,h.error)):h.table._trans("readonly",a).then(l)},Pe.prototype._write=function(a){var l=this._ctx;return l.error?l.table._trans(null,st.bind(null,l.error)):l.table._trans("readwrite",a,"locked")},Pe.prototype._addAlgorithm=function(a){var l=this._ctx;l.algorithm=qt(l.algorithm,a)},Pe.prototype._iterate=function(a,l){return je(this._ctx,a,l,this._ctx.table.core)},Pe.prototype.clone=function(a){var l=Object.create(this.constructor.prototype),h=Object.create(this._ctx);return a&&f(h,a),l._ctx=h,l},Pe.prototype.raw=function(){return this._ctx.valueMapper=null,this},Pe.prototype.each=function(a){var l=this._ctx;return this._read(function(h){return je(l,a,h,l.table.core)})},Pe.prototype.count=function(a){var l=this;return this._read(function(h){var y,m=l._ctx,v=m.table.core;return de(m,!0)?v.count({trans:h,query:{index:$e(m,v.schema),range:m.range}}).then(function(E){return Math.min(E,m.limit)}):(y=0,je(m,function(){return++y,!1},h,v).then(function(){return y}))}).then(a)},Pe.prototype.sortBy=function(a,l){var h=a.split(".").reverse(),y=h[0],m=h.length-1;function v(M,V){return V?v(M[h[V]],V-1):M[y]}var E=this._ctx.dir==="next"?1:-1;function S(M,V){return qe(v(M,m),v(V,m))*E}return this.toArray(function(M){return M.slice().sort(S)}).then(l)},Pe.prototype.toArray=function(a){var l=this;return this._read(function(h){var y,m,v,E=l._ctx;return de(E,!0)&&0<E.limit?(y=E.valueMapper,m=$e(E,E.table.core.schema),E.table.core.query({trans:h,limit:E.limit,values:!0,direction:E.dir==="prev"?"prev":void 0,query:{index:m,range:E.range}}).then(function(S){return S=S.result,y?S.map(y):S})):(v=[],je(E,function(S){return v.push(S)},h,E.table.core).then(function(){return v}))},a)},Pe.prototype.offset=function(a){var l=this._ctx;return a<=0||(l.offset+=a,de(l)?Te(l,function(){var h=a;return function(y,m){return h===0||(h===1?--h:m(function(){y.advance(h),h=0}),!1)}}):Te(l,function(){var h=a;return function(){return--h<0}})),this},Pe.prototype.limit=function(a){return this._ctx.limit=Math.min(this._ctx.limit,a),Te(this._ctx,function(){var l=a;return function(h,y,m){return--l<=0&&y(m),0<=l}},!0),this},Pe.prototype.until=function(a,l){return be(this._ctx,function(h,y,m){return!a(h.value)||(y(m),l)}),this},Pe.prototype.first=function(a){return this.limit(1).toArray(function(l){return l[0]}).then(a)},Pe.prototype.last=function(a){return this.reverse().first(a)},Pe.prototype.filter=function(a){var l;return be(this._ctx,function(h){return a(h.value)}),(l=this._ctx).isMatch=qt(l.isMatch,a),this},Pe.prototype.and=function(a){return this.filter(a)},Pe.prototype.or=function(a){return new this.db.WhereClause(this._ctx.table,a,this)},Pe.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Pe.prototype.desc=function(){return this.reverse()},Pe.prototype.eachKey=function(a){var l=this._ctx;return l.keysOnly=!l.isMatch,this.each(function(h,y){a(y.key,y)})},Pe.prototype.eachUniqueKey=function(a){return this._ctx.unique="unique",this.eachKey(a)},Pe.prototype.eachPrimaryKey=function(a){var l=this._ctx;return l.keysOnly=!l.isMatch,this.each(function(h,y){a(y.primaryKey,y)})},Pe.prototype.keys=function(a){var l=this._ctx,h=(l.keysOnly=!l.isMatch,[]);return this.each(function(y,m){h.push(m.key)}).then(function(){return h}).then(a)},Pe.prototype.primaryKeys=function(a){var l=this._ctx;if(de(l,!0)&&0<l.limit)return this._read(function(y){var m=$e(l,l.table.core.schema);return l.table.core.query({trans:y,values:!1,limit:l.limit,direction:l.dir==="prev"?"prev":void 0,query:{index:m,range:l.range}})}).then(function(y){return y.result}).then(a);l.keysOnly=!l.isMatch;var h=[];return this.each(function(y,m){h.push(m.primaryKey)}).then(function(){return h}).then(a)},Pe.prototype.uniqueKeys=function(a){return this._ctx.unique="unique",this.keys(a)},Pe.prototype.firstKey=function(a){return this.limit(1).keys(function(l){return l[0]}).then(a)},Pe.prototype.lastKey=function(a){return this.reverse().firstKey(a)},Pe.prototype.distinct=function(){var a,l=this._ctx,l=l.index&&l.table.schema.idxByName[l.index];return l&&l.multi&&(a={},be(this._ctx,function(y){var y=y.primaryKey.toString(),m=g(a,y);return a[y]=!0,!m})),this},Pe.prototype.modify=function(a){var l=this,h=this._ctx;return this._write(function(y){function m(F,K){var Z=K.failures;O+=F-K.numFailures;for(var G=0,ne=c(Z);G<ne.length;G++){var ce=ne[G];B.push(Z[ce])}}var v=typeof a=="function"?a:function(F){return q(F,a)},E=h.table.core,N=E.schema.primaryKey,S=N.outbound,M=N.extractKey,V=200,N=l.db._options.modifyChunkSize,B=(N&&(V=typeof N=="object"?N[E.name]||N["*"]||200:N),[]),O=0,z=[],U=a===Bn;return l.clone().primaryKeys().then(function(F){function K(G){var ne=Math.min(V,F.length-G),ce=F.slice(G,G+ne);return(U?Promise.resolve([]):E.getMany({trans:y,keys:ce,cache:"immutable"})).then(function(fe){var Ee=[],me=[],Ae=S?[]:null,ve=U?ce:[];if(!U)for(var Ie=0;Ie<ne;++Ie){var ue=fe[Ie],De={value:j(ue),primKey:F[G+Ie]};v.call(De,De.value,De)!==!1&&(De.value==null?ve.push(F[G+Ie]):S||qe(M(ue),M(De.value))===0?(me.push(De.value),S&&Ae.push(F[G+Ie])):(ve.push(F[G+Ie]),Ee.push(De.value)))}return Promise.resolve(0<Ee.length&&E.mutate({trans:y,type:"add",values:Ee}).then(function(Ne){for(var ze in Ne.failures)ve.splice(parseInt(ze),1);m(Ee.length,Ne)})).then(function(){return(0<me.length||Z&&typeof a=="object")&&E.mutate({trans:y,type:"put",keys:Ae,values:me,criteria:Z,changeSpec:typeof a!="function"&&a,isAdditionalChunk:0<G}).then(function(Ne){return m(me.length,Ne)})}).then(function(){return(0<ve.length||Z&&U)&&E.mutate({trans:y,type:"delete",keys:ve,criteria:Z,isAdditionalChunk:0<G}).then(function(Ne){return R(h.table,ve,Ne)}).then(function(Ne){return m(ve.length,Ne)})}).then(function(){return F.length>G+ne&&K(G+V)})})}var Z=de(h)&&h.limit===1/0&&(typeof a!="function"||U)&&{index:h.index,range:h.range};return K(0).then(function(){if(0<B.length)throw new Me("Error modifying one or more objects",B,O,z);return F.length})})})},Pe.prototype.delete=function(){var a=this._ctx,l=a.range;return!de(a)||a.table.schema.yProps||!a.isPrimKey&&l.type!==3?this.modify(Bn):this._write(function(h){var y=a.table.core.schema.primaryKey,m=l;return a.table.core.count({trans:h,query:{index:y,range:m}}).then(function(v){return a.table.core.mutate({trans:h,type:"deleteRange",range:m}).then(function(M){var S=M.failures,M=M.numFailures;if(M)throw new Me("Could not delete some values",Object.keys(S).map(function(V){return S[V]}),v-M);return v-M})})})};var at=Pe;function Pe(){}var Bn=function(a,l){return l.value=null};function ni(a,l){return a<l?-1:a===l?0:1}function so(a,l){return l<a?-1:a===l?0:1}function pt(a,l,h){return a=a instanceof eu?new a.Collection(a):a,a._ctx.error=new(h||TypeError)(l),a}function nr(a){return new a.Collection(a,function(){return ri("")}).limit(0)}function Sr(z,l,h,y){var m,v,E,S,M,V,N,B=h.length;if(!h.every(function(F){return typeof F=="string"}))return pt(z,ei);function O(F){m=F==="next"?function(Z){return Z.toUpperCase()}:function(Z){return Z.toLowerCase()},v=F==="next"?function(Z){return Z.toLowerCase()}:function(Z){return Z.toUpperCase()},E=F==="next"?ni:so;var K=h.map(function(Z){return{lower:v(Z),upper:m(Z)}}).sort(function(Z,G){return E(Z.lower,G.lower)});S=K.map(function(Z){return Z.upper}),M=K.map(function(Z){return Z.lower}),N=(V=F)==="next"?"":y}O("next");var z=new z.Collection(z,function(){return nn(S[0],M[B-1]+y)}),U=(z._ondirectionchange=function(F){O(F)},0);return z._addAlgorithm(function(F,K,Z){var G=F.key;if(typeof G=="string"){var ne=v(G);if(l(ne,M,U))return!0;for(var ce=null,fe=U;fe<B;++fe){var Ee=((me,Ae,ve,Ie,ue,De)=>{for(var Ne=Math.min(me.length,Ie.length),ze=-1,We=0;We<Ne;++We){var Lt=Ae[We];if(Lt!==Ie[We])return ue(me[We],ve[We])<0?me.substr(0,We)+ve[We]+ve.substr(We+1):ue(me[We],Ie[We])<0?me.substr(0,We)+Ie[We]+ve.substr(We+1):0<=ze?me.substr(0,ze)+Ae[ze]+ve.substr(ze+1):null;ue(me[We],Lt)<0&&(ze=We)}return Ne<Ie.length&&De==="next"?me+ve.substr(me.length):Ne<me.length&&De==="prev"?me.substr(0,ve.length):ze<0?null:me.substr(0,ze)+Ie[ze]+ve.substr(ze+1)})(G,ne,S[fe],M[fe],E,V);Ee===null&&ce===null?U=fe+1:(ce===null||0<E(ce,Ee))&&(ce=Ee)}K(ce!==null?function(){F.continue(ce+N)}:Z)}return!1}),z}function nn(a,l,h,y){return{type:2,lower:a,upper:l,lowerOpen:h,upperOpen:y}}function ri(a){return{type:1,lower:a,upper:a}}Object.defineProperty(dt.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),dt.prototype.between=function(a,l,h,y){h=h!==!1,y=y===!0;try{return 0<this._cmp(a,l)||this._cmp(a,l)===0&&(h||y)&&(!h||!y)?nr(this):new this.Collection(this,function(){return nn(a,l,!h,!y)})}catch{return pt(this,_t)}},dt.prototype.equals=function(a){return a==null?pt(this,_t):new this.Collection(this,function(){return ri(a)})},dt.prototype.above=function(a){return a==null?pt(this,_t):new this.Collection(this,function(){return nn(a,void 0,!0)})},dt.prototype.aboveOrEqual=function(a){return a==null?pt(this,_t):new this.Collection(this,function(){return nn(a,void 0,!1)})},dt.prototype.below=function(a){return a==null?pt(this,_t):new this.Collection(this,function(){return nn(void 0,a,!1,!0)})},dt.prototype.belowOrEqual=function(a){return a==null?pt(this,_t):new this.Collection(this,function(){return nn(void 0,a)})},dt.prototype.startsWith=function(a){return typeof a!="string"?pt(this,ei):this.between(a,a+tn,!0,!0)},dt.prototype.startsWithIgnoreCase=function(a){return a===""?this.startsWith(a):Sr(this,function(l,h){return l.indexOf(h[0])===0},[a],tn)},dt.prototype.equalsIgnoreCase=function(a){return Sr(this,function(l,h){return l===h[0]},[a],"")},dt.prototype.anyOfIgnoreCase=function(){var a=_.apply(_e,arguments);return a.length===0?nr(this):Sr(this,function(l,h){return h.indexOf(l)!==-1},a,"")},dt.prototype.startsWithAnyOfIgnoreCase=function(){var a=_.apply(_e,arguments);return a.length===0?nr(this):Sr(this,function(l,h){return h.some(function(y){return l.indexOf(y)===0})},a,tn)},dt.prototype.anyOf=function(){var a,l,h=this,y=_.apply(_e,arguments),m=this._cmp;try{y.sort(m)}catch{return pt(this,_t)}return y.length===0?nr(this):((a=new this.Collection(this,function(){return nn(y[0],y[y.length-1])}))._ondirectionchange=function(v){m=v==="next"?h._ascending:h._descending,y.sort(m)},l=0,a._addAlgorithm(function(v,E,S){for(var M=v.key;0<m(M,y[l]);)if(++l===y.length)return E(S),!1;return m(M,y[l])===0||(E(function(){v.continue(y[l])}),!1)}),a)},dt.prototype.notEqual=function(a){return this.inAnyRange([[-1/0,a],[a,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},dt.prototype.noneOf=function(){var a=_.apply(_e,arguments);if(a.length===0)return new this.Collection(this);try{a.sort(this._ascending)}catch{return pt(this,_t)}var l=a.reduce(function(h,y){return h?h.concat([[h[h.length-1][1],y]]):[[-1/0,y]]},null);return l.push([a[a.length-1],this.db._maxKey]),this.inAnyRange(l,{includeLowers:!1,includeUppers:!1})},dt.prototype.inAnyRange=function(a,Z){var h=this,y=this._cmp,m=this._ascending,v=this._descending,E=this._min,S=this._max;if(a.length===0)return nr(this);if(!a.every(function(G){return G[0]!==void 0&&G[1]!==void 0&&m(G[0],G[1])<=0}))return pt(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Be.InvalidArgument);var M=!Z||Z.includeLowers!==!1,V=Z&&Z.includeUppers===!0,N,B=m;function O(G,ne){return B(G[0],ne[0])}try{(N=a.reduce(function(G,ne){for(var ce=0,fe=G.length;ce<fe;++ce){var Ee=G[ce];if(y(ne[0],Ee[1])<0&&0<y(ne[1],Ee[0])){Ee[0]=E(Ee[0],ne[0]),Ee[1]=S(Ee[1],ne[1]);break}}return ce===fe&&G.push(ne),G},[])).sort(O)}catch{return pt(this,_t)}var z=0,U=V?function(G){return 0<m(G,N[z][1])}:function(G){return 0<=m(G,N[z][1])},F=M?function(G){return 0<v(G,N[z][0])}:function(G){return 0<=v(G,N[z][0])},K=U,Z=new this.Collection(this,function(){return nn(N[0][0],N[N.length-1][1],!M,!V)});return Z._ondirectionchange=function(G){B=G==="next"?(K=U,m):(K=F,v),N.sort(O)},Z._addAlgorithm(function(G,ne,ce){for(var fe,Ee=G.key;K(Ee);)if(++z===N.length)return ne(ce),!1;return!U(fe=Ee)&&!F(fe)||(h._cmp(Ee,N[z][1])===0||h._cmp(Ee,N[z][0])===0||ne(function(){B===m?G.continue(N[z][0]):G.continue(N[z][1])}),!1)}),Z},dt.prototype.startsWithAnyOf=function(){var a=_.apply(_e,arguments);return a.every(function(l){return typeof l=="string"})?a.length===0?nr(this):this.inAnyRange(a.map(function(l){return[l,l+tn]})):pt(this,"startsWithAnyOf() only works with strings")};var eu=dt;function dt(){}function Wt(a){return et(function(l){return ii(l),a(l.target.error),!1})}function ii(a){a.stopPropagation&&a.stopPropagation(),a.preventDefault&&a.preventDefault()}var Pi="storagemutated",oo="x-storagemutated-1",Ln=oe(null,Pi),Od=(rn.prototype._lock=function(){return le(!Le.global),++this._reculock,this._reculock!==1||Le.global||(Le.lockOwnerFor=this),this},rn.prototype._unlock=function(){if(le(!Le.global),--this._reculock==0)for(Le.global||(Le.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var a=this._blockedFuncs.shift();try{dn(a[1],a[0])}catch{}}return this},rn.prototype._locked=function(){return this._reculock&&Le.lockOwnerFor!==this},rn.prototype.create=function(a){var l=this;if(this.mode){var h=this.db.idbdb,y=this.db._state.dbOpenError;if(le(!this.idbtrans),!a&&!h)switch(y&&y.name){case"DatabaseClosedError":throw new Be.DatabaseClosed(y);case"MissingAPIError":throw new Be.MissingAPI(y.message,y);default:throw new Be.OpenFailed(y)}if(!this.active)throw new Be.TransactionInactive;le(this._completion._state===null),(a=this.idbtrans=a||(this.db.core||h).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=et(function(m){ii(m),l._reject(a.error)}),a.onabort=et(function(m){ii(m),l.active&&l._reject(new Be.Abort(a.error)),l.active=!1,l.on("abort").fire(m)}),a.oncomplete=et(function(){l.active=!1,l._resolve(),"mutatedParts"in a&&Ln.storagemutated.fire(a.mutatedParts)})}return this},rn.prototype._promise=function(a,l,h){var y,m=this;return a==="readwrite"&&this.mode!=="readwrite"?st(new Be.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Se(function(v,E){m._blockedFuncs.push([function(){m._promise(a,l,h).then(v,E)},Le])}):h?Jt(function(){var v=new Se(function(E,S){m._lock();var M=l(E,S,m);M&&M.then&&M.then(E,S)});return v.finally(function(){return m._unlock()}),v._lib=!0,v}):((y=new Se(function(v,E){var S=l(v,E,m);S&&S.then&&S.then(v,E)}))._lib=!0,y):st(new Be.TransactionInactive)},rn.prototype._root=function(){return this.parent?this.parent._root():this},rn.prototype.waitFor=function(a){var l,h=this._root(),y=Se.resolve(a),m=(h._waitingFor?h._waitingFor=h._waitingFor.then(function(){return y}):(h._waitingFor=y,h._waitingQueue=[],l=h.idbtrans.objectStore(h.storeNames[0]),(function v(){for(++h._spinCount;h._waitingQueue.length;)h._waitingQueue.shift()();h._waitingFor&&(l.get(-1/0).onsuccess=v)})()),h._waitingFor);return new Se(function(v,E){y.then(function(S){return h._waitingQueue.push(et(v.bind(null,S)))},function(S){return h._waitingQueue.push(et(E.bind(null,S)))}).finally(function(){h._waitingFor===m&&(h._waitingFor=null)})})},rn.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Be.Abort))},rn.prototype.table=function(a){var l=this._memoizedTables||(this._memoizedTables={});if(g(l,a))return l[a];var h=this.schema[a];if(h)return(h=new this.db.Table(a,h,this)).core=this.db.core.table(a),l[a]=h;throw new Be.NotFound("Table "+a+" not part of transaction")},rn);function rn(){}function ao(a,l,h,y,m,v,E,S){return{name:a,keyPath:l,unique:h,multi:y,auto:m,compound:v,src:(h&&!E?"&":"")+(y?"*":"")+(m?"++":"")+tu(l),type:S}}function tu(a){return typeof a=="string"?a:a?"["+[].join.call(a,"+")+"]":""}function co(a,l,h){return{name:a,primKey:l,indexes:h,mappedClass:null,idxByName:(y=function(m){return[m.name,m]},h.reduce(function(m,v,E){return v=y(v,E),v&&(m[v[0]]=v[1]),m},{}))};var y}var si=function(a){try{return a.only([[]]),si=function(){return[[]]},[[]]}catch{return si=function(){return tn},tn}};function uo(a){return a==null?function(){}:typeof a=="string"?(l=a).split(".").length===1?function(h){return h[l]}:function(h){return Q(h,l)}:function(h){return Q(h,a)};var l}function nu(a){return[].slice.call(a)}var Dd=0;function oi(a){return a==null?":id":typeof a=="string"?a:"[".concat(a.join("+"),"]")}function Nd(a,l,E){function y(K){if(K.type===3)return null;if(K.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var z=K.lower,U=K.upper,F=K.lowerOpen,K=K.upperOpen;return z===void 0?U===void 0?null:l.upperBound(U,!!K):U===void 0?l.lowerBound(z,!!F):l.bound(z,U,!!F,!!K)}function m(O){var z,U,F=O.name;return{name:F,schema:O,mutate:function(K){var Z=K.trans,G=K.type,ne=K.keys,ce=K.values,fe=K.range;return new Promise(function(Ee,me){Ee=et(Ee);var Ae=Z.objectStore(F),ve=Ae.keyPath==null,Ie=G==="put"||G==="add";if(!Ie&&G!=="delete"&&G!=="deleteRange")throw new Error("Invalid operation type: "+G);var ue,De=(ne||ce||{length:1}).length;if(ne&&ce&&ne.length!==ce.length)throw new Error("Given keys array must have same length as given values array.");if(De===0)return Ee({numFailures:0,failures:{},results:[],lastResult:void 0});function Ne(kt){++Lt,ii(kt)}var ze=[],We=[],Lt=0;if(G==="deleteRange"){if(fe.type===4)return Ee({numFailures:Lt,failures:We,results:[],lastResult:void 0});fe.type===3?ze.push(ue=Ae.clear()):ze.push(ue=Ae.delete(y(fe)))}else{var ve=Ie?ve?[ce,ne]:[ce,null]:[ne,null],Ke=ve[0],vt=ve[1];if(Ie)for(var bt=0;bt<De;++bt)ze.push(ue=vt&&vt[bt]!==void 0?Ae[G](Ke[bt],vt[bt]):Ae[G](Ke[bt])),ue.onerror=Ne;else for(bt=0;bt<De;++bt)ze.push(ue=Ae[G](Ke[bt])),ue.onerror=Ne}function Yi(kt){kt=kt.target.result,ze.forEach(function(sr,Co){return sr.error!=null&&(We[Co]=sr.error)}),Ee({numFailures:Lt,failures:We,results:G==="delete"?ne:ze.map(function(sr){return sr.result}),lastResult:kt})}ue.onerror=function(kt){Ne(kt),Yi(kt)},ue.onsuccess=Yi})},getMany:function(K){var Z=K.trans,G=K.keys;return new Promise(function(ne,ce){ne=et(ne);for(var fe,Ee=Z.objectStore(F),me=G.length,Ae=new Array(me),ve=0,Ie=0,ue=function(ze){ze=ze.target,Ae[ze._pos]=ze.result,++Ie===ve&&ne(Ae)},De=Wt(ce),Ne=0;Ne<me;++Ne)G[Ne]!=null&&((fe=Ee.get(G[Ne]))._pos=Ne,fe.onsuccess=ue,fe.onerror=De,++ve);ve===0&&ne(Ae)})},get:function(K){var Z=K.trans,G=K.key;return new Promise(function(ne,ce){ne=et(ne);var fe=Z.objectStore(F).get(G);fe.onsuccess=function(Ee){return ne(Ee.target.result)},fe.onerror=Wt(ce)})},query:(z=M,U=V,function(K){return new Promise(function(Z,G){Z=et(Z);var ne,ce,fe,Ee,De=K.trans,me=K.values,Ae=K.limit,ue=K.query,ve=(ve=K.direction)!=null?ve:"next",Ie=Ae===1/0?void 0:Ae,Ne=ue.index,ue=ue.range,De=De.objectStore(F),De=Ne.isPrimaryKey?De:De.index(Ne.name),Ne=y(ue);if(Ae===0)return Z({result:[]});U?(ue={query:Ne,count:Ie,direction:ve},(ne=me?De.getAll(ue):De.getAllKeys(ue)).onsuccess=function(ze){return Z({result:ze.target.result})},ne.onerror=Wt(G)):z&&ve==="next"?((ne=me?De.getAll(Ne,Ie):De.getAllKeys(Ne,Ie)).onsuccess=function(ze){return Z({result:ze.target.result})},ne.onerror=Wt(G)):(ce=0,fe=!me&&"openKeyCursor"in De?De.openKeyCursor(Ne,ve):De.openCursor(Ne,ve),Ee=[],fe.onsuccess=function(){var ze=fe.result;return!ze||(Ee.push(me?ze.value:ze.primaryKey),++ce===Ae)?Z({result:Ee}):void ze.continue()},fe.onerror=Wt(G))})}),openCursor:function(K){var Z=K.trans,G=K.values,ne=K.query,ce=K.reverse,fe=K.unique;return new Promise(function(Ee,me){Ee=et(Ee);var Ie=ne.index,Ae=ne.range,ve=Z.objectStore(F),ve=Ie.isPrimaryKey?ve:ve.index(Ie.name),Ie=ce?fe?"prevunique":"prev":fe?"nextunique":"next",ue=!G&&"openKeyCursor"in ve?ve.openKeyCursor(y(Ae),Ie):ve.openCursor(y(Ae),Ie);ue.onerror=Wt(me),ue.onsuccess=et(function(De){var Ne,ze,We,Lt,Ke=ue.result;Ke?(Ke.___id=++Dd,Ke.done=!1,Ne=Ke.continue.bind(Ke),ze=(ze=Ke.continuePrimaryKey)&&ze.bind(Ke),We=Ke.advance.bind(Ke),Lt=function(){throw new Error("Cursor not stopped")},Ke.trans=Z,Ke.stop=Ke.continue=Ke.continuePrimaryKey=Ke.advance=function(){throw new Error("Cursor not started")},Ke.fail=et(me),Ke.next=function(){var vt=this,bt=1;return this.start(function(){return bt--?vt.continue():vt.stop()}).then(function(){return vt})},Ke.start=function(vt){function bt(){if(ue.result)try{vt()}catch(kt){Ke.fail(kt)}else Ke.done=!0,Ke.start=function(){throw new Error("Cursor behind last entry")},Ke.stop()}var Yi=new Promise(function(kt,sr){kt=et(kt),ue.onerror=Wt(sr),Ke.fail=sr,Ke.stop=function(Co){Ke.stop=Ke.continue=Ke.continuePrimaryKey=Ke.advance=Lt,kt(Co)}});return ue.onsuccess=et(function(kt){ue.onsuccess=bt,bt()}),Ke.continue=Ne,Ke.continuePrimaryKey=ze,Ke.advance=We,bt(),Yi},Ee(Ke)):Ee(null)},me)})},count:function(K){var Z=K.query,G=K.trans,ne=Z.index,ce=Z.range;return new Promise(function(fe,Ee){var me=G.objectStore(F),me=ne.isPrimaryKey?me:me.index(ne.name),Ae=y(ce),Ae=Ae?me.count(Ae):me.count();Ae.onsuccess=et(function(ve){return fe(ve.target.result)}),Ae.onerror=Wt(Ee)})}}}v=E,S=nu((E=a).objectStoreNames),N=0<S.length?v.objectStore(S[0]):{};var v,E={schema:{name:E.name,tables:S.map(function(O){return v.objectStore(O)}).map(function(O){var z=O.keyPath,U=O.autoIncrement,K=u(z),F={},K={name:O.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:z==null,compound:K,keyPath:z,autoIncrement:U,unique:!0,extractKey:uo(z)},indexes:nu(O.indexNames).map(function(Z){return O.index(Z)}).map(function(ce){var fe=ce.name,G=ce.unique,ne=ce.multiEntry,ce=ce.keyPath,fe={name:fe,compound:u(ce),keyPath:ce,unique:G,multiEntry:ne,extractKey:uo(ce)};return F[oi(ce)]=fe}),getIndexByKeyPath:function(Z){return F[oi(Z)]}};return F[":id"]=K.primaryKey,z!=null&&(F[oi(z)]=K.primaryKey),K})},hasGetAll:0<S.length&&"getAll"in N&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in N},S=E.schema,M=E.hasGetAll,V=E.hasIdb3Features,N=S.tables.map(m),B={};return N.forEach(function(O){return B[O.name]=O}),{stack:"dbcore",transaction:a.transaction.bind(a),table:function(O){if(B[O])return B[O];throw new Error("Table '".concat(O,"' not found"))},MIN_KEY:-1/0,MAX_KEY:si(l),schema:S}}function Pd(a,l,h,y){return h=h.IDBKeyRange,l=Nd(l,h,y),{dbcore:a.dbcore.reduce(function(m,v){return v=v.create,i(i({},m),v(m))},l)}}function Fi(a,l){var h=l.db,h=Pd(a._middlewares,h,a._deps,l);a.core=h.dbcore,a.tables.forEach(function(y){var m=y.name;a.core.schema.tables.some(function(v){return v.name===m})&&(y.core=a.core.table(m),a[m]instanceof a.Table)&&(a[m].core=y.core)})}function Ui(a,l,h,y){h.forEach(function(m){var v=y[m];l.forEach(function(E){var S=(function M(V,N){return T(V,N)||(V=p(V))&&M(V,N)})(E,m);(!S||"value"in S&&S.value===void 0)&&(E===a.Transaction.prototype||E instanceof a.Transaction?A(E,m,{get:function(){return this.table(m)},set:function(M){x(this,m,{value:M,writable:!0,configurable:!0,enumerable:!0})}}):E[m]=new a.Table(m,v))})})}function lo(a,l){l.forEach(function(h){for(var y in h)h[y]instanceof a.Table&&delete h[y]})}function Fd(a,l){return a._cfg.version-l._cfg.version}function Ud(a,l,h,y){var m=a._dbSchema,v=(h.objectStoreNames.contains("$meta")&&!m.$meta&&(m.$meta=co("$meta",iu("")[0],[]),a._storeNames.push("$meta")),a._createTransaction("readwrite",a._storeNames,m)),E=(v.create(h),v._completion.catch(y),v._reject.bind(v)),S=Le.transless||Le;Jt(function(){if(Le.trans=v,Le.transless=S,l!==0)return Fi(a,h),V=l,((M=v).storeNames.includes("$meta")?M.table("$meta").get("version").then(function(N){return N??V}):Se.resolve(V)).then(function(K){var B=a,O=K,z=v,U=h,F=[],K=B._versions,Z=B._dbSchema=Ki(0,B.idbdb,U);return(K=K.filter(function(G){return G._cfg.version>=O})).length===0?Se.resolve():(K.forEach(function(G){F.push(function(){var ne,ce,fe,Ee=Z,me=G._cfg.dbschema,Ae=(zi(B,Ee,U),zi(B,me,U),Z=B._dbSchema=me,fo(Ee,me)),ve=(Ae.add.forEach(function(Ie){ho(U,Ie[0],Ie[1].primKey,Ie[1].indexes)}),Ae.change.forEach(function(Ie){if(Ie.recreate)throw new Be.Upgrade("Not yet support for changing primary key");var ue=U.objectStore(Ie.name);Ie.add.forEach(function(De){return $i(ue,De)}),Ie.change.forEach(function(De){ue.deleteIndex(De.name),$i(ue,De)}),Ie.del.forEach(function(De){return ue.deleteIndex(De)})}),G._cfg.contentUpgrade);if(ve&&G._cfg.version>O)return Fi(B,U),z._memoizedTables={},ne=ee(me),Ae.del.forEach(function(Ie){ne[Ie]=Ee[Ie]}),lo(B,[B.Transaction.prototype]),Ui(B,[B.Transaction.prototype],c(ne),ne),z.schema=ne,(ce=W(ve))&&Tn(),me=Se.follow(function(){var Ie;(fe=ve(z))&&ce&&(Ie=Qt.bind(null,null),fe.then(Ie,Ie))}),fe&&typeof fe.then=="function"?Se.resolve(fe):me.then(function(){return fe})}),F.push(function(ne){var ce,fe,Ee=G._cfg.dbschema;ce=Ee,fe=ne,[].slice.call(fe.db.objectStoreNames).forEach(function(me){return ce[me]==null&&fe.db.deleteObjectStore(me)}),lo(B,[B.Transaction.prototype]),Ui(B,[B.Transaction.prototype],B._storeNames,B._dbSchema),z.schema=B._dbSchema}),F.push(function(ne){B.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(B.idbdb.version/10)===G._cfg.version?(B.idbdb.deleteObjectStore("$meta"),delete B._dbSchema.$meta,B._storeNames=B._storeNames.filter(function(ce){return ce!=="$meta"})):ne.objectStore("$meta").put(G._cfg.version,"version"))})}),(function G(){return F.length?Se.resolve(F.shift()(z.idbtrans)).then(G):Se.resolve()})().then(function(){ru(Z,U)}))}).catch(E);var M,V;c(m).forEach(function(N){ho(h,N,m[N].primKey,m[N].indexes)}),Fi(a,h),Se.follow(function(){return a.on.populate.fire(v)}).catch(E)})}function $d(a,l){ru(a._dbSchema,l),l.db.version%10!=0||l.objectStoreNames.contains("$meta")||l.db.createObjectStore("$meta").add(Math.ceil(l.db.version/10-1),"version");var h=Ki(0,a.idbdb,l);zi(a,a._dbSchema,l);for(var y=0,m=fo(h,a._dbSchema).change;y<m.length;y++){var v=(E=>{if(E.change.length||E.recreate)return console.warn("Unable to patch indexes of table ".concat(E.name," because it has changes on the type of index or primary key.")),{value:void 0};var S=l.objectStore(E.name);E.add.forEach(function(M){Rt&&console.debug("Dexie upgrade patch: Creating missing index ".concat(E.name,".").concat(M.src)),$i(S,M)})})(m[y]);if(typeof v=="object")return v.value}}function fo(a,l){var h,y={del:[],add:[],change:[]};for(h in a)l[h]||y.del.push(h);for(h in l){var m=a[h],v=l[h];if(m){var E={name:h,def:v,recreate:!1,del:[],add:[],change:[]};if(""+(m.primKey.keyPath||"")!=""+(v.primKey.keyPath||"")||m.primKey.auto!==v.primKey.auto)E.recreate=!0,y.change.push(E);else{var S=m.idxByName,M=v.idxByName,V=void 0;for(V in S)M[V]||E.del.push(V);for(V in M){var N=S[V],B=M[V];N?N.src!==B.src&&E.change.push(B):E.add.push(B)}(0<E.del.length||0<E.add.length||0<E.change.length)&&y.change.push(E)}}else y.add.push([h,v])}return y}function ho(a,l,h,y){var m=a.db.createObjectStore(l,h.keyPath?{keyPath:h.keyPath,autoIncrement:h.auto}:{autoIncrement:h.auto});y.forEach(function(v){return $i(m,v)})}function ru(a,l){c(a).forEach(function(h){l.db.objectStoreNames.contains(h)||(Rt&&console.debug("Dexie: Creating missing table",h),ho(l,h,a[h].primKey,a[h].indexes))})}function $i(a,l){a.createIndex(l.name,l.keyPath,{unique:l.unique,multiEntry:l.multi})}function Ki(a,l,h){var y={};return ae(l.objectStoreNames,0).forEach(function(m){for(var v=h.objectStore(m),E=ao(tu(V=v.keyPath),V||"",!0,!1,!!v.autoIncrement,V&&typeof V!="string",!0),S=[],M=0;M<v.indexNames.length;++M){var N=v.index(v.indexNames[M]),V=N.keyPath,N=ao(N.name,V,!!N.unique,!!N.multiEntry,!1,V&&typeof V!="string",!1);S.push(N)}y[m]=co(m,E,S)}),y}function zi(a,l,h){for(var y=h.db.objectStoreNames,m=0;m<y.length;++m){var v=y[m],E=h.objectStore(v);a._hasGetAll="getAll"in E;for(var S=0;S<E.indexNames.length;++S){var M,V=E.indexNames[S],N=E.index(V).keyPath,N=typeof N=="string"?N:"["+ae(N).join("+")+"]";l[v]&&(M=l[v].idxByName[N])&&(M.name=V,delete l[v].idxByName[N],l[v].idxByName[V]=M)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(a._hasGetAll=!1)}function iu(a){return a.split(",").map(function(l,h){var m=l.split(":"),y=(y=m[1])==null?void 0:y.trim(),m=(l=m[0].trim()).replace(/([&*]|\+\+)/g,""),v=/^\[/.test(m)?m.match(/^\[(.*)\]$/)[1].split("+"):m;return ao(m,v||null,/\&/.test(l),/\*/.test(l),/\+\+/.test(l),u(v),h===0,y)})}Ar.prototype._createTableSchema=co,Ar.prototype._parseIndexSyntax=iu,Ar.prototype._parseStoresSpec=function(a,l){var h=this;c(a).forEach(function(y){if(a[y]!==null){var m=h._parseIndexSyntax(a[y]),v=m.shift();if(!v)throw new Be.Schema("Invalid schema for table "+y+": "+a[y]);if(v.unique=!0,v.multi)throw new Be.Schema("Primary key cannot be multiEntry*");m.forEach(function(E){if(E.auto)throw new Be.Schema("Only primary key can be marked as autoIncrement (++)");if(!E.keyPath)throw new Be.Schema("Index must have a name and cannot be an empty string")}),v=h._createTableSchema(y,v,m),l[y]=v}})},Ar.prototype.stores=function(h){var l=this.db,h=(this._cfg.storesSource=this._cfg.storesSource?f(this._cfg.storesSource,h):h,l._versions),y={},m={};return h.forEach(function(v){f(y,v._cfg.storesSource),m=v._cfg.dbschema={},v._parseStoresSpec(y,m)}),l._dbSchema=m,lo(l,[l._allTables,l,l.Transaction.prototype]),Ui(l,[l._allTables,l,l.Transaction.prototype,this._cfg.tables],c(m),m),l._storeNames=c(m),this},Ar.prototype.upgrade=function(a){return this._cfg.contentUpgrade=Jn(this._cfg.contentUpgrade||Ge,a),this};var Kd=Ar;function Ar(){}var ai=(()=>{var a,l,h;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(a=new Set,l=new FinalizationRegistry(function(y){a.delete(y)}),{toArray:function(){return Array.from(a).map(function(y){return y.deref()}).filter(function(y){return y!==void 0})},add:function(y){var m=new WeakRef(y._novip);a.add(m),l.register(y._novip,m,m),a.size>y._options.maxConnections&&(m=a.values().next().value,a.delete(m),l.unregister(m))},remove:function(y){if(y)for(var m=a.values(),v=m.next();!v.done;){var E=v.value;if(E.deref()===y._novip)return a.delete(E),void l.unregister(E);v=m.next()}}}):(h=[],{toArray:function(){return h},add:function(y){h.push(y._novip)},remove:function(y){y&&(y=h.indexOf(y._novip))!==-1&&h.splice(y,1)}})})();function po(a,l){var h=a._dbNamesDB;return h||(h=a._dbNamesDB=new pn(Ht,{addons:[],indexedDB:a,IDBKeyRange:l})).version(1).stores({dbnames:"name"}),h.table("dbnames")}function yo(a){return a&&typeof a.databases=="function"}function go(a){return Jt(function(){return Le.letThrough=!0,a()})}function mo(a){return!("from"in a)}var wt=function(a,l){var h;if(!this)return h=new wt,a&&"d"in a&&f(h,a),h;f(this,arguments.length?{d:1,from:a,to:1<arguments.length?l:a}:{d:0})};function ci(a,l,h){var y=qe(l,h);if(!isNaN(y)){if(0<y)throw RangeError();if(mo(a))return f(a,{from:l,to:h,d:1});var y=a.l,m=a.r;if(qe(h,a.from)<0)return y?ci(y,l,h):a.l={from:l,to:h,d:1,l:null,r:null},ou(a);if(0<qe(l,a.to))return m?ci(m,l,h):a.r={from:l,to:h,d:1,l:null,r:null},ou(a);qe(l,a.from)<0&&(a.from=l,a.l=null,a.d=m?m.d+1:1),0<qe(h,a.to)&&(a.to=h,a.r=null,a.d=a.l?a.l.d+1:1),l=!a.r,y&&!a.l&&ui(a,y),m&&l&&ui(a,m)}}function ui(a,l){mo(l)||(function h(y,m){var v=m.from,E=m.l,S=m.r;ci(y,v,m.to),E&&h(y,E),S&&h(y,S)})(a,l)}function su(a,l){var h=Hi(l),y=h.next();if(!y.done)for(var m=y.value,v=Hi(a),E=v.next(m.from),S=E.value;!y.done&&!E.done;){if(qe(S.from,m.to)<=0&&0<=qe(S.to,m.from))return!0;qe(m.from,S.from)<0?m=(y=h.next(S.from)).value:S=(E=v.next(m.from)).value}return!1}function Hi(a){var l=mo(a)?null:{s:0,n:a};return{next:function(h){for(var y=0<arguments.length;l;)switch(l.s){case 0:if(l.s=1,y)for(;l.n.l&&qe(h,l.n.from)<0;)l={up:l,n:l.n.l,s:1};else for(;l.n.l;)l={up:l,n:l.n.l,s:1};case 1:if(l.s=2,!y||qe(h,l.n.to)<=0)return{value:l.n,done:!1};case 2:if(l.n.r){l.s=3,l={up:l,n:l.n.r,s:0};continue}case 3:l=l.up}return{done:!0}}}}function ou(a){var l,h,y,m=(((m=a.r)==null?void 0:m.d)||0)-(((m=a.l)==null?void 0:m.d)||0),m=1<m?"r":m<-1?"l":"";m&&(l=m=="r"?"l":"r",h=i({},a),y=a[m],a.from=y.from,a.to=y.to,a[m]=y[m],h[m]=y[l],(a[l]=h).d=au(h)),a.d=au(a)}function au(h){var l=h.r,h=h.l;return(l?h?Math.max(l.d,h.d):l.d:h?h.d:0)+1}function qi(a,l){return c(l).forEach(function(h){a[h]?ui(a[h],l[h]):a[h]=(function y(m){var v,E,S={};for(v in m)g(m,v)&&(E=m[v],S[v]=!E||typeof E!="object"||H.has(E.constructor)?E:y(E));return S})(l[h])}),a}function wo(a,l){return a.all||l.all||Object.keys(a).some(function(h){return l[h]&&su(l[h],a[h])})}w(wt.prototype,((mt={add:function(a){return ui(this,a),this},addKey:function(a){return ci(this,a,a),this},addKeys:function(a){var l=this;return a.forEach(function(h){return ci(l,h,h)}),this},hasKey:function(a){var l=Hi(this).next(a).value;return l&&qe(l.from,a)<=0&&0<=qe(l.to,a)}})[re]=function(){return Hi(this)},mt));var rr={},vo={},bo=!1;function Wi(a){qi(vo,a),bo||(bo=!0,setTimeout(function(){bo=!1,Eo(vo,!(vo={}))},0))}function Eo(a,l){l===void 0&&(l=!1);var h=new Set;if(a.all)for(var y=0,m=Object.values(rr);y<m.length;y++)cu(S=m[y],a,h,l);else for(var v in a){var E,S,v=/^idb\:\/\/(.*)\/(.*)\//.exec(v);v&&(E=v[1],v=v[2],S=rr["idb://".concat(E,"/").concat(v)])&&cu(S,a,h,l)}h.forEach(function(M){return M()})}function cu(a,l,h,y){for(var m=[],v=0,E=Object.entries(a.queries.query);v<E.length;v++){for(var S=E[v],M=S[0],V=[],N=0,B=S[1];N<B.length;N++){var O=B[N];wo(l,O.obsSet)?O.subscribers.forEach(function(K){return h.add(K)}):y&&V.push(O)}y&&m.push([M,V])}if(y)for(var z=0,U=m;z<U.length;z++){var F=U[z],M=F[0],V=F[1];a.queries.query[M]=V}}function zd(a){var l=a._state,h=a._deps.indexedDB;if(l.isBeingOpened||a.idbdb)return l.dbReadyPromise.then(function(){return l.dbOpenError?st(l.dbOpenError):a});l.isBeingOpened=!0,l.dbOpenError=null,l.openComplete=!1;var y=l.openCanceller,m=Math.round(10*a.verno),v=!1;function E(){if(l.openCanceller!==y)throw new Be.DatabaseClosed("db.open() was cancelled")}function S(){return new Se(function(O,z){if(E(),!h)throw new Be.MissingAPI;var U=a.name,F=l.autoSchema||!m?h.open(U):h.open(U,m);if(!F)throw new Be.MissingAPI;F.onerror=Wt(z),F.onblocked=et(a._fireOnBlocked),F.onupgradeneeded=et(function(K){var Z;N=F.transaction,l.autoSchema&&!a._options.allowEmptyDB?(F.onerror=ii,N.abort(),F.result.close(),(Z=h.deleteDatabase(U)).onsuccess=Z.onerror=et(function(){z(new Be.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(N.onerror=Wt(z),Z=K.oldVersion>Math.pow(2,62)?0:K.oldVersion,B=Z<1,a.idbdb=F.result,v&&$d(a,N),Ud(a,Z/10,N,z))},z),F.onsuccess=et(function(){N=null;var K,Z,G,ne,ce,fe,Ee=a.idbdb=F.result,me=ae(Ee.objectStoreNames);if(0<me.length)try{var Ae=Ee.transaction((ce=me).length===1?ce[0]:ce,"readonly");if(l.autoSchema)fe=Ee,ne=Ae,(G=a).verno=fe.version/10,ne=G._dbSchema=Ki(0,fe,ne),G._storeNames=ae(fe.objectStoreNames,0),Ui(G,[G._allTables],c(ne),ne);else if(zi(a,a._dbSchema,Ae),Z=Ae,((Z=fo(Ki(0,(K=a).idbdb,Z),K._dbSchema)).add.length||Z.change.some(function(ve){return ve.add.length||ve.change.length}))&&!v)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Ee.close(),m=Ee.version+1,v=!0,O(S());Fi(a,Ae)}catch{}ai.add(a),Ee.onversionchange=et(function(ve){l.vcFired=!0,a.on("versionchange").fire(ve)}),Ee.onclose=et(function(){a.close({disableAutoOpen:!1})}),B&&(me=a._deps,ce=U,yo(fe=me.indexedDB)||ce===Ht||po(fe,me.IDBKeyRange).put({name:ce}).catch(Ge)),O()},z)}).catch(function(O){switch(O?.name){case"UnknownError":if(0<l.PR1398_maxLoop)return l.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),S();break;case"VersionError":if(0<m)return m=0,S()}return Se.reject(O)})}var M,V=l.dbReadyResolve,N=null,B=!1;return Se.race([y,(typeof navigator>"u"?Se.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(O){function z(){return indexedDB.databases().finally(O)}M=setInterval(z,100),z()}).finally(function(){return clearInterval(M)}):Promise.resolve()).then(S)]).then(function(){return E(),l.onReadyBeingFired=[],Se.resolve(go(function(){return a.on.ready.fire(a.vip)})).then(function O(){var z;if(0<l.onReadyBeingFired.length)return z=l.onReadyBeingFired.reduce(Jn,Ge),l.onReadyBeingFired=[],Se.resolve(go(function(){return z(a.vip)})).then(O)})}).finally(function(){l.openCanceller===y&&(l.onReadyBeingFired=null,l.isBeingOpened=!1)}).catch(function(O){l.dbOpenError=O;try{N&&N.abort()}catch{}return y===l.openCanceller&&a._close(),st(O)}).finally(function(){l.openComplete=!0,V()}).then(function(){var O;return B&&(O={},a.tables.forEach(function(z){z.schema.indexes.forEach(function(U){U.name&&(O["idb://".concat(a.name,"/").concat(z.name,"/").concat(U.name)]=new wt(-1/0,[[[]]]))}),O["idb://".concat(a.name,"/").concat(z.name,"/")]=O["idb://".concat(a.name,"/").concat(z.name,"/:dels")]=new wt(-1/0,[[[]]])}),Ln(Pi).fire(O),Eo(O,!0)),a})}function xo(a){function l(v){return a.next(v)}var h=m(l),y=m(function(v){return a.throw(v)});function m(v){return function(S){var S=v(S),M=S.value;return S.done?M:M&&typeof M.then=="function"?M.then(h,y):u(M)?Promise.all(M).then(h,y):h(M)}}return m(l)()}function ji(a,l,h){for(var y=u(a)?a.slice():[a],m=0;m<h;++m)y.push(l);return y}var Hd={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(a){return i(i({},a),{table:function(y){var h=a.table(y),y=h.schema,m={},v=[];function E(O,z,U){var G=oi(O),F=m[G]=m[G]||[],K=O==null?0:typeof O=="string"?1:O.length,Z=0<z,G=i(i({},U),{name:Z?"".concat(G,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:Z,keyTail:z,keyLength:K,extractKey:uo(O),unique:!Z&&U.unique});return F.push(G),G.isPrimaryKey||v.push(G),1<K&&E(K===2?O[0]:O.slice(0,K-1),z+1,U),F.sort(function(ne,ce){return ne.keyTail-ce.keyTail}),G}var S=E(y.primaryKey.keyPath,0,y.primaryKey);m[":id"]=[S];for(var M=0,V=y.indexes;M<V.length;M++){var N=V[M];E(N.keyPath,0,N)}function B(O){var z,U=O.query.index;return U.isVirtual?i(i({},O),{query:{index:U.lowLevelIndex,range:(z=O.query.range,U=U.keyTail,{type:z.type===1?2:z.type,lower:ji(z.lower,z.lowerOpen?a.MAX_KEY:a.MIN_KEY,U),lowerOpen:!0,upper:ji(z.upper,z.upperOpen?a.MIN_KEY:a.MAX_KEY,U),upperOpen:!0})}}):O}return i(i({},h),{schema:i(i({},y),{primaryKey:S,indexes:v,getIndexByKeyPath:function(O){return(O=m[oi(O)])&&O[0]}}),count:function(O){return h.count(B(O))},query:function(O){return h.query(B(O))},openCursor:function(O){var z=O.query.index,U=z.keyTail,F=z.keyLength;return z.isVirtual?h.openCursor(B(O)).then(function(Z){return Z&&K(Z)}):h.openCursor(O);function K(Z){return Object.create(Z,{continue:{value:function(G){G!=null?Z.continue(ji(G,O.reverse?a.MAX_KEY:a.MIN_KEY,U)):O.unique?Z.continue(Z.key.slice(0,F).concat(O.reverse?a.MIN_KEY:a.MAX_KEY,U)):Z.continue()}},continuePrimaryKey:{value:function(G,ne){Z.continuePrimaryKey(ji(G,a.MAX_KEY,U),ne)}},primaryKey:{get:function(){return Z.primaryKey}},key:{get:function(){var G=Z.key;return F===1?G[0]:G.slice(0,F)}},value:{get:function(){return Z.value}}})}}})}})}};function _o(a,l,h,y){return h=h||{},y=y||"",c(a).forEach(function(m){var v,E,S;g(l,m)?(v=a[m],E=l[m],typeof v=="object"&&typeof E=="object"&&v&&E?(S=X(v))!==X(E)?h[y+m]=l[m]:S==="Object"?_o(v,E,h,y+m+"."):v!==E&&(h[y+m]=l[m]):v!==E&&(h[y+m]=l[m])):h[y+m]=void 0}),c(l).forEach(function(m){g(a,m)||(h[y+m]=l[m])}),h}function ko(a,l){return l.type==="delete"?l.keys:l.keys||l.values.map(a.extractKey)}var qd={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(a){return i(i({},a),{table:function(l){var h=a.table(l),y=h.schema.primaryKey;return i(i({},h),{mutate:function(m){var v=Le.trans,E=v.table(l).hook,S=E.deleting,M=E.creating,V=E.updating;switch(m.type){case"add":if(M.fire===Ge)break;return v._promise("readwrite",function(){return N(m)},!0);case"put":if(M.fire===Ge&&V.fire===Ge)break;return v._promise("readwrite",function(){return N(m)},!0);case"delete":if(S.fire===Ge)break;return v._promise("readwrite",function(){return N(m)},!0);case"deleteRange":if(S.fire===Ge)break;return v._promise("readwrite",function(){return(function B(O,z,U){return h.query({trans:O,values:!1,query:{index:y,range:z},limit:U}).then(function(F){var K=F.result;return N({type:"delete",keys:K,trans:O}).then(function(Z){return 0<Z.numFailures?Promise.reject(Z.failures[0]):K.length<U?{failures:[],numFailures:0,lastResult:void 0}:B(O,i(i({},z),{lower:K[K.length-1],lowerOpen:!0}),U)})})})(m.trans,m.range,1e4)},!0)}return h.mutate(m);function N(B){var O,z,U,F=Le.trans,K=B.keys||ko(y,B);if(K)return(B=B.type==="add"||B.type==="put"?i(i({},B),{keys:K}):i({},B)).type!=="delete"&&(B.values=s([],B.values)),B.keys&&(B.keys=s([],B.keys)),O=h,U=K,((z=B).type==="add"?Promise.resolve([]):O.getMany({trans:z.trans,keys:U,cache:"immutable"})).then(function(Z){var G=K.map(function(ne,ce){var fe,Ee,me,Ae=Z[ce],ve={onerror:null,onsuccess:null};return B.type==="delete"?S.fire.call(ve,ne,Ae,F):B.type==="add"||Ae===void 0?(fe=M.fire.call(ve,ne,B.values[ce],F),ne==null&&fe!=null&&(B.keys[ce]=ne=fe,y.outbound||ie(B.values[ce],y.keyPath,ne))):(fe=_o(Ae,B.values[ce]),(Ee=V.fire.call(ve,fe,ne,Ae,F))&&(me=B.values[ce],Object.keys(Ee).forEach(function(Ie){g(me,Ie)?me[Ie]=Ee[Ie]:ie(me,Ie,Ee[Ie])}))),ve});return h.mutate(B).then(function(ne){for(var ce=ne.failures,fe=ne.results,Ee=ne.numFailures,ne=ne.lastResult,me=0;me<K.length;++me){var Ae=(fe||K)[me],ve=G[me];Ae==null?ve.onerror&&ve.onerror(ce[me]):ve.onsuccess&&ve.onsuccess(B.type==="put"&&Z[me]?B.values[me]:Ae)}return{failures:ce,results:fe,numFailures:Ee,lastResult:ne}}).catch(function(ne){return G.forEach(function(ce){return ce.onerror&&ce.onerror(ne)}),Promise.reject(ne)})});throw new Error("Keys missing")}}})}})}};function uu(a,l,h){try{if(!l||l.keys.length<a.length)return null;for(var y=[],m=0,v=0;m<l.keys.length&&v<a.length;++m)qe(l.keys[m],a[v])===0&&(y.push(h?j(l.values[m]):l.values[m]),++v);return y.length===a.length?y:null}catch{return null}}var Wd={stack:"dbcore",level:-1,create:function(a){return{table:function(l){var h=a.table(l);return i(i({},h),{getMany:function(y){var m;return y.cache?(m=uu(y.keys,y.trans._cache,y.cache==="clone"))?Se.resolve(m):h.getMany(y).then(function(v){return y.trans._cache={keys:y.keys,values:y.cache==="clone"?j(v):v},v}):h.getMany(y)},mutate:function(y){return y.type!=="add"&&(y.trans._cache=null),h.mutate(y)}})}}}};function lu(a,l){return a.trans.mode==="readonly"&&!!a.subscr&&!a.trans.explicit&&a.trans.db._options.cache!=="disabled"&&!l.schema.primaryKey.outbound}function fu(a,l){switch(a){case"query":return l.values&&!l.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var jd={stack:"dbcore",level:0,name:"Observability",create:function(a){var l=a.schema.name,h=new wt(a.MIN_KEY,a.MAX_KEY);return i(i({},a),{transaction:function(y,m,v){if(Le.subscr&&m!=="readonly")throw new Be.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(Le.querier));return a.transaction(y,m,v)},table:function(y){function m(K){var F,K=K.query;return[F=K.index,new wt((F=(K=K.range).lower)!=null?F:a.MIN_KEY,(F=K.upper)!=null?F:a.MAX_KEY)]}var v=a.table(y),E=v.schema,S=E.primaryKey,M=E.indexes,V=S.extractKey,N=S.outbound,B=S.autoIncrement&&M.filter(function(U){return U.compound&&U.keyPath.includes(S.keyPath)}),O=i(i({},v),{mutate:function(U){function F(ue){return ue="idb://".concat(l,"/").concat(y,"/").concat(ue),ce[ue]||(ce[ue]=new wt)}var K,Z,G,ne=U.trans,ce=U.mutatedParts||(U.mutatedParts={}),fe=F(""),Ee=F(":dels"),me=U.type,ve=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[ko(S,U).filter(function(ue){return ue}),U.values]:[],Ae=ve[0],ve=ve[1],Ie=U.trans._cache;return u(Ae)?(fe.addKeys(Ae),(me=me==="delete"||Ae.length===ve.length?uu(Ae,Ie):null)||Ee.addKeys(Ae),(me||ve)&&(K=F,Z=me,G=ve,E.indexes.forEach(function(ue){var De=K(ue.name||"");function Ne(We){return We!=null?ue.extractKey(We):null}function ze(We){ue.multiEntry&&u(We)?We.forEach(function(Lt){return De.addKey(Lt)}):De.addKey(We)}(Z||G).forEach(function(We,vt){var Ke=Z&&Ne(Z[vt]),vt=G&&Ne(G[vt]);qe(Ke,vt)!==0&&(Ke!=null&&ze(Ke),vt!=null)&&ze(vt)})}))):Ae?(ve={from:(Ie=Ae.lower)!=null?Ie:a.MIN_KEY,to:(me=Ae.upper)!=null?me:a.MAX_KEY},Ee.add(ve),fe.add(ve)):(fe.add(h),Ee.add(h),E.indexes.forEach(function(ue){return F(ue.name).add(h)})),v.mutate(U).then(function(ue){return!Ae||U.type!=="add"&&U.type!=="put"||(fe.addKeys(ue.results),B&&B.forEach(function(De){for(var Ne=U.values.map(function(Ke){return De.extractKey(Ke)}),ze=De.keyPath.findIndex(function(Ke){return Ke===S.keyPath}),We=0,Lt=ue.results.length;We<Lt;++We)Ne[We][ze]=ue.results[We];F(De.name).addKeys(Ne)})),ne.mutatedParts=qi(ne.mutatedParts||{},ce),ue})}}),z={get:function(U){return[S,new wt(U.key)]},getMany:function(U){return[S,new wt().addKeys(U.keys)]},count:m,query:m,openCursor:m};return c(z).forEach(function(U){O[U]=function(F){var K=Le.subscr,Z=!!K,G=lu(Le,v)&&fu(U,F)?F.obsSet={}:K;if(Z){var ne,K=function(ve){return ve="idb://".concat(l,"/").concat(y,"/").concat(ve),G[ve]||(G[ve]=new wt)},ce=K(""),fe=K(":dels"),Z=z[U](F),Ee=Z[0],Z=Z[1];if((U==="query"&&Ee.isPrimaryKey&&!F.values?fe:K(Ee.name||"")).add(Z),!Ee.isPrimaryKey){if(U!=="count")return ne=U==="query"&&N&&F.values&&v.query(i(i({},F),{values:!1})),v[U].apply(this,arguments).then(function(ve){if(U==="query"){if(N&&F.values)return ne.then(function(Ne){return Ne=Ne.result,ce.addKeys(Ne),ve});var Ie=F.values?ve.result.map(V):ve.result;(F.values?ce:fe).addKeys(Ie)}else{var ue,De;if(U==="openCursor")return De=F.values,(ue=ve)&&Object.create(ue,{key:{get:function(){return fe.addKey(ue.primaryKey),ue.key}},primaryKey:{get:function(){var Ne=ue.primaryKey;return fe.addKey(Ne),Ne}},value:{get:function(){return De&&ce.addKey(ue.primaryKey),ue.value}}})}return ve});fe.add(h)}}return v[U].apply(this,arguments)}}),O}})}};function hu(a,l,h){var y;return h.numFailures===0?l:l.type==="deleteRange"||(y=l.keys?l.keys.length:"values"in l&&l.values?l.values.length:1,h.numFailures===y)?null:(y=i({},l),u(y.keys)&&(y.keys=y.keys.filter(function(m,v){return!(v in h.failures)})),"values"in y&&u(y.values)&&(y.values=y.values.filter(function(m,v){return!(v in h.failures)})),y)}function So(a,l){return h=a,((y=l).lower===void 0||(y.lowerOpen?0<qe(h,y.lower):0<=qe(h,y.lower)))&&(h=a,(y=l).upper===void 0||(y.upperOpen?qe(h,y.upper)<0:qe(h,y.upper)<=0));var h,y}function du(a,l,h,y,m,v){var E,S,M,V,N,B,O;return!h||h.length===0||(E=l.query.index,S=E.multiEntry,M=l.query.range,V=y.schema.primaryKey.extractKey,N=E.extractKey,B=(E.lowLevelIndex||E).extractKey,(y=h.reduce(function(z,U){var F=z,K=[];if(U.type==="add"||U.type==="put")for(var Z=new wt,G=U.values.length-1;0<=G;--G){var ne,ce=U.values[G],fe=V(ce);!Z.hasKey(fe)&&(ne=N(ce),S&&u(ne)?ne.some(function(Ie){return So(Ie,M)}):So(ne,M))&&(Z.addKey(fe),K.push(ce))}switch(U.type){case"add":var Ee=new wt().addKeys(l.values?z.map(function(ue){return V(ue)}):z),F=z.concat(l.values?K.filter(function(ue){return ue=V(ue),!Ee.hasKey(ue)&&(Ee.addKey(ue),!0)}):K.map(function(ue){return V(ue)}).filter(function(ue){return!Ee.hasKey(ue)&&(Ee.addKey(ue),!0)}));break;case"put":var me=new wt().addKeys(U.values.map(function(ue){return V(ue)}));F=z.filter(function(ue){return!me.hasKey(l.values?V(ue):ue)}).concat(l.values?K:K.map(function(ue){return V(ue)}));break;case"delete":var Ae=new wt().addKeys(U.keys);F=z.filter(function(ue){return!Ae.hasKey(l.values?V(ue):ue)});break;case"deleteRange":var ve=U.range;F=z.filter(function(ue){return!So(V(ue),ve)})}return F},a))===a)?a:(O=function(z,U){return qe(B(z),B(U))||qe(V(z),V(U))},y.sort(l.direction==="prev"||l.direction==="prevunique"?function(z,U){return O(U,z)}:O),l.limit&&l.limit<1/0&&(y.length>l.limit?y.length=l.limit:a.length===l.limit&&y.length<l.limit&&(m.dirty=!0)),v?Object.freeze(y):y)}function pu(a,l){return qe(a.lower,l.lower)===0&&qe(a.upper,l.upper)===0&&!!a.lowerOpen==!!l.lowerOpen&&!!a.upperOpen==!!l.upperOpen}function Vd(a,l){return((h,y,m,v)=>{if(h===void 0)return y!==void 0?-1:0;if(y===void 0)return 1;if((h=qe(h,y))===0){if(m&&v)return 0;if(m)return 1;if(v)return-1}return h})(a.lower,l.lower,a.lowerOpen,l.lowerOpen)<=0&&0<=((h,y,m,v)=>{if(h===void 0)return y!==void 0?1:0;if(y===void 0)return-1;if((h=qe(h,y))===0){if(m&&v)return 0;if(m)return-1;if(v)return 1}return h})(a.upper,l.upper,a.upperOpen,l.upperOpen)}function Gd(a,l,h,y){a.subscribers.add(h),y.addEventListener("abort",function(){var m,v;a.subscribers.delete(h),a.subscribers.size===0&&(m=a,v=l,setTimeout(function(){m.subscribers.size===0&&pe(v,m)},3e3))})}var Yd={stack:"dbcore",level:0,name:"Cache",create:function(a){var l=a.schema.name;return i(i({},a),{transaction:function(h,y,m){var v,E,S=a.transaction(h,y,m);return y==="readwrite"&&(m=(v=new AbortController).signal,S.addEventListener("abort",(E=function(M){return function(){if(v.abort(),y==="readwrite"){for(var V=new Set,N=0,B=h;N<B.length;N++){var O=B[N],z=rr["idb://".concat(l,"/").concat(O)];if(z){var U=a.table(O),F=z.optimisticOps.filter(function(ue){return ue.trans===S});if(S._explicit&&M&&S.mutatedParts)for(var K=0,Z=Object.values(z.queries.query);K<Z.length;K++)for(var G=0,ne=(Ee=Z[K]).slice();G<ne.length;G++)wo((me=ne[G]).obsSet,S.mutatedParts)&&(pe(Ee,me),me.subscribers.forEach(function(ue){return V.add(ue)}));else if(0<F.length){z.optimisticOps=z.optimisticOps.filter(function(ue){return ue.trans!==S});for(var ce=0,fe=Object.values(z.queries.query);ce<fe.length;ce++)for(var Ee,me,Ae,ve=0,Ie=(Ee=fe[ce]).slice();ve<Ie.length;ve++)(me=Ie[ve]).res!=null&&S.mutatedParts&&(M&&!me.dirty?(Ae=Object.isFrozen(me.res),Ae=du(me.res,me.req,F,U,me,Ae),me.dirty?(pe(Ee,me),me.subscribers.forEach(function(ue){return V.add(ue)})):Ae!==me.res&&(me.res=Ae,me.promise=Se.resolve({result:Ae}))):(me.dirty&&pe(Ee,me),me.subscribers.forEach(function(ue){return V.add(ue)})))}}}V.forEach(function(ue){return ue()})}}})(!1),{signal:m}),S.addEventListener("error",E(!1),{signal:m}),S.addEventListener("complete",E(!0),{signal:m})),S},table:function(h){var y=a.table(h),m=y.schema.primaryKey;return i(i({},y),{mutate:function(v){var E,S=Le.trans;return!m.outbound&&S.db._options.cache!=="disabled"&&!S.explicit&&S.idbtrans.mode==="readwrite"&&(E=rr["idb://".concat(l,"/").concat(h)])?(S=y.mutate(v),v.type!=="add"&&v.type!=="put"||!(50<=v.values.length||ko(m,v).some(function(M){return M==null}))?(E.optimisticOps.push(v),v.mutatedParts&&Wi(v.mutatedParts),S.then(function(M){0<M.numFailures&&(pe(E.optimisticOps,v),(M=hu(0,v,M))&&E.optimisticOps.push(M),v.mutatedParts)&&Wi(v.mutatedParts)}),S.catch(function(){pe(E.optimisticOps,v),v.mutatedParts&&Wi(v.mutatedParts)})):S.then(function(M){var V=hu(0,i(i({},v),{values:v.values.map(function(N,B){var O;return M.failures[B]?N:(ie(O=(O=m.keyPath)!=null&&O.includes(".")?j(N):i({},N),m.keyPath,M.results[B]),O)})}),M);E.optimisticOps.push(V),queueMicrotask(function(){return v.mutatedParts&&Wi(v.mutatedParts)})}),S):y.mutate(v)},query:function(v){var E,S,M,V,N,B,O;return lu(Le,y)&&fu("query",v)?(E=((M=Le.trans)==null?void 0:M.db._options.cache)==="immutable",S=(M=Le).requery,M=M.signal,B=((z,U,F,K)=>{var Z=rr["idb://".concat(z,"/").concat(U)];if(!Z)return[];if(!(z=Z.queries[F]))return[null,!1,Z,null];var G=z[(K.query?K.query.index.name:null)||""];if(!G)return[null,!1,Z,null];switch(F){case"query":var ne=(ce=K.direction)!=null?ce:"next",ce=G.find(function(fe){var Ee;return fe.req.limit===K.limit&&fe.req.values===K.values&&((Ee=fe.req.direction)!=null?Ee:"next")===ne&&pu(fe.req.query.range,K.query.range)});return ce?[ce,!0,Z,G]:[G.find(function(fe){var Ee;return("limit"in fe.req?fe.req.limit:1/0)>=K.limit&&((Ee=fe.req.direction)!=null?Ee:"next")===ne&&(!K.values||fe.req.values)&&Vd(fe.req.query.range,K.query.range)}),!1,Z,G];case"count":return ce=G.find(function(fe){return pu(fe.req.query.range,K.query.range)}),[ce,!!ce,Z,G]}})(l,h,"query",v),O=B[0],V=B[2],N=B[3],O&&B[1]?O.obsSet=v.obsSet:(B=y.query(v).then(function(z){var U=z.result;if(O&&(O.res=U),E){for(var F=0,K=U.length;F<K;++F)Object.freeze(U[F]);Object.freeze(U)}return z}).catch(function(z){return N&&O&&pe(N,O),Promise.reject(z)}),O={obsSet:v.obsSet,promise:B,subscribers:new Set,type:"query",req:v,dirty:!1},N?N.push(O):(N=[O],(V=V||(rr["idb://".concat(l,"/").concat(h)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[v.query.index.name||""]=N)),Gd(O,N,S,M),O.promise.then(function(z){return z=du(z.result,v,V?.optimisticOps,y,O,E),{result:E?z:j(z)}})):y.query(v)}})}})}};function Vi(a,l){return new Proxy(a,{get:function(h,y,m){return y==="db"?l:Reflect.get(h,y,m)}})}lt.prototype.version=function(a){if(isNaN(a)||a<.1)throw new Be.Type("Given version is not a positive number");if(a=Math.round(10*a)/10,this.idbdb||this._state.isBeingOpened)throw new Be.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,a);var l=this._versions,h=l.filter(function(y){return y._cfg.version===a})[0];return h||(h=new this.Version(a),l.push(h),l.sort(Fd),h.stores({}),this._state.autoSchema=!1),h},lt.prototype._whenReady=function(a){var l=this;return this.idbdb&&(this._state.openComplete||Le.letThrough||this._vip)?a():new Se(function(h,y){if(l._state.openComplete)return y(new Be.DatabaseClosed(l._state.dbOpenError));if(!l._state.isBeingOpened){if(!l._state.autoOpen)return void y(new Be.DatabaseClosed);l.open().catch(Ge)}l._state.dbReadyPromise.then(h,y)}).then(a)},lt.prototype.use=function(m){var l=m.stack,h=m.create,y=m.level,m=m.name,v=(m&&this.unuse({stack:l,name:m}),this._middlewares[l]||(this._middlewares[l]=[]));return v.push({stack:l,create:h,level:y??10,name:m}),v.sort(function(E,S){return E.level-S.level}),this},lt.prototype.unuse=function(a){var l=a.stack,h=a.name,y=a.create;return l&&this._middlewares[l]&&(this._middlewares[l]=this._middlewares[l].filter(function(m){return y?m.create!==y:!!h&&m.name!==h})),this},lt.prototype.open=function(){var a=this;return dn(zt,function(){return zd(a)})},lt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var a=this._state;if(ai.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}a.isBeingOpened||(a.dbReadyPromise=new Se(function(l){a.dbReadyResolve=l}),a.openCanceller=new Se(function(l,h){a.cancelOpen=h}))},lt.prototype.close=function(l){var l=(l===void 0?{disableAutoOpen:!0}:l).disableAutoOpen,h=this._state;l?(h.isBeingOpened&&h.cancelOpen(new Be.DatabaseClosed),this._close(),h.autoOpen=!1,h.dbOpenError=new Be.DatabaseClosed):(this._close(),h.autoOpen=this._options.autoOpen||h.isBeingOpened,h.openComplete=!1,h.dbOpenError=null)},lt.prototype.delete=function(a){var l=this,h=(a===void 0&&(a={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),y=this._state;return new Se(function(m,v){function E(){l.close(a);var S=l._deps.indexedDB.deleteDatabase(l.name);S.onsuccess=et(function(){var M,V,N;M=l._deps,V=l.name,yo(N=M.indexedDB)||V===Ht||po(N,M.IDBKeyRange).delete(V).catch(Ge),m()}),S.onerror=Wt(v),S.onblocked=l._fireOnBlocked}if(h)throw new Be.InvalidArgument("Invalid closeOptions argument to db.delete()");y.isBeingOpened?y.dbReadyPromise.then(E):E()})},lt.prototype.backendDB=function(){return this.idbdb},lt.prototype.isOpen=function(){return this.idbdb!==null},lt.prototype.hasBeenClosed=function(){var a=this._state.dbOpenError;return a&&a.name==="DatabaseClosed"},lt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},lt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(lt.prototype,"tables",{get:function(){var a=this;return c(this._allTables).map(function(l){return a._allTables[l]})},enumerable:!1,configurable:!0}),lt.prototype.transaction=function(){var a=(function(l,h,y){var m=arguments.length;if(m<2)throw new Be.InvalidArgument("Too few arguments");for(var v=new Array(m-1);--m;)v[m-1]=arguments[m];return y=v.pop(),[l,$(v),y]}).apply(this,arguments);return this._transaction.apply(this,a)},lt.prototype._transaction=function(a,l,h){var y,m,v=this,E=Le.trans,S=(E&&E.db===this&&a.indexOf("!")===-1||(E=null),a.indexOf("?")!==-1);a=a.replace("!","").replace("?","");try{if(m=l.map(function(V){if(V=V instanceof v.Table?V.name:V,typeof V!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return V}),a=="r"||a===ti)y=ti;else{if(a!="rw"&&a!=In)throw new Be.InvalidArgument("Invalid transaction mode: "+a);y=In}if(E){if(E.mode===ti&&y===In){if(!S)throw new Be.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");E=null}E&&m.forEach(function(V){if(E&&E.storeNames.indexOf(V)===-1){if(!S)throw new Be.SubTransaction("Table "+V+" not included in parent transaction.");E=null}}),S&&E&&!E.active&&(E=null)}}catch(V){return E?E._promise(null,function(N,B){B(V)}):st(V)}var M=(function V(N,B,O,z,U){return Se.resolve().then(function(){var G=Le.transless||Le,F=N._createTransaction(B,O,N._dbSchema,z),G=(F.explicit=!0,{trans:F,transless:G});if(z)F.idbtrans=z.idbtrans;else try{F.create(),F.idbtrans._explicit=!0,N._state.PR1398_maxLoop=3}catch(ne){return ne.name===Ue.InvalidState&&N.isOpen()&&0<--N._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),N.close({disableAutoOpen:!1}),N.open().then(function(){return V(N,B,O,null,U)})):st(ne)}var K,Z=W(U),G=(Z&&Tn(),Se.follow(function(){var ne;(K=U.call(F,F))&&(Z?(ne=Qt.bind(null,null),K.then(ne,ne)):typeof K.next=="function"&&typeof K.throw=="function"&&(K=xo(K)))},G));return(K&&typeof K.then=="function"?Se.resolve(K).then(function(ne){return F.active?ne:st(new Be.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):G.then(function(){return K})).then(function(ne){return z&&F._resolve(),F._completion.then(function(){return ne})}).catch(function(ne){return F._reject(ne),st(ne)})})}).bind(null,this,y,m,E,h);return E?E._promise(y,M,"lock"):Le.trans?dn(Le.transless,function(){return v._whenReady(M)}):this._whenReady(M)}
vendor: 1,617 bytes, line 3
3,lt.prototype.table=function(a){if(g(this._allTables,a))return this._allTables[a];throw new Be.InvalidTable("Table ".concat(a," does not exist"))};var pn=lt;function lt(a,l){var h,y,m,v,E,S=this,M=(this._middlewares={},this.verno=0,lt.dependencies),M=(this._options=l=i({addons:lt.addons,autoOpen:!0,indexedDB:M.indexedDB,IDBKeyRange:M.IDBKeyRange,cache:"cloned",maxConnections:1e3},l),this._deps={indexedDB:l.indexedDB,IDBKeyRange:l.IDBKeyRange},l.addons),V=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Ge,dbReadyPromise:null,cancelOpen:Ge,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:l.autoOpen}),N=(V.dbReadyPromise=new Se(function(B){V.dbReadyResolve=B}),V.openCanceller=new Se(function(B,O){V.cancelOpen=O}),this._state=V,this.name=a,this.on=oe(this,"populate","blocked","versionchange","close",{ready:[Jn,Ge]}),this.once=function(B,O){var z=function(){for(var U=[],F=0;F<arguments.length;F++)U[F]=arguments[F];S.on(B).unsubscribe(z),O.apply(S,U)};return S.on(B,z)},this.on.ready.subscribe=Re(this.on.ready.subscribe,function(B){return function(O,z){lt.vip(function(){var U,F=S._state;F.openComplete?(F.dbOpenError||Se.resolve().then(O),z&&B(O)):F.onReadyBeingFired?(F.onReadyBeingFired.push(O),z&&B(O)):(B(O),U=S,z||B(function K(){U.on.ready.unsubscribe(O),U.on.ready.unsubscribe(K)}))})}}),this.Collection=(h=this,he(at.prototype,function(K,F){this.db=h;var z=Di,U=null;if(F)try{z=F()}catch(G){U=G}var F=K._ctx,K=F.table,Z=K.hook.reading.fire;
vendor: 6,212 bytes, line 3
3this._ctx={table:K,index:F.index,isPrimKey:!F.index||K.schema.primKey.keyPath&&F.index===K.schema.primKey.name,range:z,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:F.or,valueMapper:Z!==Xn?Z:null}})),this.Table=(y=this,he(L.prototype,function(B,O,z){this.db=y,this._tx=z,this.name=B,this.schema=O,this.hook=y._allTables[B]?y._allTables[B].hook:oe(null,{creating:[eo,Ge],reading:[Qs,Xn],updating:[dr,Ge],deleting:[Ti,Ge]})})),this.Transaction=(m=this,he(Od.prototype,function(B,O,z,U,F){var K=this;B!=="readonly"&&O.forEach(function(Z){Z=(Z=z[Z])==null?void 0:Z.yProps,Z&&(O=O.concat(Z.map(function(G){return G.updatesTable})))}),this.db=m,this.mode=B,this.storeNames=O,this.schema=z,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=oe(this,"complete","error","abort"),this.parent=F||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Se(function(Z,G){K._resolve=Z,K._reject=G}),this._completion.then(function(){K.active=!1,K.on.complete.fire()},function(Z){var G=K.active;return K.active=!1,K.on.error.fire(Z),K.parent?K.parent._reject(Z):G&&K.idbtrans&&K.idbtrans.abort(),st(Z)})})),this.Version=(v=this,he(Kd.prototype,function(B){this.db=v,this._cfg={version:B,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(E=this,he(eu.prototype,function(B,O,z){if(this.db=E,this._ctx={table:B,index:O===":id"?null:O,or:z},this._cmp=this._ascending=qe,this._descending=function(U,F){return qe(F,U)},this._max=function(U,F){return 0<qe(U,F)?U:F},this._min=function(U,F){return qe(U,F)<0?U:F},this._IDBKeyRange=E._deps.IDBKeyRange,!this._IDBKeyRange)throw new Be.MissingAPI})),this.on("versionchange",function(B){0<B.newVersion?console.warn("Another connection wants to upgrade database '".concat(S.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(S.name,"'. Closing db now to resume the delete request.")),S.close({disableAutoOpen:!1})}),this.on("blocked",function(B){!B.newVersion||B.newVersion<B.oldVersion?console.warn("Dexie.delete('".concat(S.name,"') was blocked")):console.warn("Upgrade '".concat(S.name,"' blocked by other connection holding version ").concat(B.oldVersion/10))}),this._maxKey=si(l.IDBKeyRange),this._createTransaction=function(B,O,z,U){return new S.Transaction(B,O,z,S._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(B){S.on("blocked").fire(B),ai.toArray().filter(function(O){return O.name===S.name&&O!==S&&!O._state.vcFired}).map(function(O){return O.on("versionchange").fire(B)})},this.use(Wd),this.use(Yd),this.use(jd),this.use(Hd),this.use(qd),new Proxy(this,{get:function(B,O,z){var U;return O==="_vip"||(O==="table"?function(F){return Vi(S.table(F),N)}:(U=Reflect.get(B,O,z))instanceof L?Vi(U,N):O==="tables"?U.map(function(F){return Vi(F,N)}):O==="_createTransaction"?function(){return Vi(U.apply(this,arguments),N)}:U)}}));this.vip=N,M.forEach(function(B){return B(S)})}var Gi,Rr=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Zd=(Ao.prototype.subscribe=function(a,l,h){return this._subscribe(a&&typeof a!="function"?a:{next:a,error:l,complete:h})},Ao.prototype[Rr]=function(){return this},Ao);function Ao(a){this._subscribe=a}try{Gi={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Gi={indexedDB:null,IDBKeyRange:null}}function yu(a){var l,h=!1,y=new Zd(function(m){var v=W(a),E,S=!1,M={},V={},N={get closed(){return S},unsubscribe:function(){S||(S=!0,E&&E.abort(),B&&Ln.storagemutated.unsubscribe(U))}},B=(m.start&&m.start(N),!1),O=function(){return Qr(F)};function z(){return wo(V,M)}var U=function(K){qi(M,K),z()&&O()},F=function(){var K,Z,G;!S&&Gi.indexedDB&&(M={},K={},E&&E.abort(),E=new AbortController,G=(ne=>{var ce=Rn();try{v&&Tn();var fe=Jt(a,ne);return fe=v?fe.finally(Qt):fe}finally{ce&&Cn()}})(Z={subscr:K,signal:E.signal,requery:O,querier:a,trans:null}),B||(Ln.storagemutated.subscribe(U),B=!0),Promise.resolve(G).then(function(ne){h=!0,l=ne,S||Z.signal.aborted||(z()||(V=K,z())?O():(M={},Qr(function(){return!S&&m.next&&m.next(ne)})))},function(ne){h=!1,["DatabaseClosedError","AbortError"].includes(ne?.name)||S||Qr(function(){S||m.error&&m.error(ne)})}))};return setTimeout(O,0),N});return y.hasValue=function(){return h},y.getValue=function(){return l},y}var ir=pn;function Ro(a){var l=Mn;try{Mn=!0,Ln.storagemutated.fire(a),Eo(a,!0)}finally{Mn=l}}w(ir,i(i({},we),{delete:function(a){return new ir(a,{addons:[]}).delete()},exists:function(a){return new ir(a,{addons:[]}).open().then(function(l){return l.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(a){try{return l=ir.dependencies,h=l.indexedDB,l=l.IDBKeyRange,(yo(h)?Promise.resolve(h.databases()).then(function(y){return y.map(function(m){return m.name}).filter(function(m){return m!==Ht})}):po(h,l).toCollection().primaryKeys()).then(a)}catch{return st(new Be.MissingAPI)}var l,h},defineClass:function(){return function(a){f(this,a)}},ignoreTransaction:function(a){return Le.trans?dn(Le.transless||zt,a):a()},vip:go,async:function(a){return function(){try{var l=xo(a.apply(this,arguments));return l&&typeof l.then=="function"?l:Se.resolve(l)}catch(h){return st(h)}}},spawn:function(a,l,h){try{var y=xo(a.apply(h,l||[]));return y&&typeof y.then=="function"?y:Se.resolve(y)}catch(m){return st(m)}},currentTransaction:{get:function(){return Le.trans||null}},waitFor:function(a,l){return a=Se.resolve(typeof a=="function"?ir.ignoreTransaction(a):a).timeout(l||6e4),Le.trans?Le.trans.waitFor(a):a},Promise:Se,debug:{get:function(){return Rt},set:function(a){Gr(a)}},derive:I,extend:f,props:w,override:Re,Events:oe,on:Ln,liveQuery:yu,extendObservabilitySet:qi,getByKeyPath:Q,setByKeyPath:ie,delByKeyPath:function(a,l){typeof l=="string"?ie(a,l,void 0):"length"in l&&[].map.call(l,function(h){ie(a,h,void 0)})},shallowClone:ee,deepClone:j,getObjectDiff:_o,cmp:qe,asap:Y,minKey:-1/0,addons:[],connections:{get:ai.toArray}
3,errnames:Ue,dependencies:Gi,cache:rr,semVer:"4.4.4",version:"4.4.4".split(".").map(function(a){return parseInt(a)}).reduce(function(a,l,h){return a+l/Math.pow(10,2*h)})})),ir.maxKey=si(ir.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Ln(Pi,function(a){Mn||(a=new CustomEvent(oo,{detail:a}),Mn=!0,dispatchEvent(a),Mn=!1)}),addEventListener(oo,function(a){a=a.detail,Mn||Ro(a)}));var Cr,Mn=!1,gu=function(){};return typeof BroadcastChannel<"u"&&((gu=function(){(Cr=new BroadcastChannel(oo)).onmessage=function(a){return a.data&&Ro(a.data)}})(),typeof Cr.unref=="function"&&Cr.unref(),Ln(Pi,function(a){Mn||Cr.postMessage(a)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(a){if(!pn.disableBfCache&&a.persisted){Rt&&console.debug("Dexie: handling persisted pagehide"),Cr?.close();for(var l=0,h=ai.toArray();l<h.length;l++)h[l].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(a){!pn.disableBfCache&&a.persisted&&(Rt&&console.debug("Dexie: handling persisted pageshow"),gu(),Ro({all:new wt(-1/0,[[]])}))})),Se.rejectionMapper=function(a,l){return!a||a instanceof ye||a instanceof TypeError||a instanceof SyntaxError||!a.name||!Zn[a.name]?a:(l=new Zn[a.name](l||a.message,a),"stack"in a&&A(l,"stack",{get:function(){return this.inner.stack}}),l)},Gr(Rt),i(pn,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:pn,Entity:kr,PropModification:k,RangeSet:wt,add:function(a){return new k({add:a})},cmp:qe,default:pn,liveQuery:yu,mergeRanges:ui,rangesOverlap:su,remove:function(a){return new k({remove:a})},replacePrefix:function(a,l){return new k({replacePrefix:[a,l]})}}),{default:pn}),pn})})(ps)),ps.exports}var kb=_b(),Ea=js(kb);const el=Symbol.for("Dexie"),fr=globalThis[el]||(globalThis[el]=Ea);if(Ea.semVer!==fr.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Ea.semVer} and ${fr.semVer}`);const{liveQuery:wk,mergeRanges:vk,rangesOverlap:bk,RangeSet:Ek,cmp:xk,Entity:_k,PropModification:kk,replacePrefix:Sk,add:Ak,remove:Rk,DexieYProvider:Ck}=fr;class Sb extends fr{settings;constructor(){super("DebugDB"),this.version(1).stores({settings:"key"})}}const Ts=new Sb,Ih=typeof BroadcastChannel<"u"?new BroadcastChannel("debug-sync"):null,tl=async(t,e)=>{await Ts.settings.put({key:"filter",value:t}),await Ts.settings.put({key:"enabled",value:e?"true":"false"}),Ih?.postMessage({filter:t,enabled:e})},Ab=async()=>{const t=await Ts.settings.get("filter"),e=await Ts.settings.get("enabled");return{filter:t?.value||"",enabled:e?.value==="true"}},Pr=vb()(Eb((t,e)=>({filter:"",enabled:!1,setFilter:n=>{t({filter:n,enabled:!!n}),tl(n,!!n),typeof localStorage<"u"&&(n?(localStorage.setItem("debug",n),cn.enable(n)):(localStorage.removeItem("debug"),cn.disable()))},setEnabled:n=>{const r=n?"*":"";t({filter:r,enabled:n}),tl(r,n),typeof localStorage<"u"&&(n?(localStorage.setItem("debug","*"),cn.enable("*")):(localStorage.removeItem("debug"),cn.disable()))},toggleDebug:()=>{const{enabled:n}=e();e().setEnabled(!n)}})));Ab().then(({filter:t,enabled:e})=>{t&&e&&(Pr.setState({filter:t,enabled:e}),typeof localStorage<"u"&&(localStorage.setItem("debug",t),cn.enable(t)))});Ih?.addEventListener("message",t=>{const{filter:e,enabled:n}=t.data;Pr.setState({filter:e,enabled:n}),typeof localStorage<"u"&&(e?(localStorage.setItem("debug",e),cn.enable(e)):(localStorage.removeItem("debug"),cn.disable()))});const Rb=new Set,nl=typeof BroadcastChannel<"u"?new BroadcastChannel("debug-logs"):null;function Cb(t){const{filter:e}=Pr.getState();return e?e.split(",").map(r=>r.trim()).filter(Boolean).some(r=>{if(r==="*")return!0;if(r.endsWith(":*")){const i=r.slice(0,-2);return t.startsWith(i)}return t===r}):!1}function jo(t,e,n){if(!Cb(t))return;const r={timestamp:Date.now(),namespace:t,level:e,message:n};if(typeof window>"u"&&nl){nl.postMessage(r);return}Tb()}function Tb(){Rb.forEach(t=>t())}function Ib(t){const e=cn(t),n=cn(`${t}:warn`),r=cn(`${t}:error`);return{log:(...i)=>{if(e(...i),!!Pr.getState().enabled)try{jo(t,"log",Vo(i))}catch{}},warn:(...i)=>{if(n(...i),!!Pr.getState().enabled)try{jo(t,"warn",Vo(i))}catch{}},error:(...i)=>{if(r(...i),!!Pr.getState().enabled)try{jo(t,"error",Vo(i))}catch{}}}}function Vo(t){return t.map(e=>{if(typeof e=="string")return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}).join(" ")}const Bb={NDK_RELAY:"nostr:relay"};
3function Lb(t,e){const n=r=>{e.some(i=>i[0]===r[0]&&i[1]===r[1])||e.push(r)};for(const r of t.matchAll(/nostr:(n(?:pub|profile|ote|event|addr)1[a-z0-9]+)/gi))try{const i=Wn.decode(r[1]);i.type==="npub"?n(["p",i.data]):i.type==="nprofile"?n(["p",i.data.pubkey]):i.type==="note"?n(["q",i.data]):i.type==="nevent"?(n(["q",i.data.id,i.data.relays?.[0]??"",i.data.author??""]),i.data.author&&n(["p",i.data.author])):i.type==="naddr"&&(n(["q",`${i.data.kind}:${i.data.pubkey}:${i.data.identifier}`,i.data.relays?.[0]??"",i.data.pubkey]),n(["p",i.data.pubkey]))}catch{}}function Mb(t,e,n=6){const r=new Map;for(const s of t){if(s.kind!==10002)continue;const o=r.get(s.pubkey);(!o||s.created_at>o.created_at)&&r.set(s.pubkey,s)}const i=new Set;for(const s of r.values())for(const[o,c,u]of s.tags)if(!(o!=="r"||!c||u&&u!==e))try{const f=new URL(c);if(!["wss:","ws:"].includes(f.protocol)||f.username||f.password)continue;if(i.add(f.toString().replace(/\/$/,"")),i.size>=n)return[...i]}catch{}return[...i]}function Ob(t,e){if(e.opts.relayUrls||e.opts.cacheUsage==="cache-only")return;const n=new Set,r=new Set(xa(t.explicitRelayUrls)),i=(u,f)=>{const p=f.filter(g=>r.has(g)||n.has(g)||n.size>=8?!1:(n.add(g),!0));if(!p.length||e.closed)return;const d=t.subscribe(u,{relayUrls:p,closeOnEose:!1,cacheUsage:"network-only"});e.waitForHistory(d),d.on("event",(g,w,x,A)=>e.eventReceived(g,w,A)),e.once("close",()=>d.stop())},s=e.filters.filter(u=>u.authors?.length&&u.kinds?.length&&u.kinds.every(f=>f===0||f===10002));if(s.length&&i(s,t.discoveryRelayUrls),t.enableRelayHints&&i(e.filters,xa(e.opts.relayHints??[])),!t.enableOutboxModel||e.filters.some(u=>u.kinds?.includes(10002)))return;const o=[...new Set(e.filters.flatMap(u=>u.authors??[]))].filter(u=>/^[0-9a-f]{64}$/.test(u)).slice(0,64);if(!o.length)return;const c=t.subscribe({kinds:[10002],authors:o});e.waitForHistory(c),c.on("event",u=>i(e.filters,Mb([u],"write"))),e.once("close",()=>c.stop())}function xa(t){const e=new Set;for(const n of t)try{const r=new URL(n);if(!["ws:","wss:"].includes(r.protocol)||r.username||r.password)continue;if(e.add(r.toString().replace(/\/$/,"")),e.size>=6)break}catch{}return[...e]}var Go={},rl;function Db(){return rl||(rl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.bytes=t.stringToBytes=t.str=t.bytesToString=t.hex=t.utf8=t.bech32m=t.bech32=t.base58check=t.base58xmr=t.base58xrp=t.base58flickr=t.base58=t.base64url=t.base64=t.base32crockford=t.base32hex=t.base32=t.base16=t.utils=t.assertNumber=void 0;function e($){if(!Number.isSafeInteger($))throw new Error(`Wrong integer: ${$}`)}t.assertNumber=e;function n(...$){const H=(P,X)=>re=>P(X(re)),C=Array.from($).reverse().reduce((P,X)=>P?H(P,X.encode):X.encode,void 0),j=$.reduce((P,X)=>P?H(P,X.decode):X.decode,void 0);return{encode:C,decode:j}}function r($){return{encode:H=>{if(!Array.isArray(H)||H.length&&typeof H[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return H.map(C=>{if(e(C),C<0||C>=$.length)throw new Error(`Digit index outside alphabet: ${C} (alphabet: ${$.length})`);return $[C]})},decode:H=>{if(!Array.isArray(H)||H.length&&typeof H[0]!="string")throw new Error("alphabet.decode input should be array of strings");return H.map(C=>{if(typeof C!="string")throw new Error(`alphabet.decode: not string element=${C}`);const j=$.indexOf(C);if(j===-1)throw new Error(`Unknown letter: "${C}". Allowed: ${$}`);return j})}}}function i($=""){if(typeof $!="string")throw new Error("join separator should be string");return{encode:H=>{if(!Array.isArray(H)||H.length&&typeof H[0]!="string")throw new Error("join.encode input should be array of strings");for(let C of H)if(typeof C!="string")throw new Error(`join.encode: non-string input=${C}`);return H.join($)},decode:H=>{if(typeof H!="string")throw new Error("join.decode input should be string");return H.split($)}}}function s($,H="="){if(e($),typeof H!="string")throw new Error("padding chr should be string");return{encode(C){if(!Array.isArray(C)||C.length&&typeof C[0]!="string")throw new Error("padding.encode input should be array of strings");
3for(let j of C)if(typeof j!="string")throw new Error(`padding.encode: non-string input=${j}`);for(;C.length*$%8;)C.push(H);return C},decode(C){if(!Array.isArray(C)||C.length&&typeof C[0]!="string")throw new Error("padding.encode input should be array of strings");for(let P of C)if(typeof P!="string")throw new Error(`padding.decode: non-string input=${P}`);let j=C.length;if(j*$%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;j>0&&C[j-1]===H;j--)if(!((j-1)*$%8))throw new Error("Invalid padding: string has too much padding");return C.slice(0,j)}}}function o($){if(typeof $!="function")throw new Error("normalize fn should be function");return{encode:H=>H,decode:H=>$(H)}}function c($,H,C){if(H<2)throw new Error(`convertRadix: wrong from=${H}, base cannot be less than 2`);if(C<2)throw new Error(`convertRadix: wrong to=${C}, base cannot be less than 2`);if(!Array.isArray($))throw new Error("convertRadix: data should be array");if(!$.length)return[];let j=0;const P=[],X=Array.from($);for(X.forEach(re=>{if(e(re),re<0||re>=H)throw new Error(`Wrong integer: ${re}`)});;){let re=0,xe=!0;for(let pe=j;pe<X.length;pe++){const _e=X[pe],_=H*re+_e;if(!Number.isSafeInteger(_)||H*re/H!==re||_-_e!==H*re)throw new Error("convertRadix: carry overflow");if(re=_%C,X[pe]=Math.floor(_/C),!Number.isSafeInteger(X[pe])||X[pe]*C+re!==_)throw new Error("convertRadix: carry overflow");if(xe)X[pe]?xe=!1:j=pe;else continue}if(P.push(re),xe)break}for(let re=0;re<$.length-1&&$[re]===0;re++)P.push(0);return P.reverse()}const u=($,H)=>H?u(H,$%H):$,f=($,H)=>$+(H-u($,H));function p($,H,C,j){if(!Array.isArray($))throw new Error("convertRadix2: data should be array");if(H<=0||H>32)throw new Error(`convertRadix2: wrong from=${H}`);if(C<=0||C>32)throw new Error(`convertRadix2: wrong to=${C}`);if(f(H,C)>32)throw new Error(`convertRadix2: carry overflow from=${H} to=${C} carryBits=${f(H,C)}`);let P=0,X=0;const re=2**C-1,xe=[];for(const pe of $){if(e(pe),pe>=2**H)throw new Error(`convertRadix2: invalid data word=${pe} from=${H}`);if(P=P<<H|pe,X+H>32)throw new Error(`convertRadix2: carry overflow pos=${X} from=${H}`);for(X+=H;X>=C;X-=C)xe.push((P>>X-C&re)>>>0);P&=2**X-1}if(P=P<<C-X&re,!j&&X>=H)throw new Error("Excess padding");if(!j&&P)throw new Error(`Non-zero padding: ${P}`);return j&&X>0&&xe.push(P>>>0),xe}function d($){return e($),{encode:H=>{if(!(H instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(H),2**8,$)},decode:H=>{if(!Array.isArray(H)||H.length&&typeof H[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(H,$,2**8))}}}function g($,H=!1){if(e($),$<=0||$>32)throw new Error("radix2: bits should be in (0..32]");if(f(8,$)>32||f($,8)>32)throw new Error("radix2: carry overflow");return{encode:C=>{if(!(C instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return p(Array.from(C),8,$,!H)},decode:C=>{if(!Array.isArray(C)||C.length&&typeof C[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(p(C,$,8,H))}}}function w($){if(typeof $!="function")throw new Error("unsafeWrapper fn should be function");return function(...H){try{return $.apply(null,H)}catch{}}}function x($,H){if(e($),typeof H!="function")throw new Error("checksum fn should be function");return{encode(C){if(!(C instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const j=H(C).slice(0,$),P=new Uint8Array(C.length+$);return P.set(C),P.set(j,C.length),P},decode(C){if(!(C instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const j=C.slice(0,-$),P=H(j).slice(0,$),X=C.slice(-$);for(let re=0;re<$;re++)if(P[re]!==X[re])throw new Error("Invalid checksum");return j}}}t.utils={alphabet:r,chain:n,checksum:x,radix:d,radix2:g,join:i,padding:s},t.base16=n(g(4),r("0123456789ABCDEF"),i("")),t.base32=n(g(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),t.base32hex=n(g(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),t.base32crockford=n(g(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),o($=>$.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),t.base64=n(g(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
3+/"),s(6),i("")),t.base64url=n(g(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const A=$=>n(d(58),r($),i(""));t.base58=A("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.base58flickr=A("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),t.base58xrp=A("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const I=[0,2,3,5,6,7,9,10,11];t.base58xmr={encode($){let H="";for(let C=0;C<$.length;C+=8){const j=$.subarray(C,C+8);H+=t.base58.encode(j).padStart(I[j.length],"1")}return H},decode($){let H=[];for(let C=0;C<$.length;C+=11){const j=$.slice(C,C+11),P=I.indexOf(j.length),X=t.base58.decode(j);for(let re=0;re<X.length-P;re++)if(X[re]!==0)throw new Error("base58xmr: wrong padding");H=H.concat(Array.from(X.slice(X.length-P)))}return Uint8Array.from(H)}};const T=$=>n(x(4,H=>$($(H))),t.base58);t.base58check=T;const te=n(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),ae=[996825010,642813549,513874426,1027748829,705979059];function Re($){const H=$>>25;let C=($&33554431)<<5;for(let j=0;j<ae.length;j++)(H>>j&1)===1&&(C^=ae[j]);return C}function le($,H,C=1){const j=$.length;let P=1;for(let X=0;X<j;X++){const re=$.charCodeAt(X);if(re<33||re>126)throw new Error(`Invalid prefix (${$})`);P=Re(P)^re>>5}P=Re(P);for(let X=0;X<j;X++)P=Re(P)^$.charCodeAt(X)&31;for(let X of H)P=Re(P)^X;for(let X=0;X<6;X++)P=Re(P);return P^=C,te.encode(p([P%2**30],30,5,!1))}function Y($){const H=$==="bech32"?1:734539939,C=g(5),j=C.decode,P=C.encode,X=w(j);function re(_,W,we=90){if(typeof _!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof _}`);if(!Array.isArray(W)||W.length&&typeof W[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof W}`);const ke=_.length+7+W.length;if(we!==!1&&ke>we)throw new TypeError(`Length ${ke} exceeds limit ${we}`);return _=_.toLowerCase(),`${_}1${te.encode(W)}${le(_,W,H)}`}function xe(_,W=90){if(typeof _!="string")throw new Error(`bech32.decode input should be string, not ${typeof _}`);if(_.length<8||W!==!1&&_.length>W)throw new TypeError(`Wrong string length: ${_.length} (${_}). Expected (8..${W})`);const we=_.toLowerCase();if(_!==we&&_!==_.toUpperCase())throw new Error("String must be lowercase or uppercase");_=we;const ke=_.lastIndexOf("1");if(ke===0||ke===-1)throw new Error('Letter "1" must be present between prefix and data only');const ye=_.slice(0,ke),Ce=_.slice(ke+1);if(Ce.length<6)throw new Error("Data must be at least 6 characters long");const Me=te.decode(Ce).slice(0,-6),Ve=le(ye,Me,H);if(!Ce.endsWith(Ve))throw new Error(`Invalid checksum in ${_}: expected "${Ve}"`);return{prefix:ye,words:Me}}const pe=w(xe);function _e(_){const{prefix:W,words:we}=xe(_,!1);return{prefix:W,words:we,bytes:j(we)}}return{encode:re,decode:xe,decodeToBytes:_e,decodeUnsafe:pe,fromWords:j,fromWordsUnsafe:X,toWords:P}}t.bech32=Y("bech32"),t.bech32m=Y("bech32m"),t.utf8={encode:$=>new TextDecoder().decode($),decode:$=>new TextEncoder().encode($)},t.hex=n(g(4),r("0123456789abcdef"),i(""),o($=>{if(typeof $!="string"||$.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof $} with length ${$.length}`);return $.toLowerCase()}));const Q={utf8:t.utf8,hex:t.hex,base16:t.base16,base32:t.base32,base64:t.base64,base64url:t.base64url,base58:t.base58,base58xmr:t.base58xmr},ie=`Invalid encoding type. Available types: ${Object.keys(Q).join(", ")}`,ee=($,H)=>
3{if(typeof $!="string"||!Q.hasOwnProperty($))throw new TypeError(ie);if(!(H instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return Q[$].encode(H)};t.bytesToString=ee,t.str=t.bytesToString;const ge=($,H)=>{if(!Q.hasOwnProperty($))throw new TypeError(ie);if(typeof H!="string")throw new TypeError("stringToBytes() expects string");return Q[$].decode(H)};t.stringToBytes=ge,t.bytes=t.stringToBytes})(Go)),Go}var Yo,il;function Nb(){if(il)return Yo;il=1;const{bech32:t,hex:e,utf8:n}=Db(),r={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},i={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},s={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},o={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},c={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},u=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],f={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},p=BigInt("2100000000000000000"),d=BigInt(1e11),g={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},w={};for(let le=0,Y=Object.keys(g);le<Y.length;le++){const Q=Y[le],ie=g[Y[le]].toString();w[ie]=Q}const x={1:le=>e.encode(t.fromWordsUnsafe(le)),16:le=>e.encode(t.fromWordsUnsafe(le)),13:le=>n.encode(t.fromWordsUnsafe(le)),19:le=>e.encode(t.fromWordsUnsafe(le)),23:le=>e.encode(t.fromWordsUnsafe(le)),27:le=>e.encode(t.fromWordsUnsafe(le)),6:I,24:I,3:T,5:te};function A(le){return Y=>({tagCode:parseInt(le),words:t.encode("unknown",Y,Number.MAX_SAFE_INTEGER)})}function I(le){return le.reverse().reduce((Y,Q,ie)=>Y+Q*Math.pow(32,ie),0)}function T(le){const Y=[];let Q,ie,ee,ge,$,H=t.fromWordsUnsafe(le);for(;H.length>0;)Q=e.encode(H.slice(0,33)),ie=e.encode(H.slice(33,41)),ee=parseInt(e.encode(H.slice(41,45)),16),ge=parseInt(e.encode(H.slice(45,49)),16),$=parseInt(e.encode(H.slice(49,51)),16),H=H.slice(51),Y.push({pubkey:Q,short_channel_id:ie,fee_base_msat:ee,fee_proportional_millionths:ge,cltv_expiry_delta:$});return Y}function te(le){const Y=le.slice().reverse().map(ee=>[!!(ee&1),!!(ee&2),!!(ee&4),!!(ee&8),!!(ee&16)]).reduce((ee,ge)=>ee.concat(ge),[]);for(;Y.length<u.length*2;)Y.push(!1);const Q={};u.forEach((ee,ge)=>{let $;Y[ge*2]?$="required":Y[ge*2+1]?$="supported":$="unsupported",Q[ee]=$});const ie=Y.slice(u.length*2);return Q.extra_bits={start_bit:u.length*2,bits:ie,has_required:ie.reduce((ee,ge,$)=>$%2!==0?ee||!1:ee||ge,!1)},Q}function ae(le,Y){let Q,ie;if(le.slice(-1).match(/^[munp]$/))Q=le.slice(-1),ie=le.slice(0,-1);else{if(le.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");ie=le}if(!ie.match(/^\d+$/))throw new Error("Not a valid human readable amount");const ee=BigInt(ie),ge=Q?ee*d/f[Q]:ee*d;if(Q==="p"&&ee%BigInt(10)!==BigInt(0)||ge>p)throw new Error("Amount is outside of valid range");return Y?ge.toString():ge}function Re(le,Y){if(typeof le!="string")throw new Error("Lightning Payment Request must be string");if(le.slice(0,2).toLowerCase()!=="ln")throw new Error("Not a proper lightning payment request");const Q=[],ie=t.decode(le,Number.MAX_SAFE_INTEGER);le=le.toLowerCase();const ee=ie.prefix;let ge=ie.words,$=le.slice(ee.length+1),H=ge.slice(-104);ge=ge.slice(0,-104);let C=ee.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(C&&!C[2]&&(C=ee.match(/^ln(\S+)$/)),!C)throw new Error("Not a proper lightning payment request");Q.push({name:"lightning_network",letters:"ln"});const j=C[1];let P;if(Y){if(Y.bech32===void 0||Y.pubKeyHash===void 0||Y.scriptHash===void 0||!Array.isArray(Y.validWitnessVersions))throw new Error("Invalid network");P=Y}else switch(j){case r.bech32:P=r;break;case i.bech32:P=i;break;case s.bech32:P=s;break;case o.bech32:P=o;break;case c.bech32:P=c;break}if(!P||P.bech32!==j)throw new Error("Unknown coin bech32 prefix");Q.push({name:"coin_network",letters:j,value:P});const X=C[2];let re;if(X){const ye=C[3];re=ae(X+ye,!0),Q.push({name:"amount",letters:C[2]+C[3],value:re})}else re=null;Q.push({name:"separator",letters:"1"});const xe=I(ge.slice(0,7));ge=ge.slice(7),Q.push({name:"timestamp",letters:$.slice(0,7),value:xe}),$=$.slice(7);let pe,_e,_,W;for(;ge.length>0;){const ye=ge[0].toString();pe=w[ye]||"unknown_tag",_e=x[ye]||A(ye),ge=ge.slice(1),_=I(ge.slice(0,2)),ge=ge.slice(2),W=ge.slice(0,_),ge=ge.slice(_),Q.push({name:pe,tag:$[0],letters:$.slice(0,3+_),value:_e(W)}),$=$.slice(3+_)}Q.push({name:"signature",letters:$.slice(0,104),value:e.encode(t.fromWordsUnsafe(H))}),$=$.slice(104),Q.push({name:"checksum",letters:$});let we={paymentRequest:le,sections:Q,get expiry(){let ye=Q.find(Ce=>Ce.name==="expiry");if(ye)return ke("timestamp")+ye.value},get route_hints(){return Q.filter(ye=>ye.name==="route_hint").map(ye=>ye.value)}};for(let ye in g)ye!=="route_hint"&&Object.defineProperty(we,ye,{get(){return ke(ye)}});return we;function ke(ye){let Ce=Q.find(Me=>Me.name===ye);return Ce?Ce.value:void 0}}return Yo={decode:Re,hrpToMillisat:ae},Yo}Nb();const Zo={ONLY_CACHE:"cache-only",ONLY_RELAY:"network-only",PARALLEL:"c
3ache-first"};class bi{handlers=new Map;on(e,n){const r=this.handlers.get(e)??new Set;return r.add(n),this.handlers.set(e,r),this}once(e,n){const r=(...i)=>{this.off(e,r),n(...i)};return this.on(e,r)}off(e,n){return this.handlers.get(e)?.delete(n),this}removeListener(e,n){return this.off(e,n)}removeAllListeners(e){return e?this.handlers.delete(e):this.handlers.clear(),this}emit(e,...n){const r=this.handlers.get(e);for(const i of[...r??[]])i(...n);return!!r?.size}}function Bh(t){try{const e=JSON.parse(t.content);return{...e,created_at:t.created_at,...t.id?{profileEvent:JSON.stringify(t instanceof Dt?t.rawEvent():t)}:{},displayName:e.display_name??e.displayName,image:e.picture??e.image}}catch{return{}}}class Dt extends bi{id="";pubkey="";created_at=Math.floor(Date.now()/1e3);kind=1;tags=[];content="";sig="";nostr;relay;publishStatus;constructor(e,n){super(),this.nostr=e,n&&typeof n=="object"&&Object.assign(this,n.rawEvent?.()??n)}rawEvent(){return{id:this.id,pubkey:this.pubkey,created_at:this.created_at,kind:this.kind,tags:this.tags.map(e=>[...e]),content:this.content,sig:this.sig}}async toNostrEvent(e){return e&&(this.pubkey=e),!this.pubkey&&this.nostr?.signer&&(this.pubkey=(await this.nostr.signer.user()).pubkey),this.id=Dr(this.rawEvent()),this.rawEvent()}async sign(e=this.nostr?.signer,n){if(!e)throw new Error("No signer available");return this.pubkey=(await e.user()).pubkey,!n?.skipContentTagging&&[1,20,1111,30023,30402].includes(this.kind)&&Lb(this.content,this.tags),this.nostr?.clientName&&(this.removeTag("client"),(!this.nostr.clientTagFilter||this.nostr.clientTagFilter(this))&&this.tags.push(["client",this.nostr.clientName])),this.id=Dr(this.rawEvent()),this.sig=await e.sign(this.rawEvent()),this.sig}async publish(e,n,r,i){if(this.sig||await this.sign(),!this.nostr)throw new Error("No event client");const s=e?await e.publish(this):await this.nostr.publishEvent(this);return this.publishStatus="success",this.emit("published",s),s}tagValue(e){return this.tags.find(n=>n[0]===e)?.[1]}getMatchingTags(e){return this.tags.filter(n=>n[0]===e)}removeTag(e){this.tags=this.tags.filter(n=>n[0]!==e)}get onRelays(){return this.relay?[this.relay]:[]}get author(){return this.nostr?.getUser({pubkey:this.pubkey})??new Lh({pubkey:this.pubkey})}set author(e){this.pubkey=e.pubkey}get dTag(){return this.tagValue("d")}set dTag(e){this.removeTag("d"),e!==void 0&&this.tags.push(["d",e])}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}isParamReplaceable(){return this.kind>=3e4&&this.kind<4e4}isReplaceable(){return this.kind===0||this.kind===3||this.kind>=1e4&&this.kind<2e4}isEphemeral(){return this.kind>=2e4&&this.kind<3e4}tagAddress(){return`${this.kind}:${this.pubkey}:${this.dTag??""}`}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}deduplicationKey(){return this.isParamReplaceable()?this.tagAddress():this.isReplaceable()?`${this.kind}:${this.pubkey}`:this.id}tagReference(e){return[this.isParamReplaceable()?"a":"e",this.tagId(),this.relay?.url??"",...e?[e]:[]]}referenceTags(e){return[this.tagReference(e),["p",this.pubkey]]}tag(e,n){return this.tags.push(...e instanceof Dt?e.referenceTags(n):[["p",e.pubkey]]),this}filter(){return{[this.isParamReplaceable()?"#a":"#e"]:[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()],kinds:[1111]}:{"#E":[this.tagId()],kinds:[1111]}}encode(){return this.isParamReplaceable()?Wn.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.dTag??""}):Wn.neventEncode({id:this.id,author:this.pubkey,kind:this.kind})}reply(){const e=new Dt(this.nostr,{kind:this.kind===1?1:1111});if(this.kind===1){const n=this.tags.find(r=>r[0]==="e"&&r[3]==="root");e.tags=[...n?[[...n]]:[],this.tagReference(n?"reply":"root"),["p",this.pubkey]]}else{const n=this.kind===1111?this.tags.filter(i=>["A","E","K","P"].includes(i[0])):[],r=n.length?n.map(i=>[...i]):[[this.isParamReplaceable()?"A":"E",this.tagId(),this.relay?.url??""],["K",String(this.kind)],["P",this.pubkey]];e.tags=[...r,[this.isParamReplaceable()?"a":"e",this.tagId(),this.relay?.url??""],["k",String(this.kind)],["p",this.pubkey]]}return e}async repost(e=!0){const n=new Dt(this.nostr,{kind:this.kind===1?6:16,content:JSON.stringify(this.rawEvent()),tags:[["e",this.id,this.relay?.url??""],["p",this.pubkey],...this.kind!==1?[["k",String(this.kind)]]:[]]});return e&&await n.publish(),n}async delete(e="",n=!0,r){const i=new Dt(this.nostr,{kind:5,content:e,tags:[this.tagReference(),["k",String(this.kind)]]});return n&&await i.publish(),i}async encrypt(e,n=this.nostr?.signer,r="nip04"){if(!n)throw new Error("No signer");const i=e??this.nostr?.getUser({pubkey:this.tagValue("p")??""});if(!i)throw new Error("No recipient");
3this.content=await n.encrypt(i,this.content,r)}async decrypt(e,n=this.nostr?.signer,r="nip04"){if(!n)throw new Error("No signer");return this.content=await n.decrypt(e??this.author,this.content,r),this.content}get isValid(){return!!this.sig&&Hr(this.rawEvent())}verifySignature(){return this.isValid}}class Lh{pubkey;profile;nostr;constructor(e){this.pubkey=e.pubkey??e.hexpubkey??(e.npub?Wn.decode(e.npub).data:"")}get npub(){return Wn.npubEncode(this.pubkey)}get hexpubkey(){return this.pubkey}async fetchProfile(e){const n=await this.nostr?.fetchEvent({kinds:[0],authors:[this.pubkey]});return n&&(this.profile=Bh(n)),this.profile}async validateNip05(e){return(await vc.queryProfile(e))?.pubkey===this.pubkey}async publish(){if(!this.nostr)throw new Error("No event client");return new Dt(this.nostr,{kind:0,content:JSON.stringify(this.profile??{})}).publish()}}class Mh extends bi{constructor(e,n,r){super(),this.url=e,this.nostr=r}url;status=0;connectivity={connectionStats:{attempts:0,success:0}};nostr;get connected(){return this.status>=5}async connect(){this.status=1,this.nostr?.transportPlugins.forEach(e=>e.connectRelay?.(this.url)),this.nostr?.transportPlugins.length||await this.nostr?.connect(),this.emit("connect"),this.emit("ready")}disconnect(){this.status=0,this.nostr?.transportPlugins.forEach(e=>e.disconnectRelay?.(this.url)),this.emit("disconnect")}async publish(e,n){if(!this.nostr)throw new Error("No event client");if(this.nostr.transportPlugins.length){for(const i of this.nostr.transportPlugins)if((await i.publish?.(e,[this],{requireAck:!0}))?.remoteAccepted)return!0;return!1}return(await this.nostr.getRuntime().publish(e.rawEvent(),{relays:[this.url],requireAck:!0})).remoteAccepted}}class rs extends Error{constructor(e,n=new Map,r=new Set){super(e),this.relayErrors=n,this.publishedToRelays=r}relayErrors;publishedToRelays}class Pb extends bi{constructor(e,n,r={}){super(),this.nostr=e,this.filters=n,this.opts=r,r.subId&&(this.subId=r.subId)}nostr;filters;opts;subId=crypto.randomUUID();internalId=this.subId;relayFilters=new Map;closed=!1;seen=new Set;cleanup;start(){this.nostr.startSubscription(this)}setCleanup(e){this.closed?e():this.cleanup=e}eventReceived(e,n,r=!1){if(this.closed)return;const i=e instanceof Dt?e:new Dt(this.nostr,e);if(this.seen.has(i.id)){this.emit("event:dup",i,n,0,this,r);return}this.seen.add(i.id),this.seen.size>1e4&&this.seen.delete(this.seen.values().next().value),i.relay=n,this.emit("event",i,n,this,r)}completion;historyPending=new Set;historyReports=[];ownHistoryReceived=!1;historyEmitted=!1;waitForHistory(e){this.historyEmitted||(this.historyPending.add(e),e.once("eose",()=>{this.historyPending.delete(e),e.completion&&this.historyReports.push(e.completion),this.emitHistory()}))}eoseReceived(e,n){this.completion=n,this.ownHistoryReceived=!0,this.emitHistory()}emitHistory(){if(!(this.closed||!this.ownHistoryReceived||this.historyPending.size)){if(this.historyEmitted=!0,this.historyReports.length){const e=[...this.historyReports,...this.completion?[this.completion]:[]],n=e.every(r=>r.complete);this.completion={complete:n,reason:n?"eose":e.find(r=>!r.complete)?.reason??"unavailable",sources:e.flatMap(r=>r.sources)}}this.emit("eose",this),this.opts.closeOnEose&&this.completion?.complete!==!1&&this.stop()}}stop(){this.closed||(this.closed=!0,this.cleanup?.(),this.nostr.subscriptions.delete(this.subId),this.emit("close"),this.removeAllListeners())}}class Fb extends bi{signer;activeUser;explicitRelayUrls;transportPlugins=[];subscriptions=new Map;clientName;clientTagFilter;cacheAdapter;enableOutboxModel=!1;discoveryRelayUrls;enableRelayHints;devWriteRelaySet;verifyEvent;runtime;signAuthEvent;pool;subManager={subscriptions:this.subscriptions,seenEvents:new Map,seenEvent:(e,n)=>{const r=this.subManager.seenEvents.get(e)??new Set;r.add(n),this.subManager.seenEvents.set(e,r),this.subManager.seenEvents.size>1e4&&this.subManager.seenEvents.delete(this.subManager.seenEvents.keys().next().value)},dispatchEvent:(e,n,r)=>{const i=e instanceof Dt?e.rawEvent():e;for(const s of this.subscriptions.values())jf(s.filters,i)&&s.eventReceived(i,n);this.runtime&&this.runtime.ingest(i,n?.url??"local")}};constructor(e={}){super(),this.verifyEvent=e.verifyEvent,this.signAuthEvent=e.signAuthEvent,this.enableOutboxModel=e.enableOutboxModel??!1,this.discoveryRelayUrls=xa(e.discoveryRelayUrls??[]),this.enableRelayHints=e.enableRelayHints??!1,this.signer=e.signer,this.cacheAdapter=e.cac
3heAdapter,this.explicitRelayUrls=e.explicitRelayUrls??[],this.clientName=e.clientName,this.clientTagFilter=e.clientTagFilter;const n=new Map;this.pool=Object.assign(new bi,{relays:n,connectedRelays:()=>[...n.values()].filter(r=>r.connected),connect:()=>this.connect(),getRelay:(r,i=!0)=>{let s=n.get(r);return s||(s=new Mh(r,void 0,this),n.set(r,s)),s},addRelay:r=>{r.nostr=this,n.set(r.url,r),this.transportPlugins.forEach(i=>i.addRelay?.(r.url)),this.runtime?.setRelays([...n.keys()])},removeRelay:r=>{this.transportPlugins.forEach(s=>s.removeRelay?.(r));const i=n.delete(r);return this.runtime?.setRelays([...n.keys()]),i}});for(const r of this.explicitRelayUrls)this.pool.getRelay(r,!1)}getRuntime(){return this.runtime??=ib({relays:this.explicitRelayUrls,store:this.cacheAdapter?.store,batchWindowMs:20,historyTimeoutMs:5e3,verifyEvent:this.verifyEvent,signAuthEvent:this.signAuthEvent??(async(e,n)=>{const r=new Dt(this,n);return await r.sign(),r.rawEvent()})})}async connect(e){this.getRuntime()}assertSigner(){if(!this.signer)throw new Error("No signer available")}async getUserFromNip05(e){const n=await vc.queryProfile(e);return n?this.getUser({pubkey:n.pubkey}):void 0}getUser(e,n){const r=new Lh(e);return r.nostr=this,r}subscribe(e,n={},r,i=!0){typeof r=="boolean"&&(i=r,r=void 0);const s=new Pb(this,(Array.isArray(e)?e:[e]).map(o=>Object.fromEntries(Object.entries(o).filter(([,c])=>c!==void 0))),{...n,...r?{relayUrls:[...r.relays].map(o=>o.url)}:{}});return this.subscriptions.set(s.subId,s),i&&queueMicrotask(()=>s.start()),s}async startSubscription(e){if(e.closed)return;if(Ob(this,e),this.transportPlugins.length){for(const r of this.transportPlugins)r.onSubscribe?.(e,e.filters,e.opts);return}const n=this.getRuntime().subscribe(e.filters,{onEvent:(r,i)=>e.eventReceived(r,i.source.startsWith("ws")?this.pool.getRelay(i.source):void 0,i.cached),onEose:r=>e.eoseReceived(null,r),onError:r=>e.emit("error",r)},{cache:e.opts.cacheUsage??"cache-first",relays:e.opts.relayUrls,isolated:e.opts.isolated,sources:e.opts.isolated?[]:void 0});e.setCleanup(()=>n.close())}async fetchEvents(e,n={},r){return this.collectEvents(e,n,r)}collectEvents(e,n,r,i){return new Promise(s=>{const o=new Map,c=this.subscribe(e,{...n,closeOnEose:!0},r),u=()=>{clearTimeout(f),c.stop(),s(new Set(o.values()))},f=setTimeout(u,1e4);c.on("event",p=>{const d=p.deduplicationKey(),g=o.get(d);(!g||g.created_at<p.created_at)&&o.set(d,p),p.id===i&&u()}),c.on("eose",u)})}async fetchEvent(e,n={},r){let i;if(typeof e=="string")if(e.startsWith("nostr:")&&(e=e.slice(6)),/^[0-9a-f]{64}$/.test(e))i={ids:[e]};else{const c=Wn.decode(e);if(c.type==="note")i={ids:[c.data]};else if(c.type==="nevent")i={ids:[c.data.id]},n={...n,relayHints:[...n.relayHints??[],...c.data.relays??[]]};else if(c.type==="naddr")i={kinds:[c.data.kind],authors:[c.data.pubkey],"#d":[c.data.identifier]},n={...n,relayHints:[...n.relayHints??[],...c.data.relays??[]]};else return null}else i=e;const s=i.ids?.length===1&&/^[0-9a-f]{64}$/.test(i.ids[0])?i.ids[0]:void 0;return[...await this.collectEvents(i,n,r,s)].sort((c,u)=>u.created_at-c.created_at)[0]??null}async publishEvent(e,n,r){if(this.transportPlugins.length){const o=new Set;for(const c of this.transportPlugins){const u=await c.publish?.(e,n?[...n.relays]:void 0,r);if(!(r?.requireAck&&!u?.remoteAccepted))for(const f of u?.sources??[])f.accepted&&o.add(this.pool.getRelay(f.id))}if(r?.requireAck&&o.size===0)throw new rs("No relay confirmed the event");return o}let i=n?[...n.relays].map(o=>o.url):void 0;if(r?.connectedOnly&&(i=this.getRuntime().getRelayStats().filter(o=>o.connected&&(!i||i.includes(o.url))).map(o=>o.url),!i.length))throw new rs("No connected message server");const s=await this.getRuntime().publish(e.rawEvent(),{relays:i,requireAck:r?.requireAck});if(r?.requireAck&&!s.remoteAccepted)throw new rs("No relay confirmed the event");if(!s.remoteAccepted&&!s.queued)throw new rs("Publication was not accepted");return new Set(s.sources.filter(o=>o.accepted).map(o=>this.pool.getRelay(o.id)))}async close(){for(const e of this.subscriptions.values())e.stop();await this.runtime?.close();for(const e of this.transportPlugins)e.close?.()}}function Ut(t,e){return e?{hash:t,key:e}:{hash:t}}var se;(function(t){t[t.Blob=0]="Blob",t[t.File=1]="File",t[t.Dir=2]="Dir",t[t.Fanout=3]="Fanout"})(se||(se={}));function He(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function _a(t){const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}async function it(t){const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=await crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}const sl=16*1024*1024;async function Ub(t,e,n){if(e.byteLength>sl)throw new Error(`Blob route ${n} returned ${e.byteLength} bytes, exceeding the ${sl}-byte limit`);
vendor: 7,859 bytes, line 3
3const r=new Uint8Array(e);if(He(await it(r))!==He(t))throw new Error(`Blob route ${n} returned content with the wrong hash`);return r}const Oh=12,$b=16,Kb=$b,zb=new TextEncoder().encode("hashtree-chk"),Hb=new TextEncoder().encode("encryption-key");async function Dh(t){const e=new ArrayBuffer(t.length);new Uint8Array(e).set(t);const n=await crypto.subtle.importKey("raw",e,{name:"HKDF"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",salt:zb,info:Hb,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function qb(t){return it(t)}async function $t(t){const e=await qb(t),n=await Dh(e),r=new Uint8Array(Oh),i=new ArrayBuffer(t.length);new Uint8Array(i).set(t);const s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,i);return{ciphertext:new Uint8Array(s),key:e}}async function qr(t,e){if(e.length!==32)throw new Error("CHK key must be 32 bytes");if(t.length<Kb)throw new Error("CHK encrypted data too short");const n=await Dh(e),r=new Uint8Array(Oh),i=new ArrayBuffer(t.length);new Uint8Array(i).set(t);const s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},n,i);return new Uint8Array(s)}function Wb(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function jb(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if((o&4294967168)===0){e[i++]=o;continue}else if((o&4294965248)===0)e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const c=t.charCodeAt(s);(c&64512)===56320&&(++s,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128):(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128)}e[i++]=o&63|128}}const Vb=new TextEncoder,Gb=50;function Yb(t,e,n){Vb.encodeInto(t,e.subarray(n))}function Zb(t,e,n){t.length>Gb?Yb(t,e,n):jb(t,e,n)}const Xb=4096;function Nh(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const c=t[r++];if((c&128)===0)s.push(c);else if((c&224)===192){const u=t[r++]&63;s.push((c&31)<<6|u)}else if((c&240)===224){const u=t[r++]&63,f=t[r++]&63;s.push((c&31)<<12|u<<6|f)}else if((c&248)===240){const u=t[r++]&63,f=t[r++]&63,p=t[r++]&63;let d=(c&7)<<18|u<<12|f<<6|p;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(c);s.length>=Xb&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Jb=new TextDecoder,Qb=200;function eE(t,e,n){const r=t.subarray(e,e+n);return Jb.decode(r)}function tE(t,e,n){return n>Qb?eE(t,e,n):Nh(t,e,n)}class is{type;data;constructor(e,n){this.type=e,this.data=n}}class Mt extends Error{constructor(e){super(e);const n=Object.create(Mt.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Mt.name})}}const fi=4294967295;function nE(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Ph(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Fh(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function rE(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const iE=-1,sE=4294967296-1,oE=17179869184-1;function aE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=oE)if(e===0&&t<=sE){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Ph(r,4,t),n}}function cE(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function uE(t){if(t instanceof Date){const e=cE(t);return aE(e)}else return null}function lE(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=Fh(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Mt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function fE(t){const e=lE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const hE={type:iE,encode:uE,decode:fE};class Vs{static defaultCodec=new Vs;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(hE)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new is(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new is(o,s)}}}return e instanceof is?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new is(n,e)}}function dE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ka(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):dE(t)?new Uint8Array(t):Uint8Array.from(t)}const pE=100,yE=2048;class Oc{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Vs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??pE,this.initialBufferSize=e?.initialBufferSize??yE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Oc({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>
vendor: 12,309 bytes, line 3
3=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=Wb(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Zb(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=ka(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),nE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ph(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function gE(t,e){return new Oc(e).encodeSharedRef(t)}function Xo(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const mE=16,wE=16;class vE{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=mE,n=wE){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let c=0;c<r;c++)if(o[c]!==e[n+c])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=Nh(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Sa="array",gi="map_key",Uh="map_value",bE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Mt("The type of key must be string or number but "+typeof t)};class EE{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Sa,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=gi,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Sa){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===gi||e.type===Uh){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const hi=-1,Dc=new DataView(new ArrayBuffer(0)),xE=new Uint8Array(Dc.buffer);try{Dc.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const ol=new RangeError("Insufficient data"),_E=new vE;class Nc{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Dc;bytes=xE;headByte=hi;stack=new EE;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Vs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??fi,this.maxBinLength=e?.maxBinLength??fi,this.maxArrayLength=e?.maxArrayLength??fi,this.maxMapLength=e?.maxMapLength??fi,this.maxExtLength=e?.maxExtLength??fi,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:_E,this.mapKeyConverter=e?.mapKeyConverter??bE}clone(){return new Nc({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=hi,this.stack.reset()}setBuffer(e){const n=ka(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===hi&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ka(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Xo(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new Mt(`Unrecognized type byte: ${Xo(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Sa)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===gi){if(n==="__proto__")throw new Mt("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Uh;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=gi;continue e}}return n}}readHeadByte(){return this.headByte===hi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=hi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();
3default:{if(e<160)return e-144;throw new Mt(`Unrecognized array type byte: ${Xo(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Mt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Mt(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new Mt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw ol;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=tE(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===gi:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Mt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw ol;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new Mt(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=rE(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Fh(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function kE(t,e){return new Nc(e).decode(t)}const al=new TextEncoder;function Gs(t,e){const n=al.encode(t),r=al.encode(e),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){const o=n[s]-r[s];if(o!==0)return o}return n.length<r.length?-1:n.length>r.length?1:0}const SE=-(1n<<63n),AE=(1n<<64n)-1n;function Aa(t){if(/[\uD800-\uDFFF]/u.test(t))throw new Error("Invalid Unicode string")}function $h(t){if(typeof t=="number"){if(!Number.isFinite(t))throw new Error("Metadata numbers must be finite");if(!Number.isInteger(t)||t<-9223372036854776e3||t>=2**64)return t;if(t>=-2147483648&&t<=4294967295)return t===0?0:t;t=BigInt(t)}if(t<SE||t>AE)throw new Error("Integer outside MessagePack range");return t>=-2147483648n&&t<=4294967295n?Number(t):t}function RE(t){const e=new Set;function n(r,i){if(i>100)throw new Error("Metadata nesting limit exceeded");if(r===null||typeof r=="boolean")return r;if(typeof r=="number"||typeof r=="bigint")return $h(r);if(typeof r=="string")return Aa(r),r;if(typeof r!="object")throw new Error("Unsupported metadata value");if(e.has(r))throw new Error("Cyclic metadata");e.add(r);try{if(Array.isArray(r))return Array.from(r,u=>n(u,i+1));const s=Object.getPrototypeOf(r);if(s!==Object.prototype&&s!==null)throw new Error("Metadata must use plain maps");if(Object.getOwnPropertySymbols(r).length)throw new Error("Metadata keys must be strings");const o=Object.keys(r).sort(Gs),c=Object.create(null);for(const u of o){if(Aa(u),u==="__proto__")throw new Error("Unsupported metadata key: __proto__");c[u]=n(r[u],i+1)}return new Proxy(c,{ownKeys:()=>o})}finally{e.delete(r)}}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("Metadata must be a map");return n(t,0)}function Ra(t){if(typeof t=="bigint")return t>=BigInt(Number.MIN_SAFE_INTEGER)&&t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):t;if(Array.isArray(t))return t.map(Ra);if(t!==null&&typeof t=="object"&&!(t instanceof Uint8Array))for(const e of Object.keys(t)){const n=t;n[e]=Ra(n[e])}return t}function CE(t){return t.type!==se.Dir?t.links:[...t.links].sort((e,n)=>Gs(e.name??"",n.name??""))}function cl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function TE(t){return t===se.File||t===se.Dir||t===se.Fanout}function IE(t){return t===se.Blob||t===se.File||t===se.Dir||t===se.Fanout}function BE(t){const n={l:CE(t).map(r=>{if(!Number.isSafeInteger(r.size)||r.size<0)throw new Error("Link size must be an exact nonnegative safe integer");r.name!==void 0&&Aa(r.name);const i={h:r.hash,k:r.key,m:r.meta!==void 0?RE(r.meta):void 0,n:r.name,s:$h(r.size),t:r.type};return i.k===void 0&&delete i.k,i.m===void 0&&delete i.m,i.n===void 0&&delete i.n,i}),t:t.type};return gE(n,{useBigInt64:!0})}function ct(t){let e;try{e=Ra(kE(t,{useBigInt64:!0}))}catch{return null}if(!cl(e)||!("t"in e)||!("l"in e))return null;const n=e.t;if(!TE(n))throw new Error(`Invalid node type: ${String(n)}`);const r=e.l;if(!Array.isArray(r))throw new Error("Invalid tree links");return{type:n,links:r.map(s=>{if(!cl(s))throw new Error("Invalid link");const o=s.t??se.Blob;if(!IE(o))throw new Error(`Invalid link type: ${String(o)}`);if(typeof s.s=="bigint")throw new Error("Link size exceeds the supported exact integer range");const c={hash:s.h,size:s.s??0,type:o};return s.n!==void 0&&(c.name=s.n),s.k!==void 0&&(c.key=s.k),s.m!==void 0&&(c.meta=s.m),c})}}function Vn(t){const e=ct(t);if(!e)throw new Error("Data is not a valid tree node");return e}async function fn(t){const e=BE(t),n=await it(e);return{data:e,hash:n}}function LE(t){return ct(t)?.type??se.Blob}const ME=1e3,OE=6e4,DE=4,NE=256*1024,ul=15e3,PE=6e4,FE=12e4,UE=4,$E=5e3,KE=75,zE=.12,ll=new Uint8Array([72,84,66,68,8
36,49,0,0]),HE="application/vnd.hashtree.blob-batch.v1+octet-stream";function qE(t){return new Promise(e=>{setTimeout(e,t)})}function WE(t){const e=t??UE;if(!Number.isSafeInteger(e)||e<1||e>32)throw new Error("maxConcurrentWrites must be an integer between 1 and 32");return e}function jE(){return{requests:0,successes:0,misses:0,failures:0,timeouts:0,srttMs:0,rttvarMs:0}}class VE{servers;signer;logger;onUploadProgress;getTimeoutMs;putTimeoutMs;maxConcurrentWrites;skipExistenceCheck;serverHealth=new Map;readStats=new Map;hashAttempts=new Map;activeWrites=0;writeWaiters=[];constructor(e){this.servers=e.servers.map(n=>typeof n=="string"?{url:n,write:!1}:n),this.signer=e.signer,this.logger=e.logger,this.onUploadProgress=e.onUploadProgress,this.getTimeoutMs=e.getTimeoutMs??PE,this.putTimeoutMs=e.putTimeoutMs??FE,this.maxConcurrentWrites=WE(e.maxConcurrentWrites),this.skipExistenceCheck=e.skipExistenceCheck===!0}getWriteServers(){return this.servers.filter(e=>e.write).map(e=>e.url)}getReadServers(){return this.servers.filter(e=>e.read!==!1)}isServerInBackoff(e){return this.serverBackoffRemainingMs(e)>0}serverBackoffRemainingMs(e,n=Date.now()){const r=this.serverHealth.get(e);if(!r||r.consecutiveErrors===0)return 0;const i=Math.min(ME*Math.pow(2,r.consecutiveErrors-1),OE);return Math.max(0,i-(n-r.lastErrorTime))}recordError(e){const n=this.serverHealth.get(e)||{lastErrorTime:0,consecutiveErrors:0};n.lastErrorTime=Date.now(),n.consecutiveErrors++,this.serverHealth.set(e,n)}recordSuccess(e){this.serverHealth.delete(e)}readStatsFor(e){const n=this.readStats.get(e);if(n)return n;const r=jE();return this.readStats.set(e,r),r}recordReadRequest(e){this.readStatsFor(e).requests+=1}recordReadMiss(e){this.readStatsFor(e).misses+=1}recordReadSuccess(e,n){const r=this.readStatsFor(e),i=Date.now();r.successes+=1,r.lastSuccessMs=i,r.srttMs===0?(r.srttMs=n,r.rttvarMs=n/2):(r.rttvarMs=.75*r.rttvarMs+.25*Math.abs(r.srttMs-n),r.srttMs=.875*r.srttMs+.125*n),this.recordSuccess(e)}recordReadFailure(e){const n=this.readStatsFor(e);n.failures+=1,n.lastFailureMs=Date.now(),this.recordError(e)}recordReadTimeout(e){const n=this.readStatsFor(e);n.timeouts+=1,n.lastFailureMs=Date.now(),this.recordError(e)}readReliabilityScore(e){return(e.successes+1)/(e.requests+2)}readLatencyScore(e){return e.srttMs<=0?.5:Math.min(1,500/(e.srttMs+50))}hasReadHistory(e){return e.requests>0||e.successes>0||e.misses>0||e.failures>0||e.timeouts>0}defaultReadPreference(e){let n=e.write?0:.08;try{const r=new URL(e.url).hostname.toLowerCase();(r.includes("cdn")||r.includes("cache")||r.includes("edge"))&&(n+=.06),(r.includes("upload")||r.includes("origin"))&&(n-=.04)}catch{}return n}scoreReadServer(e,n){if(this.isServerInBackoff(e.url))return Number.NEGATIVE_INFINITY;const r=this.readStatsFor(e.url),i=r.requests>0?r.misses/r.requests*.2:0,s=r.requests>0?(r.failures+r.timeouts)/r.requests*.35:0,o=r.lastSuccessMs&&n-r.lastSuccessMs<6e4?.1:0;return this.defaultReadPreference(e)+.55*this.readReliabilityScore(r)+.3*this.readLatencyScore(r)+o-i-s}orderedReadServers(e){const n=Date.now();return[...e].sort((r,i)=>{const s=this.scoreReadServer(i,n)-this.scoreReadServer(r,n);if(Math.abs(s)>Number.EPSILON)return s;const o=this.defaultReadPreference(r),c=this.defaultReadPreference(i);return o!==c?c-o:r.url.localeCompare(i.url)})}shouldProbeMultipleReadServers(e){if(e.length<=1)return!1;const[n,r]=e;if(!n||!r)return!1;const i=this.readStatsFor(n.url),s=this.readStatsFor(r.url);if(!this.hasReadHistory(i)||!this.hasReadHistory(s))return!1;const o=Date.now();return this.scoreReadServer(n,o)-this.scoreReadServer(r,o)<zE}isTimeoutError(e){return e instanceof Error?e.name==="AbortError"||e.name==="TimeoutError"||/timed?\s*out/i.test(e.message):!1}async getFromBatchEndpoint(e,n,r){const i=await fetch(`${e.url}/blob/batch`,{method:"POST",headers:{Accept:HE,"Content-Type":"application/json"},body:JSON.stringify({hashes:[n]}),signal:r});if(!i.ok){if(i.status===404)return null;throw new Error(`Blossom batch endpoint ${e.url} returned HTTP ${i.status}`)}const s=new Uint8Array(await i.arrayBuffer());if(s.length<12)throw new Error(`Blossom batch endpoint ${e.url} returned a short response`);for(let f=0;f<ll.length;f+=1)if(s[f]!==ll[f])throw new Error(`Blossom batch endpoint ${e.url}
3 returned invalid framing`);const o=new DataView(s.buffer,s.byteOffset,s.byteLength),c=o.getUint32(8,!1);let u=12;for(let f=0;f<c;f+=1){if(s.length-u<40)throw new Error(`Blossom batch endpoint ${e.url} returned a truncated entry`);const p=s.slice(u,u+32);u+=32;const d=Number(o.getBigUint64(u,!1));if(u+=8,!Number.isSafeInteger(d)||s.length-u<d)throw new Error(`Blossom batch endpoint ${e.url} returned an invalid entry length`);const g=s.slice(u,u+d);if(u+=d,He(p)!==n)continue;const w=await it(g);if(He(w)===n)return g;throw new Error(`Blossom batch endpoint ${e.url} returned data with a hash mismatch`)}return null}async getRawBlobResponse(e,n,r){const i=`${e.url}/${n}.bin`,s=await fetch(i,{signal:r});return s.status!==404?s:await fetch(i,{signal:r,cache:"reload"})}createInFlightReadRequest(e,n){const r=Date.now();this.recordReadRequest(e.url);const i=AbortSignal.timeout(this.getTimeoutMs);let s=!1,o;const c=async()=>{s=!0;try{return await this.getFromBatchEndpoint(e,n,i)}catch(u){return o=u instanceof Error?u:new Error(String(u)),null}};return{server:e,settled:!1,promise:(e.preferBatchReads?c():Promise.resolve(null)).then(async u=>u?(this.log({operation:"get",server:e.url,hash:n,success:!0,bytes:u.length}),this.recordReadSuccess(e.url,Math.max(1,Date.now()-r)),{serverUrl:e.url,data:u}):this.getRawBlobResponse(e,n,i)).then(async u=>{if("serverUrl"in u)return u;const f=u,p=Math.max(1,Date.now()-r);if(f.ok){const g=new Uint8Array(await f.arrayBuffer()),w=await it(g);return He(w)===n?(this.log({operation:"get",server:e.url,hash:n,success:!0,bytes:g.length}),this.recordReadSuccess(e.url,p),{serverUrl:e.url,data:g}):(this.log({operation:"get",server:e.url,hash:n,success:!1,error:"Hash mismatch"}),this.recordReadFailure(e.url),{serverUrl:e.url,data:null,error:new Error(`Blossom server ${e.url} returned data with a hash mismatch`)})}const d=s?null:await c();return d?(this.log({operation:"get",server:e.url,hash:n,success:!0,bytes:d.length}),this.recordReadSuccess(e.url,Math.max(1,Date.now()-r)),{serverUrl:e.url,data:d}):f.status===404?(this.log({operation:"get",server:e.url,hash:n,success:!1,error:"404"}),this.recordReadMiss(e.url),{serverUrl:e.url,data:null,error:o}):(this.log({operation:"get",server:e.url,hash:n,success:!1,error:`${f.status}`}),this.recordReadFailure(e.url),{serverUrl:e.url,data:null,error:new Error(`Blossom server ${e.url} returned HTTP ${f.status}`)})}).catch(async u=>{const f=s?null:await c();return f?(this.log({operation:"get",server:e.url,hash:n,success:!0,bytes:f.length}),this.recordReadSuccess(e.url,Math.max(1,Date.now()-r)),{serverUrl:e.url,data:f}):(this.log({operation:"get",server:e.url,hash:n,success:!1,error:u instanceof Error?u.message:"Network error"}),this.isTimeoutError(u)?this.recordReadTimeout(e.url):this.recordReadFailure(e.url),{serverUrl:e.url,data:null,error:u instanceof Error?u:new Error(String(u))})})}}hasPendingReadRequests(e){return e.some(n=>!n.settled)}async waitForNextReadResult(e,n){const r=e.filter(o=>!o.settled);if(r.length===0)return null;const i=r.map(o=>o.promise.then(c=>({request:o,...c}))),s=n===void 0?await Promise.race(i):await Promise.race([new Promise(o=>{setTimeout(()=>o(null),n)}),...i]);return s?(s.request.settled=!0,s):null}shouldGiveUpOnHash(e){const n=this.hashAttempts.get(e);return n?n.attempts>=DE:!1}recordHashFailure(e){const n=this.hashAttempts.get(e)||{attempts:0,lastAttempt:0};n.attempts++,n.lastAttempt=Date.now(),this.hashAttempts.set(e,n)}clearHashFailure(e){this.hashAttempts.delete(e)}log(e){this.logger?.({...e,timestamp:Date.now()})}async createAuthHeader(e,n,r){if(!this.signer)throw new Error("Signer required for authenticated requests");const i=He(n),s=Math.floor(Date.now()/1e3)+300,o=[["t",e.toLowerCase()],["x",i],["expiration",s.toString()]],c=await this.signer({kind:24242,created_at:Math.floor(Date.now()/1e3),content:`${e} ${i}`,tags:o});return`Nostr ${btoa(JSON.stringify(c))}`}async put(e,n,r){await this.acquireWriteSlot();try{return await this.doPut(e,n,r)}finally{this.releaseWriteSlot()}}async acquireWriteSlot(){if(this.activeWrites<this.maxConcurrentWrites){this.activeWrites+=1;return}await new Promise(e=>this.writeWaiters.push(e))}releaseWriteSlot(){const e=this.writeWaiters.shift();if(e){e();return}this.activeWrites-=1}async doPut(e,n,r){const i=He(e);if(this.shouldGiveUpOnHash(i))return!1;const s=await it(n);if(He(s)!==i)throw new Error("Hash does not match data");const o=this.servers.filter(d=>d.write);if(o.length===0)throw new Error("No write-enabled server configured");let c=o.filter(d=>!this.isServerInBackoff(d.url));if(c.length===0){const d=Date.now(),g=Math.min(...o.map(w=>this.serverBackoffRemainingMs(w.url,d)).filter(w=>w>0));Number.isFinite(g)&&g>
30&&(await qE(Math.min(g,$E)),c=o.filter(w=>!this.isServerInBackoff(w.url)))}if(c.length===0)throw this.recordHashFailure(i),new Error("All write servers are in backoff");if(!this.skipExistenceCheck&&n.length>=NE&&await this.hasOnWriteServers(e)){if(this.log({operation:"put",server:"all",hash:i,success:!0,bytes:0}),this.onUploadProgress)for(const g of c)this.onUploadProgress(g.url,"skipped");return!1}const u=await this.createAuthHeader("upload",e,r),f=await Promise.allSettled(c.map(async d=>{try{const g=await fetch(`${d.url}/upload`,{method:"PUT",signal:AbortSignal.timeout(this.putTimeoutMs),headers:{Authorization:u,"Content-Type":r||"application/octet-stream","X-SHA-256":i},body:new Blob([n])});if(!g.ok&&g.status!==409){const x=await g.text(),A=`${g.status} ${x}`;throw this.log({operation:"put",server:d.url,hash:i,success:!1,error:A}),this.recordError(d.url),this.onUploadProgress?.(d.url,"failed"),new Error(`${d.url}: ${A}`)}const w=g.status===200||g.status===409;if(g.status!==409)try{const x=await g.json();if(x.sha256&&x.sha256!==i){const A=`Hash mismatch: sent ${i}, server got ${x.sha256}`;throw this.log({operation:"put",server:d.url,hash:i,success:!1,error:A}),this.recordError(d.url),this.onUploadProgress?.(d.url,"failed"),new Error(`${d.url}: ${A}`)}}catch(x){if(!(x instanceof SyntaxError))throw x}return this.log({operation:"put",server:d.url,hash:i,success:!0,bytes:n.length}),this.recordSuccess(d.url),this.onUploadProgress?.(d.url,w?"skipped":"uploaded"),!w}catch(g){const w=g instanceof Error?g.message:String(g);throw w.includes(d.url)||(this.log({operation:"put",server:d.url,hash:i,success:!1,error:w}),this.recordError(d.url),this.onUploadProgress?.(d.url,"failed")),g}})),p=f.filter(d=>d.status==="fulfilled");if(p.length===0){this.recordHashFailure(i);const d=f.find(g=>g.status==="rejected");throw new Error(`Blossom upload failed: ${d.reason}`)}return this.clearHashFailure(i),p.some(d=>d.value)}async get(e){return await this.getFromServers(e,this.getReadServers().map(n=>n.url))}async getFromServers(e,n){const r=new Set(n.map(d=>`${d}`.trim()).filter(Boolean));if(r.size===0)return null;const i=He(e),s=this.getReadServers().filter(d=>!(!r.has(d.url)||this.isServerInBackoff(d.url)));if(s.length===0)return null;const o=this.orderedReadServers(s),c=[],u=[];let f=0;const p=d=>{for(let g=0;g<d&&f<o.length;g+=1){const w=o[f];f+=1,c.push(this.createInFlightReadRequest(w,i))}};for(p(this.shouldProbeMultipleReadServers(o)?Math.min(2,o.length):1);this.hasPendingReadRequests(c)||f<o.length;){const d=await this.waitForNextReadResult(c,f<o.length?KE:void 0);if(d?.data)return d.data;if(d?.error&&u.push(d.error),d===null&&f<o.length){p(1);continue}f<o.length&&!this.hasPendingReadRequests(c)&&p(1)}if(u.length>0)throw new AggregateError(u,`Blossom availability is uncertain: ${u[0].message}`);return null}async has(e){const n=He(e);for(const r of this.servers)if(r.read!==!1&&!this.isServerInBackoff(r.url))try{const i=await fetch(`${r.url}/${n}.bin`,{method:"HEAD",signal:AbortSignal.timeout(ul)});if(i.ok)return this.log({operation:"has",server:r.url,hash:n,success:!0}),this.recordSuccess(r.url),!0;i.status!==404&&i.status>=500&&this.recordError(r.url)}catch(i){this.log({operation:"has",server:r.url,hash:n,success:!1,error:i instanceof Error?i.message:"Network error"}),this.recordError(r.url);continue}return!1}async hasOnWriteServers(e){const n=He(e);for(const r of this.servers)if(r.write&&!this.isServerInBackoff(r.url))try{const i=await fetch(`${r.url}/${n}.bin`,{method:"HEAD",signal:AbortSignal.timeout(ul)});if(i.ok)return this.log({operation:"has",server:r.url,hash:n,success:!0}),this.recordSuccess(r.url),!0;i.status!==404&&i.status>=500&&this.recordError(r.url)}catch(i){this.log({operation:"has",server:r.url,hash:n,success:!1,error:i instanceof Error?i.message:"Network error"}),this.recordError(r.url);continue}return!1}async delete(e){const n=this.servers.find(o=>o.write);if(!n)throw new Error("No write-enabled server configured");const r=await this.createAuthHeader("delete",e),i=He(e),s=await fetch(`${n.url}/${i}.bin`,{method:"DELETE",headers:{Authorization:r}});if(!s.ok){if(s.status===404)return!1;const o=await s.text();throw new Error(`Blossom delete failed: ${s.status} ${o}`)}return!0}}class GE{primary;fallbacks;timeout;inflightReads=new Map;constructor(e){this.primary=e.primary,this.fallbacks=e.fallbacks,this.timeout=e.timeout??5e3}async put(e,n){const r=await this.primary.put(e,n);for(const i of this.fallbacks)i.put&&i.put(e,n).catch(()=>{});return r}async get(e){let n=await this.primary.get(e);if(n)return n;if(this.fallbacks.length===0)return null;const r=He(e);let i=this.inflightReads.get(r);
3return i||(i=this.loadFromFallbacks(e).finally(()=>{this.inflightReads.get(r)===i&&this.inflightReads.delete(r)}),this.inflightReads.set(r,i)),n=await i,n}async has(e){return this.primary.has(e)}async delete(e){return this.primary.delete(e)}addFallback(e){this.fallbacks.push(e)}removeFallback(e){const n=this.fallbacks.indexOf(e);n>=0&&this.fallbacks.splice(n,1)}async loadFromFallbacks(e){const n=this.fallbacks.map(i=>{const s=i.get(e).then(async c=>{if(!c)return null;const u=await Ub(e,c,"fallback");return this.primary.put(e,u).catch(()=>{}),u}).catch(()=>null),o=new Promise(c=>setTimeout(()=>c(null),this.timeout));return Promise.race([s,o])});return await new Promise(i=>{let s=!1,o=n.length;for(const c of n)c.then(u=>{if(!s){if(u){s=!0,i(u);return}o-=1,o===0&&i(null)}}).catch(()=>{s||(o-=1,o===0&&i(null))})})}}function fl(t){return()=>t}class YE{store;chunker;unencrypted;buffer;bufferOffset=0;chunks=[];totalSize=0;constructor(e,n,r,i){if("store"in e&&typeof e=="object"&&!("get"in e)){const s=e;this.store=s.store,this.chunker=s.chunker??fl(s.chunkSize??2*1024*1024),this.unencrypted=s.unencrypted??!1}else this.store=e,this.chunker=fl(n),this.unencrypted=i??!1;this.buffer=new Uint8Array(this.chunker(0))}currentChunkSize(){return this.chunker(this.chunks.length)}async append(e){let n=0;for(;n<e.length;){const r=this.currentChunkSize();if(this.buffer.length!==r){const o=new Uint8Array(r);this.bufferOffset>0&&o.set(this.buffer.subarray(0,this.bufferOffset)),this.buffer=o}const i=r-this.bufferOffset,s=Math.min(i,e.length-n);this.buffer.set(e.subarray(n,n+s),this.bufferOffset),this.bufferOffset+=s,n+=s,this.bufferOffset===r&&await this.flushChunk()}this.totalSize+=e.length}async flushChunk(){if(this.bufferOffset===0)return;const e=this.bufferOffset,n=this.buffer.slice(0,e);if(this.unencrypted){const r=await it(n);await this.store.put(r,n),this.chunks.push({hash:r,size:e,type:se.Blob})}else{const{ciphertext:r,key:i}=await $t(n),s=await it(r);await this.store.put(s,r),this.chunks.push({hash:s,size:e,key:i,type:se.Blob})}this.bufferOffset=0}async currentRoot(){if(this.chunks.length===0&&this.bufferOffset===0)return null;const e=[...this.chunks];if(this.bufferOffset>0){const n=this.buffer.slice(0,this.bufferOffset);if(this.unencrypted){const r=await it(n);await this.store.put(r,n),e.push({hash:r,size:n.length,type:se.Blob})}else{const r=n.length,{ciphertext:i,key:s}=await $t(n),o=await it(i);await this.store.put(o,i),e.push({hash:o,size:r,key:s,type:se.Blob})}}return this.buildTreeFromChunks(e,this.totalSize)}async finalize(){if(await this.flushChunk(),this.chunks.length===0)if(this.unencrypted){const n=new Uint8Array(0),r=await it(n);return await this.store.put(r,n),{hash:r,size:0}}else{const{ciphertext:n,key:r}=await $t(new Uint8Array(0)),i=await it(n);return await this.store.put(i,n),{hash:i,size:0,key:r}}const e=await this.buildTreeFromChunks(this.chunks,this.totalSize);return{hash:e.hash,size:this.totalSize,key:e.key}}async buildTreeFromChunks(e,n){if(e.length===1)return Ut(e[0].hash,e[0].key);const r={type:se.File,links:e},{data:i,hash:s}=await fn(r);if(this.unencrypted)return await this.store.put(s,i),{hash:s};{const{ciphertext:o,key:c}=await $t(i),u=await it(o);return await this.store.put(u,o),Ut(u,c)}}get stats(){return{chunks:this.chunks.length,buffered:this.bufferOffset,totalSize:this.totalSize}}clear(){this.chunks=[],this.buffer=new Uint8Array(0),this.bufferOffset=0,this.totalSize=0}}const ZE=174;async function Ca(t,e){const n=await it(e);return await t.put(n,e),n}async function XE(t,e){const{store:n,chunkSize:r}=t,i=e.length;if(e.length<=r)return{hash:await Ca(n,e),size:i};const s=[];let o=0;for(;o<e.length;){const u=Math.min(o+r,e.length),f=e.subarray(o,u),p=await Ca(n,f);s.push({hash:p,size:f.length,type:se.Blob}),o=u}return{hash:await t1(t,s,i),size:i}}async function Ri(t,e){const r=[...e].sort((i,s)=>Gs(i.name,s.name)).map(i=>({hash:i.cid.hash,key:i.cid.key,name:i.name,size:i.size??0,type:i.type??se.Blob,meta:i.meta}));return r.length<=zh(t)?JE(t,r):e1(t,r)}async function JE(t,e){const n={type:se.Dir,links:e},{data:r,hash:i}=await fn(n);return await t.store.put(i,r),i}function QE(t,e,n){return{count:t,first:e,last:n}}async function e1(t,e){const n=e.map(r=>{const i=r.name??He(r.hash);return{link:r,count:1,first:i,last:i}});return Kh(t,n,se.Dir)}async function Kh(t,e,n){const r=zh(t),i=[];for(let s=0;s<e.length;s+=r){const o=e.slice(s,s+r),c=o[0],u=o[o.length-1],f=o.reduce((w,x)=>w+x.count,0),p=o.map(({link:w})=>w),d=p.reduce((w,x)=>w+(x.size??0),0),g=await hl(t,n,p);i.push({link:{hash:g,size:d,type:n,meta:QE(f,c.first,u.last)},count:f,first:c.first,last:u.last})}return i.length<=r?hl(t,se.Fanout,i.map(({link:s})=>s)):Kh(t,i,se.Fanout)}async function hl(t,e,n){const r={type:e,links:n},{data:i,hash:s}=await fn(r);return await t.store.put(s,i),s}async function t1(t,e,n){const{store:r}=t;if(e.length===1&&e[0].size===n)return e[0].hash;const i={type:se.File,links:e},{data:s,hash:o}=await fn(i);return await r.put(o,s),o}function zh(t){const e=t.maxLinks??ZE;if(!Number.isInteger(e)||e<1)throw new Error(`Invalid maxLinks: ${t.maxLinks}`);return e}const dl=500;async function Jo(t,e,n){if(!n)return t.get(e);if(n.aborted)throw n.reason??new DOMException("Aborted","AbortError");let r;try{return await new Promise((i,s)=>{r=()=>s(n.reason??new DOMException("Aborted","AbortError")),n.addEventListener("abort",r,{once:!0}),t.get(e).then(i,s)})}finally{r&&n.removeEventListener("abort",r)}}async function Hh(t,e,n){const r=await Jo(t,e,n);if(r)return r;if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError");return new Promise((i,s)=>{let o=!1,c,u;const f=()=>{o=!0,c&&c(),u!==void 0&&clearTimeout(u),n&&n.removeEventListener("abort",p)},p=()=>
3{o||(f(),s(n?.reason??new DOMException("Aborted","AbortError")))};if(n&&n.addEventListener("abort",p),typeof t.watch=="function"){try{c=t.watch(e,d=>{o||(f(),i(d))})}catch(d){f(),s(d);return}if(o){c();return}Jo(t,e).then(d=>{o||!d||(f(),i(d))},d=>{o||(f(),s(d))})}else{const d=async()=>{if(!o){try{const g=await Jo(t,e);if(o)return;if(g){f(),i(g);return}}catch{}o||(u=setTimeout(d,dl))}};u=setTimeout(d,dl)}})}function qh(t){if(t!==void 0){if(!Number.isFinite(t)||t<0)throw new Error(`Invalid maxBytes: ${t}`);return Math.floor(t)}}function jn(t,e){if(t!==void 0&&e>t)throw new Error(`Content size ${e} exceeds maxBytes ${t}`)}function Ei(t){return t?.type===se.Dir||t?.type===se.Fanout}function Wh(t){const e="_chunk_";if(!t.startsWith(e))return null;const n=t.slice(e.length);if(n.length===0||!/^[0-9]+$/.test(n))return null;const r=Number(n);return Number.isSafeInteger(r)?r:null}function n1(t){return t.type===se.Dir&&t.links.length>0&&t.links.every(e=>e.type===se.Dir&&e.name!==void 0&&Wh(e.name)!==null)}function jh(t,e){return t.type===se.Fanout?e.type===se.Dir||e.type===se.Fanout:n1(t)&&e.type===se.Dir&&e.name!==void 0&&Wh(e.name)!==null}async function r1(t,e){return t.get(e)}async function i1(t,e){const n=await t.get(e);return n?ct(n):null}async function s1(t,e){if(!e)return se.Blob;const n=await t.get(e);return n?LE(n):se.Blob}async function o1(t,e){if(!e)return!1;const n=await t.get(e);if(!n)return!1;const r=ct(n);return Ei(r)}async function a1(t,e,n={}){if(!e)return null;const r=qh(n.maxBytes),i=await t.get(e);if(!i)return null;const s=ct(i);if(!s)return jn(r,i.length),i;const o=s.links.reduce((c,u)=>c+(u.size??0),0);return jn(r,o),Pc(t,s,{maxBytes:r,bytesRead:0})}async function Pc(t,e,n={bytesRead:0}){const r=[];for(const c of e.links){jn(n.maxBytes,n.bytesRead+(c.size??0));const u=await t.get(c.hash);if(!u)throw new Error(`Missing chunk: ${He(c.hash)}`);if(c.type!==se.Blob){const f=Vn(u);r.push(await Pc(t,f,n))}else jn(n.maxBytes,n.bytesRead+u.length),n.bytesRead+=u.length,r.push(u)}const i=r.reduce((c,u)=>c+u.length,0),s=new Uint8Array(i);let o=0;for(const c of r)s.set(c,o),o+=c.length;return s}async function*c1(t,e,n={}){const{offset:r=0,prefetch:i=1}=n,s=await t.get(e);if(!s)return;const o=ct(s);if(!o){if(r>=s.length)return;yield r>0?s.slice(r):s;return}yield*Vh(t,o,r,i)}async function*Vh(t,e,n,r=1){let i=0,s=0;for(let p=0;p<e.links.length;p++){const d=e.links[p].size??0;if(d>0&&i+d<=n)i+=d,s=p+1;else break}const o=e.links.slice(s);if(o.length===0)return;const c=[];let u=i;for(let p=0;p<Math.min(r,o.length);p++){const d=o[p];c.push({promise:t.get(d.hash),link:d,position:u}),u+=d.size??0}let f=r;for(const p of o){const d=c.shift();if(!d)throw new Error("Prefetch queue empty unexpectedly");const g=await d.promise;if(!g)throw new Error(`Missing chunk: ${He(p.hash)}`);if(f<o.length){const w=o[f];c.push({promise:t.get(w.hash),link:w,position:u}),u+=w.size??0,f++}if(p.type!==se.Blob){const w=Vn(g),x=Math.max(0,n-d.position);yield*Vh(t,w,x,r),i=d.position+(p.size??0)}else{const w=d.position,x=d.position+g.length;if(i=x,x<=n)continue;if(w>=n)yield g;else{const A=n-w;yield g.slice(A)}}}}async function u1(t,e,n,r){const i=await t.get(e);if(!i)return null;const s=ct(i);if(!s){if(n>=i.length)return new Uint8Array(0);const o=r!==void 0?Math.min(r,i.length):i.length;return i.slice(n,o)}return Gh(t,s,n,r)}async function Gh(t,e,n,r){const i=[];let s=0,o=0;const c=r!==void 0?r-n:1/0;for(const d of e.links){if(o>=c)break;const g=d.size??0;if(g>0&&s+g<=n){s+=g;continue}const w=await t.get(d.hash);if(!w)throw new Error(`Missing chunk: ${He(d.hash)}`);if(d.type!==se.Blob){const x=Vn(w),A=Math.max(0,n-s),I=r!==void 0?r-s:void 0,T=await Gh(t,x,A,I);if(T.length>0){const te=Math.min(T.length,c-o);i.push(T.slice(0,te)),o+=te}s+=g}else{const x=s,A=s+w.length;if(s=A,A<=n)continue;const I=Math.max(0,n-x),T=r!==void 0?Math.min(w.length,r-x):w.length;if(I<T){const te=Math.min(T-I,c-o);i.push(w.slice(I,I+te)),o+=te}}}const u=i.reduce((d,g)=>d+g.length,0),f=new Uint8Array(u);let p=0;for(const d of i)f.set(d,p),p+=d.length;return f}async function Yh(t,e,n){const r=await Hh(t,e,n),i=ct(r);if(!i)return null;if(Ei(i))return i;const s=await Pc(t,i),o=ct(s);return Ei(o)?o:null}async function _n(t,e,n){const r=await Yh(t,e,n);if(!r)return[];const i=[];for(const s of r.links){if(jh(r,s)){i.push(...await _n(t,s.hash,n));continue}s.name!==void 0&&i.push({name:s.name,cid:Ut(s.hash,s.key),size:s.size,type:s.type,meta:s.meta})}return i}async function l1(t,e,n,r){const i=n.split("/").filter(o=>o.length>0);let s=e;for(const o of i){const u=(await _n(t,s,r)).find(f=>f.name===o);if(!u)return null;s=u.cid.hash}return s}async function f1(t,e){const n=await t.get(e);if(!n)return 0;const r=ct(n);if(!r)return n.length;let i=0;for(const s of r.links)i+=s.size;return i}async function*Zh(t,e,n=""){const r=await t.get(e);if(!r)return;if(await Yh(t,e)){const c=await _n(t,e),u=c.reduce((f,p)=>f+p.size,0);yield{path:n,hash:e,type:se.Dir,size:u};for(const f of c){const p=n?`${n}/${f.name}
3`:f.name;yield*Zh(t,f.cid.hash,p)}return}const s=ct(r);if(!s){yield{path:n,hash:e,type:se.Blob,size:r.length};return}const o=s.links.reduce((c,u)=>c+u.size,0);yield{path:n,hash:e,type:se.File,size:o}}async function Xh(t,e,n,r,i,s,o=se.Blob,c){const{store:u}=t,f=await Ci(u,e,n);if(!f)throw new Error(`Path not found: ${n.join("/")}`);const d=(await _n(u,f)).filter(w=>w.name!==r).map(w=>({name:w.name,cid:w.cid,size:w.size,type:w.type,meta:w.meta}));d.push({name:r,cid:i,size:s,type:o,meta:c});const g=await Ri(t,d);return Fc(t,e,n,g)}async function Jh(t,e,n,r){const{store:i}=t,s=await Ci(i,e,n);if(!s)throw new Error(`Path not found: ${n.join("/")}`);const c=(await _n(i,s)).filter(f=>f.name!==r).map(f=>({name:f.name,cid:f.cid,size:f.size,type:f.type,meta:f.meta})),u=await Ri(t,c);return Fc(t,e,n,u)}async function h1(t,e,n,r,i){if(r===i)return e;const{store:s}=t,o=await Ci(s,e,n);if(!o)throw new Error(`Path not found: ${n.join("/")}`);const c=await _n(s,o),u=c.find(d=>d.name===r);if(!u)throw new Error(`Entry not found: ${r}`);const f=c.filter(d=>d.name!==r).map(d=>({name:d.name,cid:d.cid,size:d.size,type:d.type,meta:d.meta}));f.push({name:i,cid:u.cid,size:u.size,type:u.type,meta:u.meta});const p=await Ri(t,f);return Fc(t,e,n,p)}async function d1(t,e,n,r,i){const{store:s}=t,o=await Ci(s,e,n);if(!o)throw new Error(`Source path not found: ${n.join("/")}`);const u=(await _n(s,o)).find(p=>p.name===r);if(!u)throw new Error(`Entry not found: ${r}`);let f=await Jh(t,e,n,r);return f=await Xh(t,f,i,r,u.cid,u.size,u.type),f}async function Ci(t,e,n){return n.length===0?e:l1(t,e,n.join("/"))}async function Fc(t,e,n,r){if(n.length===0)return r;const{store:i}=t;let s=r;const o=[...n];for(;o.length>0;){const c=o.pop(),u=o.length===0?e:await Ci(i,e,o);if(!u)throw new Error(`Parent path not found: ${o.join("/")}`);const p=(await _n(i,u)).map(d=>d.name===c?{name:d.name,cid:Ut(s),size:d.size,type:d.type,meta:d.meta}:{name:d.name,cid:d.cid,size:d.size,type:d.type,meta:d.meta});s=await Ri(t,p)}return s}const p1=174;async function Ys(t,e,n){const r=await t.get(e);return r?Uc(r,n):null}async function y1(t,e,n,r){const i=await Hh(t,e,r);return Uc(i,n)}async function Uc(t,e){const n=ct(t);try{const r=await qr(t,e);return ct(r)||!n?r:t}catch(r){if(n)return t;throw r}}async function g1(t,e){const{store:n,chunkSize:r}=t,i=e.length;if(e.length<=r){const{ciphertext:f,key:p}=await $t(e),d=await it(f);return await n.put(d,f),{hash:d,size:i,key:p}}const s=[];let o=0;for(;o<e.length;){const f=Math.min(o+r,e.length),p=e.subarray(o,f),{ciphertext:d,key:g}=await $t(p),w=await it(d);await n.put(w,d),s.push({hash:w,size:p.length,key:g,type:se.Blob}),o=f}const{hash:c,key:u}=await m1(t,s,i);return{hash:c,size:i,key:u}}async function m1(t,e,n){const{store:r}=t;if(e.length===1&&e[0].key&&n!==void 0&&e[0].size===n)return{hash:e[0].hash,key:e[0].key};const i={type:se.File,links:e},{data:s}=await fn(i),{ciphertext:o,key:c}=await $t(s),u=await it(o);return await r.put(u,o),{hash:u,key:c}}async function w1(t,e,n,r={}){const i=qh(r.maxBytes),s=await Ys(t,e,n);if(!s)return null;const o=ct(s);if(o){const c=o.links.reduce((u,f)=>u+(f.size??0),0);return jn(i,c),$c(t,o,{maxBytes:i,bytesRead:0})}return jn(i,s.length),s}async function v1(t,e,n,r){const i=await y1(t,e,n,r),s=ct(i);if(Ei(s))return s;if(s){const o=await $c(t,s),c=ct(o);if(Ei(c))return c}return null}async function $c(t,e,n={bytesRead:0}){const r=[];for(const c of e.links){jn(n.maxBytes,n.bytesRead+(c.size??0));const u=c.key;if(!u)throw new Error(`Missing decryption key for chunk: ${He(c.hash)}`);const f=await t.get(c.hash);if(!f)throw new Error(`Missing chunk: ${He(c.hash)}`);const p=await qr(f,u);if(c.type!==se.Blob){const d=Vn(p);r.push(await $c(t,d,n))}else jn(n.maxBytes,n.bytesRead+p.length),n.bytesRead+=p.length,r.push(p)}const i=r.reduce((c,u)=>c+u.length,0),s=new Uint8Array(i);let o=0;for(const c of r)s.set(c,o),o+=c.length;return s}async function*b1(t,e,n,r={}){const{offset:i=0,prefetch:s=1}=r,o=await Ys(t,e,n);if(!o)return;const c=ct(o);if(c)yield*Qh(t,c,i,s);else{if(i>=o.length)return;yield i>0?o.slice(i):o}}async function*Qh(t,e,n,r=1){let i=0,s=0;for(let p=0;p<e.links.length;p++){const d=e.links[p].size??0;if(d>0&&i+d<=n)i+=d,s=p+1;else break}const o=e.links.slice(s);if(o.length===0)return;const c=[];let u=i;for(let p=0;p<Math.min(r,o.length);p++){const d=o[p];c.push({promise:t.get(d.hash),link:d,position:u}),u+=d.size??0}let f=r;for(const p of o){const d=p.key;if(!d)throw new Error(`Missing decryption key for chunk: ${He(p.hash)}`);const g=c.shift();if(!g)throw new Error("Prefetch queue empty unexpectedly");const w=await g.promise;if(!w)throw new Error(`Missing chunk: ${He(p.hash)}`);if(f<o.length){const A=o[f];c.push({promise:t.get(A.hash),link:A,position:u}),u+=A.size??0,f++}const x=await qr(w,d);if(p.type!==se.Blob){const A=Vn(x),I=Math.max(0,n-g.position);yield*Qh(t,A,I,r),i=g.position+(p.size??0)}else{const A=g.position,I=g.position+x.length;if(i=I,I<=n)continue;if(A>=n)yield x;else{const T=n-A;yield x.slice(T)}}}}async function E1(t,e,n,r,i){const s=await Ys(t,e,n);if(!s)return null;const o=ct(s);if(!o){if(r>=s.length)return new Uint8Array(0);const c=i!==void 0?Math.min(i,s.length):s.length;return s.slice(r,c)}return ed(t,o,r,i)}async function ed(t,e,n,r){const i=[];let s=0,o=0;const c=r!==void 0?r-n:1/0;for(const d of e.links){if(o>=c)break;const g=d.key;if(!g)throw new Error(`Missing decryption key for chunk: ${He(d.hash)}`);const w=d.size??0;if(w>0&&s+w<=n){s+=w;continue}const x=await t.get(d.hash);if(!x)throw new Error(`Missing chunk: ${He(d.hash)}`);const A=await qr(x,g);if(d.type!==se.Blob){const I=Vn(A),T=Math.max(0,n-s),te=r!==void 0?r-s:void 0,ae=await ed(t,I,T,te);if(ae.length>0){const Re=Math.min(ae.length,c-o);i.push(ae.slice(0,Re)),o+=Re}s+=w}else{const I=s,T=s+A.length;if(s=T,T<=n)continue;const te=Math.max(0,n-I),ae=r!==void 0?Math.min(A.length,r-I):A.length;if(te<ae){const Re=Math.min(ae-te,c-o);i.push(A.slice(te,te+Re)),o+=Re}}}const u=i.reduce((d,g)=>d+g.length,0),f=new Uint8Array(u);let p=0;for(const d of i)f.set(d,p),p+=d.length;return f}async function Wr(t,e){const r=[...e].sort((i,s)=>Gs(i.name,s.name)).map(i=>({hash:i.hash,name:i.name,size:i.size??0,key:i.key,type:i.type??se.Blob,meta:i.meta}));return r.length<=nd(t)?x1(t,r):k1(t,r)}async function x1(t,e){return Ta(t,se.Dir,e)}async function Ta(t,e,n){const r=n.reduce((f,p)=>f+(p.size??0),0),i={type:e,links:n},{data:s}=await fn(i),{ciphertext:o,key:c}=await $t(s),u=await it(o);return await t.store.put(u,o),{hash:u,size:r,key:c}}function _1(t,e,n){return{count:t,first:e,last:n}}async function k1(t,e){const n=e.map(r=>{const i=r.name??He(r.hash);return{link:r,count:1,first:i,last:i}});return td(t,n,se.Dir)}async function td(t,e,n){const r=nd(t),i=[];for(let s=0;s<e.length;s+=r){const o=e.slice(s,s+r),c=o[0],u=o[o.length-1],f=o.reduce((g,w)=>g+w.count,0),p=o.map(({link:g})=>g),d=await Ta(t,n,p);i.push({link:{hash:d.hash,size:d.size,key:d.key,type:n,meta:_1(f,c.first,u.last)},count:f,first:c.first,last:u.last})}return i.length<=r?Ta(t,se.Fanout,i.map(({link:s})=>s)):td(t,i,se.Fanout)}async function un(t,e,n,r){const i=await v1(t,e,n,r);if(!i)return[];const s=[];
3for(const o of i.links){if(jh(i,o)){if(!o.key)throw new Error(`Missing decryption key for directory fanout: ${He(o.hash)}`);s.push(...await un(t,o.hash,o.key,r));continue}o.name!==void 0&&s.push({name:o.name,hash:o.hash,size:o.size,key:o.key,type:o.type,meta:o.meta})}return s}async function Qo(t,e,n){const r=await Ys(t,e,n);return r?ct(r):null}function nd(t){const e=t.maxLinks??p1;if(!Number.isInteger(e)||e<1)throw new Error(`Invalid maxLinks: ${t.maxLinks}`);return e}async function xi(t,e,n,r){const i=[];let s=e,o=n;for(const c of r){const f=(await un(t,s,o)).find(p=>p.name===c);if(!f||!f.key)return null;i.push(f.key),s=f.hash,o=f.key}return{dirHash:s,dirKey:o,pathKeys:i}}async function S1(t,e,n,r,i,s,o,c,u=se.Blob,f){const{store:p}=t,d=await xi(p,e,n,r);if(!d)throw new Error(`Path not found: ${r.join("/")}`);const{dirHash:g,dirKey:w,pathKeys:x}=d,I=(await un(p,g,w)).filter(te=>te.name!==i).map(te=>({name:te.name,hash:te.hash,size:te.size,key:te.key,type:te.type,meta:te.meta}));I.push({name:i,hash:s,size:o,key:c,type:u,meta:f});const T=await Wr(t,I);return Zs(t,e,n,r,x,T.hash,T.key)}async function rd(t,e,n,r,i){const{store:s}=t,o=await xi(s,e,n,r);if(!o)throw new Error(`Path not found: ${r.join("/")}`);const{dirHash:c,dirKey:u,pathKeys:f}=o,d=(await un(s,c,u)).filter(w=>w.name!==i).map(w=>({name:w.name,hash:w.hash,size:w.size,key:w.key,type:w.type,meta:w.meta})),g=await Wr(t,d);return Zs(t,e,n,r,f,g.hash,g.key)}async function A1(t,e,n,r,i,s){if(i===s)return{hash:e,key:n};const{store:o}=t,c=await xi(o,e,n,r);if(!c)throw new Error(`Path not found: ${r.join("/")}`);const{dirHash:u,dirKey:f,pathKeys:p}=c,d=await un(o,u,f),g=d.find(A=>A.name===i);if(!g)throw new Error(`Entry not found: ${i}`);const w=d.filter(A=>A.name!==i).map(A=>({name:A.name,hash:A.hash,size:A.size,key:A.key,type:A.type,meta:A.meta}));w.push({name:s,hash:g.hash,size:g.size,key:g.key,type:g.type,meta:g.meta});const x=await Wr(t,w);return Zs(t,e,n,r,p,x.hash,x.key)}async function R1(t,e,n,r,i,s){const{store:o}=t,c=await xi(o,e,n,r);if(!c)throw new Error(`Source path not found: ${r.join("/")}`);const f=(await un(o,c.dirHash,c.dirKey)).find(A=>A.name===i);if(!f)throw new Error(`Entry not found: ${i}`);const p=await rd(t,e,n,r,i),d=await xi(o,p.hash,p.key,s);if(!d)throw new Error(`Target path not found: ${s.join("/")}`);const g=await un(o,d.dirHash,d.dirKey);if(g.some(A=>A.name===i))throw new Error(`Entry already exists in target: ${i}`);const w=g.map(A=>({name:A.name,hash:A.hash,size:A.size,key:A.key,type:A.type,meta:A.meta}));w.push({name:f.name,hash:f.hash,size:f.size,key:f.key,type:f.type,meta:f.meta});const x=await Wr(t,w);return Zs(t,p.hash,p.key,s,d.pathKeys,x.hash,x.key)}async function Zs(t,e,n,r,i,s,o){if(r.length===0)return{hash:s,key:o};const{store:c}=t;let u=s,f=o;const p=[...r];for(;p.length>0;){const d=p.pop();let g,w;if(p.length===0)g=e,w=n;else{g=e,w=n;for(let T=0;T<p.length;T++){const ae=(await un(c,g,w)).find(Re=>Re.name===p[T]);if(!ae||!ae.key)throw new Error(`Parent path not found: ${p.join("/")}`);g=ae.hash,w=i[T]??ae.key}}const A=(await un(c,g,w)).map(T=>T.name===d?{name:T.name,hash:u,size:T.size,key:f,type:T.type,meta:T.meta}:{name:T.name,hash:T.hash,size:T.size,key:T.key,type:T.type,meta:T.meta}),I=await Wr(t,A);u=I.hash,f=I.key}return{hash:u,key:f}}async function C1(t,e,n,r){const{store:i}=t,s=await i.get(e);if(!s)throw new Error(`Root not found: ${He(e)}`);const o=ct(s);if(!o){if(n+r.length>s.length)throw new Error(`Write extends beyond file: offset=${n}, data=${r.length}, file=${s.length}`);const p=new Uint8Array(s);p.set(r,n);const d=await it(p);return await i.put(d,p),{hash:d,size:p.length}}const c=o.links.reduce((p,d)=>p+d.size,0);if(n+r.length>c)throw new Error(`Write extends beyond file: offset=${n}, data=${r.length}, file=${c}`);const u=await id(t,o,n,r);return{hash:await I1(t,u,c),size:c}}async function T1(t,e,n,r,i){const{store:s}=t,o=await s.get(e);if(!o)throw new Error(`Root not found: ${He(e)}`);const c=await qr(o,n),u=ct(c);if(!u){if(r+i.length>c.length)throw new Error(`Write extends beyond file: offset=${r}, data=${i.length}, file=${c.length}`);const w=new Uint8Array(c);w.set(i,r);const{ciphertext:x,key:A}=await $t(w),I=await it(x);return await s.put(I,x),{hash:I,size:w.length,key:A}}const f=u.links.reduce((w,x)=>w+x.size,0);if(r+i.length>f)throw new Error(`Write extends beyond file: offset=${r}, data=${i.length}, file=${f}`);const p=await sd(t,u,r,i),{hash:d,key:g}=await B1(t,p,f);return{hash:d,size:f,key:g}}async function id(t,e,n,r){const{store:i}=t,s=[];let o=0;for(const c of e.links){const u=o,f=o+c.size;o=f;const p=n,d=n+r.length;if(f<=p||u>=d){s.push(c);continue}const g=await i.get(c.hash);if(!g)throw new Error(`Missing chunk: ${He(c.hash)}`);if(c.type!==se.Blob){const w=Vn(g),x=Math.max(0,n-u),A=r.slice(Math.max(0,u-n),Math.min(r.length,f-n)),I=await id(t,w,x,A),T={type:se.File,links:I},{data:te,hash:ae}=await fn(T);await i.put(ae,te),s.push({hash:ae,size:c.size,type:se.File})}else{const w=new Uint8Array(g),x=Math.max(0,p-u),A=Math.min(g.length,d-u),I=Math.max(0,u-p),T=I+(A-x);w.set(r.slice(I,T),x);const te=await it(w);await i.put(te,w),s.push({hash:te,size:w.length,type:se.Blob})}}return s}async function sd(t,e,n,r){const{store:i}=t,s=[],o=16;let c=0;for(const u of e.links){const f=u.type===se.Blob?u.size-o:u.size,p=c,d=c+f;c=d;const g=n,w=n+r.length;if(d<=g||p>=w){s.push(u);continue}if(!u.key)throw new Error(`Missing decryption key for chunk: ${He(u.hash)}`);const x=await i.get(u.hash);if(!x)throw new Error(`Missing chunk: ${He(u.hash)}`);const A=await qr(x,u.key);if(u.type!==se.Blob){const I=Vn(A),T=Math.max(0,n-p),te=r.slice(Math.max(0,p-n),Math.min(r.length,d-n)),ae=await sd(t,I,T,te),Re={type:se.File,links:ae},{data:le}=await fn(Re),{ciphertext:Y,key:Q}=await $t(le),ie=await it(Y);await i.put(ie,Y);const ee=ae.reduce((ge,$)=>ge+($.type===se.Blob?$.size-o:$.size),0);s.push({hash:ie,size:ee,key:Q,type:se.File})}else{const I=new Uint8Array(A),T=Math.max(0,g-p),te=Math.min(A.length,w-p),ae=Math.max(0,p-g),Re=ae+(te-T);I.set(r.slice(ae,Re),T);const{ciphertext:le,key:Y}=await $t(I),Q=await it(le);await i.put(Q,le),s.push({hash:Q,size:le.length,key:Y,type:se.Blob})}}return s}async function I1(t,e,n){const{store:r}=t;if(e.length===1&&e[0].size===n)return e[0].hash;const i={type:se.File,links:e},{data:s,hash:o}=await fn(i);return await r.put(o,s),o}async function B1(t,e,n){const{store:r}=t;if(e.length===1&&e[0].key&&e[0].size===n)return{hash:e[0].hash,key:e[0].key};const i={type:se.File,links:e},{data:s}=await fn(i),{ciphertext:o,key:c}=await $t(s),u=await it(o);return await r.put(u,o),{hash:u,key:c}}const L1=2*1024*1024,M1=174;class od{store;chunkSize;maxLinks;constructor(e){if(this.store=e.store,this.chunkSize=e.chunkSize??L1,this.maxLinks=e.maxLinks??M1,!Number.isInteger(this.maxLinks)||this.maxLinks<1)throw new Error(`Invalid maxLinks: ${e.maxLinks}`)}get config(){return{store:this.store,chunkSize:this.chunkSize,maxLinks:this.maxLinks}}async putBlob(e){return Ca(this.store,e)}async putFile(e,n){if(n?.unencrypted){const i=await XE(this.config,e);return{cid:{hash:i.hash},size:i.size}}const r=await g1(this.config,e);
3return{cid:Ut(r.hash,r.key),size:r.size}}async putDirectory(e,n){const r=e.reduce((o,c)=>o+(c.size??0),0);if(n?.unencrypted){const o=e.map(u=>({name:u.name,cid:u.cid,size:u.size,type:u.type??se.Blob,meta:u.meta}));return{cid:{hash:await Ri(this.config,o)},size:r}}const i=e.map(o=>({name:o.name,hash:o.cid.hash,size:o.size,key:o.cid.key,type:o.type??se.Blob,meta:o.meta})),s=await Wr(this.config,i);return{cid:Ut(s.hash,s.key),size:r}}async getBlob(e){return r1(this.store,e)}async getTreeNode(e){return e.key?Qo(this.store,e.hash,e.key):i1(this.store,e.hash)}async getType(e){return e?.hash?s1(this.store,e.hash):se.Blob}async isDirectory(e){if(!e?.hash)return!1;if(e.key)try{const n=await Qo(this.store,e.hash,e.key);return n?n.type===se.Dir||n.type===se.Fanout:!1}catch{return!1}return o1(this.store,e.hash)}async readFile(e,n={}){return this.get(e,n)}async get(e,n={}){return e.key?w1(this.store,e.hash,e.key,n):a1(this.store,e.hash,n)}async*readFileStream(e,n={}){e.key?yield*b1(this.store,e.hash,e.key,n):yield*c1(this.store,e.hash,n)}async readFileRange(e,n,r){return e.key?E1(this.store,e.hash,e.key,n,r):u1(this.store,e.hash,n,r)}async listDirectory(e,n){return e.key?(await un(this.store,e.hash,e.key,n)).map(s=>({name:s.name,cid:Ut(s.hash,s.key),size:s.size,type:s.type??se.Blob,meta:s.meta})):(await _n(this.store,e.hash,n)).map(i=>({name:i.name,cid:i.cid,size:i.size,type:i.type,meta:i.meta}))}async resolvePath(e,n,r){const i=Array.isArray(n)?n:n.split("/").filter(c=>c.length>0);let s=e,o=se.Dir;for(const c of i){const f=(await this.listDirectory(s,r)).find(p=>p.name===c);if(!f)return null;s=f.cid,o=f.type}return{cid:s,type:o}}async getSize(e){return f1(this.store,e)}async*walk(e,n=""){yield*Zh(this.store,e,n)}async walkTree(e,n){const r=[],i=async(s,o)=>{if(await this.isDirectory(s)){if(!n?.filesOnly){const p=(await this.listDirectory(s)).reduce((d,g)=>d+g.size,0);r.push({path:o,cid:s,type:se.Dir,size:p})}const u=await this.listDirectory(s);for(const f of u){const p=o?`${o}/${f.name}`:f.name;await i(f.cid,p)}}
3else{const u=await this.getType(s),f=await this.getSize(s.hash),p={path:o,cid:s,type:u,size:f};if(n?.includeData){const d=await this.readFile(s);d&&(p.data=d)}r.push(p)}};return await i(e,""),r}async*walkBlocks(e){const n=new Set,r=async function*(i,s,o){const c=He(s);if(n.has(c))return;n.add(c);const u=await i.get(s);if(!u)throw new Error(`Missing block: ${c}`);yield{hash:s,data:u};const f=ct(o?await Uc(u,o):u);if(f)for(const p of f.links)yield*r(i,p.hash,p.key)};yield*r(this.store,e.hash,e.key)}async pull(e){const n=new Set;let r=0,i=0;const s=async(o,c)=>{const u=He(o);if(n.has(u))return;n.add(u);const f=await this.store.get(o);if(f)if(r++,i+=f.length,c){const p=await Qo(this.store,o,c);p&&await Promise.all(p.links.map(d=>s(d.hash,d.key)))}else{const p=ct(f);p&&await Promise.all(p.links.map(d=>s(d.hash,d.key)))}};return await s(e.hash,e.key),{cid:e,chunks:r,bytes:i}}async push(e,n,r){const i=await this.pull(e);if(r?.signal?.aborted)return{cid:e,pushed:0,skipped:0,failed:0,bytes:0,errors:[],cancelled:!0};let s=0,o=0,c=0,u=0,f=0;const p=i.chunks;let d=!1;const g=[],w=r?.concurrency??4,x=[],A=w*2;let I=null,T=null;const te=async le=>{if(r?.signal?.aborted)return;const{hash:Y,data:Q}=le;try{await n.put(Y,Q)===!1?(o++,r?.onBlock?.(Y,"skipped")):(s++,u+=Q.length,r?.onBlock?.(Y,"success"))}catch(ie){c++;const ee=ie instanceof Error?ie:new Error(String(ie));g.push({hash:Y,error:ee}),r?.onBlock?.(Y,"error",ee)}f++,r?.onProgress?.(f,p)},ae=async()=>{const le=[];for(;(!d||x.length>0||le.length>0)&&!r?.signal?.aborted;){for(;le.length<w&&x.length>0;){const Y=x.shift();I&&x.length<A&&(I(),I=null);const Q=te(Y).then(()=>{le.splice(le.indexOf(Q),1)});le.push(Q)}if(x.length===0&&!d&&le.length<w){await new Promise(Y=>{T=Y});continue}le.length>0&&await Promise.race(le)}await Promise.all(le)},Re=async()=>{for await(const le of this.walkBlocks(e)){if(r?.signal?.aborted)break;for(;x.length>=A&&(await new Promise(Y=>{I=Y}),!r?.signal?.aborted););x.push(le),T&&(T(),T=null)}d=!0,T&&(T(),T=null)};return await Promise.all([Re(),ae()]),{cid:e,pushed:s,skipped:o,failed:c,bytes:u,errors:g,cancelled:r?.signal?.aborted??!1}}async setEntry(e,n,r,i,s,o=se.Blob,c){if(e.key){const f=await S1(this.config,e.hash,e.key,n,r,i.hash,s,i.key,o,c);return Ut(f.hash,f.key)}return{hash:await Xh(this.config,e.hash,n,r,i,s,o,c)}}async removeEntry(e,n,r){if(e.key){const s=await rd(this.config,e.hash,e.key,n,r);return Ut(s.hash,s.key)}return{hash:await Jh(this.config,e.hash,n,r)}}async renameEntry(e,n,r,i){if(e.key){const o=await A1(this.config,e.hash,e.key,n,r,i);return Ut(o.hash,o.key)}return{hash:await h1(this.config,e.hash,n,r,i)}}async moveEntry(e,n,r,i){if(e.key){const o=await R1(this.config,e.hash,e.key,n,r,i);return Ut(o.hash,o.key)}return{hash:await d1(this.config,e.hash,n,r,i)}}async writeAt(e,n,r){if(e.key){const s=await T1(this.config,e.hash,e.key,n,r);return Ut(s.hash,s.key)}return{hash:(await C1(this.config,e.hash,n,r)).hash}}getStore(){return this.store}createStream(e){return new YE({store:this.store,chunkSize:this.chunkSize,chunker:e?.chunker,unencrypted:e?.unencrypted??!1})}}function ad(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function cd(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function O1(t){if(typeof t!="function")throw new TypeError("function expected");return!0}function _i(t,e){if(typeof e!="string")throw new TypeError(`${t}: string expected`);return!0}function ud(t){if(typeof t!="number")throw new TypeError(`number expected, got ${typeof t}`);if(!Number.isSafeInteger(t))throw new RangeError(`invalid integer: ${t}`)}function Ia(t){if(!Array.isArray(t))throw new TypeError("array expected")}function ld(t,e){if(!cd(!0,e))throw new TypeError(`${t}: array of strings expected`)}function fd(t,e){if(!cd(!1,e))throw new TypeError(`${t}: array of numbers expected`)}function D1(...t){const e=s=>s,n=(s,o)=>c=>s(o(c)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function N1(t){const e=typeof t=="string"?t.split(""):t,n=e.length;ld("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Ia(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Ia(i),i.map(s=>
3{_i("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function P1(t=""){return _i("join",t),{encode:e=>(ld("join.decode",e),e.join(t)),decode:e=>(_i("join.decode",e),e.split(t))}}const hd=(t,e)=>e===0?t:hd(e,t%e),Is=(t,e)=>t+(e-hd(t,e)),ys=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ba(t,e,n,r){if(Ia(t),e<=0||e>32)throw new RangeError(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new RangeError(`convertRadix2: wrong to=${n}`);if(Is(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Is(e,n)}`);let i=0,s=0;const o=ys[e],c=ys[n]-1,u=[];for(const f of t){if(ud(f),f>=o)throw new Error(`convertRadix2: invalid data word=${f} from=${e}`);if(i=i<<e|f,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)u.push((i>>s-n&c)>>>0);const p=ys[s];if(p===void 0)throw new Error("invalid carry");i&=p-1}if(i=i<<n-s&c,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&u.push(i>>>0),u}function F1(t,e=!1){if(ud(t),t<=0||t>32)throw new RangeError("radix2: bits should be in (0..32]");if(Is(8,t)>32||Is(t,8)>32)throw new RangeError("radix2: carry overflow");return{encode:n=>{if(!ad(n))throw new TypeError("radix2.encode input should be Uint8Array");return Ba(Array.from(n),8,t,!e)},decode:n=>(fd("radix2.decode",n),Uint8Array.from(Ba(n,t,8,e)))}}function pl(t){return O1(t),function(...e){try{return t.apply(null,e)}catch{}}}const La=D1(N1("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),P1("")),yl=[996825010,642813549,513874426,1027748829,705979059];function di(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<yl.length;r++)(e>>r&1)===1&&(n^=yl[r]);return n}function gl(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=di(i)^o>>5}i=di(i);for(let s=0;s<r;s++)i=di(i)^t.charCodeAt(s)&31;for(let s of e)i=di(i)^s;for(let s=0;s<6;s++)i=di(i);return i^=n,La.encode(Ba([i%ys[30]],30,5,!1))}function U1(t){const e=t==="bech32"?1:734539939,n=F1(5),r=n.decode,i=n.encode,s=pl(r);function o(d,g,w=90){_i("bech32.encode prefix",d),ad(g)&&(g=Array.from(g)),fd("bech32.encode",g);const x=d.length;if(x===0)throw new TypeError(`Invalid prefix length ${x}`);const A=x+7+g.length;if(w!==!1&&A>w)throw new TypeError(`Length ${A} exceeds limit ${w}`);const I=d.toLowerCase(),T=gl(I,g,e);return`${I}1${La.encode(g)}${T}`}function c(d,g=90){_i("bech32.decode input",d);const w=d.length;if(w<8||g!==!1&&w>g)throw new TypeError(`invalid string length: ${w} (${d}). Expected (8..${g})`);const x=d.toLowerCase();if(d!==x&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");const A=x.lastIndexOf("1");if(A===0||A===-1)throw new Error('Letter "1" must be present between prefix and data only');const I=x.slice(0,A),T=x.slice(A+1);if(T.length<6)throw new Error("Data must be at least 6 characters long");const te=La.decode(T).slice(0,-6),ae=gl(I,te,e);if(!T.endsWith(ae))throw new Error(`Invalid checksum in ${d}: expected "${ae}"`);return{prefix:I,words:te}}const u=pl(c);function f(d){const{prefix:g,words:w}=c(d,!1);return{prefix:g,words:w,bytes:r(w)}}function p(d,g){return o(d,i(g))}return{encode:o,decode:c,encodeFromBytes:p,decodeToBytes:f,decodeUnsafe:u,fromWords:r,fromWordsUnsafe:s,toWords:i}}const Bs=Object.freeze(U1("bech32"));function $1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function K1(t,e,n=""){const r=$1(t),i=t?.length;if(!r||e!==void 0){const o=n&&`"${n}" `,c="",u=r?`length=${i}`:`type=${typeof t}`,f=o+"expected Uint8Array"+c+", got "+u;throw r?new RangeError(f):new TypeError(f)}return t}const z1=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",gn={_0:48,_9:57,A:65,F:70,a:97,f:102};function ml(t){if(t>=gn._0&&t<=gn._9)return t-gn._0;if(t>=gn.A&&t<=gn.F)return t-(gn.A-10);if(t>=gn.a&&t<=gn.f)return t-(gn.a-10)}function ea(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);
3if(z1)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}const e=t.length,n=e/2;if(e%2)throw new RangeError("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=ml(t.charCodeAt(s)),c=ml(t.charCodeAt(s+1));if(o===void 0||c===void 0){const u=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+s)}r[i]=o*16+c}return r}function H1(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];K1(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const dd=5e3;new TextEncoder;new TextDecoder("utf-8");const Un={HASH:0,DECRYPT_KEY:5};function q1(t){const e={};let n=0;for(;n<t.length;){if(n+2>t.length)throw new Error("TLV: unexpected end of data");const r=t[n],i=t[n+1];if(n+=2,n+i>t.length)throw new Error(`TLV: not enough data for type ${r}, need ${i} bytes`);const s=t.slice(n,n+i);n+=i,e[r]=e[r]||[],e[r].push(s)}return e}function W1(t){const e=[],n=Object.keys(t).map(Number).sort((r,i)=>r-i);for(const r of n){const i=t[r];for(const s of i){if(s.length>255)throw new Error(`TLV value too long for type ${r}: ${s.length} bytes`);const o=new Uint8Array(s.length+2);o[0]=r,o[1]=s.length,o.set(s,2),e.push(o)}}return H1(...e)}function ta(t,e){const n=Bs.toWords(e);return Bs.encode(t,n,dd)}function j1(t){return typeof t=="object"&&t!==null&&"hash"in t&&t.hash instanceof Uint8Array}function na(t,e){if(t.length!==32)throw new Error(`Hash must be 32 bytes, got ${t.length}`);const n={[Un.HASH]:[t]};if(e){if(e.length!==32)throw new Error(`Decrypt key must be 32 bytes, got ${e.length}`);n[Un.DECRYPT_KEY]=[e]}return W1(n)}function Ma(t){if(typeof t=="string"||t instanceof Uint8Array){const r=typeof t=="string"?ea(t):t;return ta("nhash",na(r))}if(j1(t))return ta("nhash",na(t.hash,t.key));const e=ea(t.hash),n=t.decryptKey?ea(t.decryptKey):void 0;return ta("nhash",na(e,n))}function Xs(t){t.startsWith("hashtree:")&&(t=t.substring(9));const{prefix:e,words:n}=Bs.decode(t,dd);if(e!=="nhash")throw new Error(`Expected nhash prefix, got ${e}`);const r=new Uint8Array(Bs.fromWords(n));if(r.length===32)return{hash:r};const i=q1(r);if(!i[Un.HASH]?.[0]||i[Un.HASH][0].length!==32)throw new Error("nhash: missing or invalid hash");const s={hash:i[Un.HASH][0]};if(i[Un.DECRYPT_KEY]?.[0]){if(i[Un.DECRYPT_KEY][0].length!==32)throw new Error("nhash: decrypt key must be 32 bytes");s.key=i[Un.DECRYPT_KEY][0]}return s}const V1=50;class G1 extends fr{blobs;accesses;constructor(e){super(e),this.version(1).stores({blobs:"&hashHex"}),this.version(2).stores({blobs:"&hashHex, lastAccess"}).upgrade(n=>{const r=Date.now();return n.table("blobs").toCollection().modify(i=>{i.lastAccess=r})}),this.version(3).stores({blobs:"&hashHex, lastAccess",accesses:"&hashHex, lastAccess"}).upgrade(async n=>{const r=await n.table("blobs").toArray(),i=n.table("accesses");await Promise.all(r.map(s=>i.put({hashHex:s.hashHex,lastAccess:s.lastAccess??Date.now()})))})}}class Y1{db;pendingLastAccessUpdates=new Map;lastAccessFlushPromise=null;lastAccessFlushTimer=null;constructor(e="hashtree"){this.db=new G1(e)}scheduleLastAccessTouch(e){this.pendingLastAccessUpdates.set(e,Date.now()),this.lastAccessFlushTimer===null&&(this.lastAccessFlushTimer=setTimeout(()=>{this.lastAccessFlushTimer=null,this.flushPendingLastAccessUpdates()},V1))}async flushPendingLastAccessUpdates(){if(this.lastAccessFlushTimer!==null&&(clearTimeout(this.lastAccessFlushTimer),this.lastAccessFlushTimer=null),this.lastAccessFlushPromise&&(await this.lastAccessFlushPromise,this.pendingLastAccessUpdates.size===0)||this.pendingLastAccessUpdates.size===0)return;const e=Array.from(this.pendingLastAccessUpdates,([r,i])=>({hashHex:r,lastAccess:i}));this.pendingLastAccessUpdates.clear();const n=this.db.accesses.bulkPut(e).then(()=>{}).catch(r=>{console.error("[DexieStore] lastAccess flush error:",r)}).finally(()=>{this.lastAccessFlushPromise=null});this.lastAccessFlushPromise=n,await n,this.pendingLastAccessUpdates.size>0&&await this.flushPendingLastAccessUpdates()}async put(e,n){const r=He(e),i=Date.now();try{return await this.flushPendingLastAccessUpdates(),await this.db.transaction("rw",this.db.blobs,this.db.accesses,async()=>{await this.db.blobs.put({hashHex:r,data:n,lastAccess:i}),await this.db.accesses.put({hashHex:r,lastAccess:i})}),!0}catch(s){return console.error("[DexieStore] put error:",s),!1}}async get(e){if(!e)return null;const n=He(e);try{const r=await this.db.blobs.get(n);if(!r)return null;this.scheduleLastAccessTouch(n);const i=r.data;return i.byteOffset===0&&i.byteLength===i.buffer.byteLength?i:new Uint8Array(i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength))}catch(r){return console.error("[DexieStore] get error:",r),null}}async has(e){const n=He(e);try{return await this.db.blobs.where("hashHex").equals(n).count()>0}catch(r){return console.error("[DexieStore] has error:",r),!1}}async delete(e){const n=He(e);try{return await this.flushPendingLastAccessUpdates(),await this.has(e)?(await this.db.transaction("rw",this.db.blobs,this.db.accesses,async()=>{await this.db.blobs.delete(n),await this.db.accesses.delete(n)}),!0):!1}catch(r){return console.error("[DexieStore] delete error:",r),!1}}async keys(){try{return(await this.db.blobs.toCollection().primaryKeys()).map(n=>_a(n))}catch(e){return console.error("[DexieStore] keys error:",e),[]}}async clear(){try{await this.flushPendingLastAccessUpdates(),await this.db.transaction("rw",this.db.blobs,this.db.accesses,async()=>{await this.db.blobs.clear(),await this.db.accesses.clear()})}catch(e){console.error("[DexieStore] clear error:",e)}}async count(){try{return await this.db.blobs.count()}catch(e){return console.error("[DexieStore] count error:",e),0}}async totalBytes(){try{let e=0;return await this.db.blobs.each(n=>{e+=n.data.byteLength}),e}catch(e){return console.error("[DexieStore] totalBytes error:",e),0}}async evict(e,n=new Set){try{await this.flushPendingLastAccessUpdates();const r=await this.totalBytes();if(r<=e)return 0;const i=await this.db.accesses.orderBy("lastAccess").toArray();let s=0,o=0;const c=r-e;for(const u of i){if(s>=c)break;if(n.has(u.hashHex))continue;const f=await this.db.blobs.get(u.hashHex);await this.db.transaction("rw",this.db.blobs,this.db.accesses,async()=>{await this.db.blobs.delete(u.hashHex),await this.db.accesses.delete(u.hashHex)}),s+=f?.data.byteLength??0,o++}return console.log(`[DexieStore] Evicted ${o} entries (${s} bytes)`),o}catch(r){return console.error("[DexieStore] evict error:",r),0}}close(){this.lastAccessFlushTimer!==null&&(clearTimeout(this.lastAccessFlushTimer),this.lastAccessFlushTimer=null),this.pendingLastAccessUpdates.clear(),this.db.close()}static async deleteDatabase(e="hashtree"){await fr.delete(e)}}function ss(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var ra={exports:{}},wl;function Z1(){return wl||(wl=1,(function(t,e){var n={};(function(r){t.exports=r()})(function(){return(function r(i,s,o){function c(p,d){if(!s[p]){if(!i[p]){var g=typeof ss=="function"&&ss;if(!d&&g)return g(p,!0);if(u)return u(p,!0);var w=new Error("Cannot find module '"+p+"'");throw w.code="MODULE_NOT_FOUND",w}var x=s[p]={exports:{}};i[p][0].call(x.exports,function(A){var I=i[p][1][A];return c(I||A)},x,x.exports,r,i,s,o)}return s[p].exports}for(var u=typeof ss=="function"&&ss,f=0;f<o.length;f++)c(o[f]);return c})({1:[function(r,i,s){(function(o){var c=o.MutationObserver||o.WebKitMutationObserver,u;if(c){var f=0,p=new c(A),d=o.document.createTextNode("");p.observe(d,{characterData:!0}
vendor: 28,480 bytes, line 3
3),u=function(){d.data=f=++f%2}}else if(!o.setImmediate&&typeof o.MessageChannel<"u"){var g=new o.MessageChannel;g.port1.onmessage=A,u=function(){g.port2.postMessage(0)}}else"document"in o&&"onreadystatechange"in o.document.createElement("script")?u=function(){var T=o.document.createElement("script");T.onreadystatechange=function(){A(),T.onreadystatechange=null,T.parentNode.removeChild(T),T=null},o.document.documentElement.appendChild(T)}:u=function(){setTimeout(A,0)};var w,x=[];function A(){w=!0;for(var T,te,ae=x.length;ae;){for(te=x,x=[],T=-1;++T<ae;)te[T]();ae=x.length}w=!1}i.exports=I;function I(T){x.push(T)===1&&!w&&u()}}).call(this,typeof n<"u"?n:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(r,i,s){var o=r(1);function c(){}var u={},f=["REJECTED"],p=["FULFILLED"],d=["PENDING"];i.exports=g;function g(Y){if(typeof Y!="function")throw new TypeError("resolver must be a function");this.state=d,this.queue=[],this.outcome=void 0,Y!==c&&I(this,Y)}g.prototype.catch=function(Y){return this.then(null,Y)},g.prototype.then=function(Y,Q){if(typeof Y!="function"&&this.state===p||typeof Q!="function"&&this.state===f)return this;var ie=new this.constructor(c);if(this.state!==d){var ee=this.state===p?Y:Q;x(ie,ee,this.outcome)}else this.queue.push(new w(ie,Y,Q));return ie};function w(Y,Q,ie){this.promise=Y,typeof Q=="function"&&(this.onFulfilled=Q,this.callFulfilled=this.otherCallFulfilled),typeof ie=="function"&&(this.onRejected=ie,this.callRejected=this.otherCallRejected)}w.prototype.callFulfilled=function(Y){u.resolve(this.promise,Y)},w.prototype.otherCallFulfilled=function(Y){x(this.promise,this.onFulfilled,Y)},w.prototype.callRejected=function(Y){u.reject(this.promise,Y)},w.prototype.otherCallRejected=function(Y){x(this.promise,this.onRejected,Y)};function x(Y,Q,ie){o(function(){var ee;try{ee=Q(ie)}catch(ge){return u.reject(Y,ge)}ee===Y?u.reject(Y,new TypeError("Cannot resolve promise with itself")):u.resolve(Y,ee)})}u.resolve=function(Y,Q){var ie=T(A,Q);if(ie.status==="error")return u.reject(Y,ie.value);var ee=ie.value;if(ee)I(Y,ee);else{Y.state=p,Y.outcome=Q;for(var ge=-1,$=Y.queue.length;++ge<$;)Y.queue[ge].callFulfilled(Q)}return Y},u.reject=function(Y,Q){Y.state=f,Y.outcome=Q;for(var ie=-1,ee=Y.queue.length;++ie<ee;)Y.queue[ie].callRejected(Q);return Y};function A(Y){var Q=Y&&Y.then;if(Y&&(typeof Y=="object"||typeof Y=="function")&&typeof Q=="function")return function(){Q.apply(Y,arguments)}}function I(Y,Q){var ie=!1;function ee(C){ie||(ie=!0,u.reject(Y,C))}function ge(C){ie||(ie=!0,u.resolve(Y,C))}function $(){Q(ge,ee)}var H=T($);H.status==="error"&&ee(H.value)}function T(Y,Q){var ie={};try{ie.value=Y(Q),ie.status="success"}catch(ee){ie.status="error",ie.value=ee}return ie}g.resolve=te;function te(Y){return Y instanceof this?Y:u.resolve(new this(c),Y)}g.reject=ae;function ae(Y){var Q=new this(c);return u.reject(Q,Y)}g.all=Re;function Re(Y){var Q=this;if(Object.prototype.toString.call(Y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var ie=Y.length,ee=!1;if(!ie)return this.resolve([]);for(var ge=new Array(ie),$=0,H=-1,C=new this(c);++H<ie;)j(Y[H],H);return C;function j(P,X){Q.resolve(P).then(re,function(xe){ee||(ee=!0,u.reject(C,xe))});function re(xe){ge[X]=xe,++$===ie&&!ee&&(ee=!0,u.resolve(C,ge))}}}g.race=le;function le(Y){var Q=this;if(Object.prototype.toString.call(Y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var ie=Y.length,ee=!1;if(!ie)return this.resolve([]);for(var ge=-1,$=new this(c);++ge<ie;)H(Y[ge]);return $;function H(C){Q.resolve(C).then(function(j){ee||(ee=!0,u.resolve($,j))},function(j){ee||(ee=!0,u.reject($,j))})}}},{1:1}],3:[function(r,i,s){(function(o){typeof o.Promise!="function"&&(o.Promise=r(2))}).call(this,typeof n<"u"?n:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(r,i,s){var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(b){return typeof b}:function(b){return b&&typeof Symbol=="function"&&b.constructor===Symbol&&b!==Symbol.prototype?"symbol":typeof b};function c(b,R){if(!(b instanceof R))throw new TypeError("Cannot call a class as a function")}function u(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var f=u();function p(){try{if(!f||!f.open)return!1;var b=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),R=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!b||R)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function d(b,R){b=b||[],R=R||{};try{return new Blob(b,R)}catch(L){if(L.name!=="TypeError")throw L;for(var k=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,D=new k,q=0;q<b.length;q+=1)D.append(b[q]);return D.getBlob(R.type)}}typeof Promise>"u"&&r(3);var g=Promise;function w(b,R){R&&b.then(function(k){R(null,k)},function(k){R(k)})}function x(b,R,k){typeof R=="function"&&b.then(R),typeof k=="function"&&b.catch(k)}function A(b){return typeof b!="string"&&(console.warn(b+" used as a key, but it is not a string."),b=String(b)),b}function I(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var T="local-forage-detect-blob-support",te=void 0,ae={},Re=Object.prototype.toString,le="readonly",Y="readwrite";function Q(b){for(var R=b.length,k=new ArrayBuffer(R),D=new Uint8Array(k),q=0;q<R;q++)D[q]=b.charCodeAt(q);return k}function ie(b){return new g(function(R){var k=b.transaction(T,Y),D=d([""]);k.objectStore(T).put(D,"key"),k.onabort=function(q){q.preventDefault(),q.stopPropagation(),R(!1)},k.oncomplete=function(){var q=navigator.userAgent.match(/Chrome\/(\d+)/),L=navigator.userAgent.match(/Edge\//);R(L||!q||parseInt(q[1],10)>=43)}}).catch(function(){return!1})}function ee(b){return typeof te=="boolean"?g.resolve(te):ie(b).then(function(R){return te=R,te})}function ge(b){var R=ae[b.name],k={};k.promise=new g(function(D,q){k.resolve=D,k.reject=q}),R.deferredOperations.push(k),R.dbReady?R.dbReady=R.dbReady.then(function(){return k.promise}):R.dbReady=k.promise}function $(b){var R=ae[b.name],k=R.deferredOperations.pop();if(k)return k.resolve(),k.promise}function H(b,R){var k=ae[b.name],D=k.deferredOperations.pop();if(D)return D.reject(R),D.promise}function C(b,R){return new g(function(k,D){if(ae[b.name]=ae[b.name]||we(),b.db)if(R)ge(b),b.db.close();else return k(b.db);var q=[b.name];R&&q.push(b.version);var L=f.open.apply(f,q);R&&(L.onupgradeneeded=function(J){var oe=L.result;try{oe.createObjectStore(b.storeName),J.oldVersion<=1&&oe.createObjectStore(T)}catch(he){if(he.name==="ConstraintError")console.warn('The database "'+b.name+'" has been upgraded from version '+J.oldVersion+" to version "+J.newVersion+', but the storage "'+b.storeName+'" already exists.');else throw he}}),L.onerror=function(J){J.preventDefault(),D(L.error)},L.onsuccess=function(){var J=L.result;J.onversionchange=function(oe){oe.target.close()},k(J),$(b)}})}function j(b){return C(b,!1)}function P(b){return C(b,!0)}function X(b,R){if(!b.db)return!0;var k=!b.db.objectStoreNames.contains(b.storeName),D=b.version<b.db.version,q=b.version>b.db.version;if(D&&(b.version!==R&&console.warn('The database "'+b.name+`" can't be downgraded from version `+b.db.version+" to version "+b.version+"."),b.version=b.db.version),q||k){if(k){var L=b.db.version+1;L>b.version&&(b.version=L)}return!0}return!1}function re(b){return new g(function(R,k){var D=new FileReader;D.onerror=k,D.onloadend=function(q){var L=btoa(q.target.result||"");R({__local_forage_encoded_blob:!0,data:L,type:b.type})},D.readAsBinaryString(b)})}function xe(b){var R=Q(atob(b.data));return d([R],{type:b.type})}function pe(b){return b&&b.__local_forage_encoded_blob}function _e(b){var R=this,k=R._initReady().then(function(){var D=ae[R._dbInfo.name];if(D&&D.dbReady)return D.dbReady});return x(k,b,b),k}function _(b){ge(b);for(var R=ae[b.name],k=R.forages,D=0;D<k.length;D++){var q=k[D];q._dbInfo.db&&(q._dbInfo.db.close(),q._dbInfo.db=null)}return b.db=null,j(b).then(function(L){return b.db=L,X(b)?P(b):L}).then(function(L){b.db=R.db=L;for(var J=0;J<k.length;J++)k[J]._dbInfo.db=L}).catch(function(L){throw H(b,L),L})}function W(b,R,k,D){D===void 0&&(D=1);try{var q=b.db.transaction(b.storeName,R);k(null,q)}catch(L){if(D>0&&(!b.db||L.name==="InvalidStateError"||L.name==="NotFoundError"))return g.resolve().then(function(){if(!b.db||L.name==="NotFoundError"&&!b.db.objectStoreNames.contains(b.storeName)&&b.version<=b.db.version)return b.db&&(b.version=b.db.version+1),P(b)}).then(function(){return _(b).then(function(){W(b,R,k,D-1)})}).catch(k);k(L)}}function we(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function ke(b){var R=this,k={db:null};if(b)for(var D in b)k[D]=b[D];var q=ae[k.name];q||(q=we(),ae[k.name]=q),q.forages.push(R),R._initReady||(R._initReady=R.ready,R.ready=_e);var L=[];function J(){return g.resolve()}for(var oe=0;oe<q.forages.length;oe++){var he=q.forages[oe];he!==R&&L.push(he._initReady().catch(J))}var de=q.forages.slice(0);return g.all(L).then(function(){return k.db=q.db,j(k)}).then(function(be){return k.db=be,X(k,R._defaultConfig.version)?P(k):be}).then(function(be){k.db=q.db=be,R._dbInfo=k;for(var Te=0;Te<de.length;Te++){var $e=de[Te];$e!==R&&($e._dbInfo.db=k.db,$e._dbInfo.version=k.version)}})}function ye(b,R){var k=this;b=A(b);var D=new g(function(q,L){k.ready().then(function(){W(k._dbInfo,le,function(J,oe){if(J)return L(J);try{var he=oe.objectStore(k._dbInfo.storeName),de=he.get(b);de.onsuccess=function(){var be=de.result;be===void 0&&(be=null),pe(be)&&(be=xe(be)),q(be)},de.onerror=function(){L(de.error)}}catch(be){L(be)}})}).catch(L)});return w(D,R),D}function Ce(b,R){var k=this,D=new g(function(q,L){k.ready().then(function(){W(k._dbInfo,le,function(J,oe){if(J)return L(J);try{var he=oe.objectStore(k._dbInfo.storeName),de=he.openCursor(),be=1;de.onsuccess=function(){var Te=de.result;if(Te){var $e=Te.value;pe($e)&&($e=xe($e));var Ye=b($e,Te.key,be++);Ye!==void 0?q(Ye):Te.continue()}else q()},de.onerror=function(){L(de.error)}}catch(Te){L(Te)}})}).catch(L)});return w(D,R),D}function Me(b,R,k){var D=this;b=A(b);var q=new g(function(L,J){var oe;D.ready().then(function(){return oe=D._dbInfo,Re.call(R)==="[object Blob]"?ee(oe.db).then(function(he){return he?R:re(R)}):R}).then(function(he){W(D._dbInfo,Y,function(de,be){if(de)return J(de);try{var Te=be.objectStore(D._dbInfo.storeName);he===null&&(he=void 0);var $e=Te.put(he,b);be.oncomplete=function(){he===void 0&&(he=null),L(he)},be.onabort=be.onerror=function(){var Ye=$e.error?$e.error:$e.transaction.error;J(Ye)}}catch(Ye){J(Ye)}})}).catch(J)});return w(q,k),q}function Ve(b,R){var k=this;b=A(b);var D=new g(function(q,L){k.ready().then(function(){W(k._dbInfo,Y,function(J,oe){if(J)return L(J);try{var he=oe.objectStore(k._dbInfo.storeName),de=he.delete(b);oe.oncomplete=function(){q()},oe.onerror=function(){L(de.error)},oe.onabort=function(){var be=de.error?de.error:de.transaction.error;L(be)}}catch(be){L(be)}})}).catch(L)});return w(D,R),D}function Ue(b){var R=this,k=new g(function(D,q){R.ready().then(function(){W(R._dbInfo,Y,function(L,J){if(L)return q(L);try{var oe=J.objectStore(R._dbInfo.storeName),he=oe.clear();J.oncomplete=function(){D()},J.onabort=J.onerror=function(){var de=he.error?he.error:he.transaction.error;q(de)}}catch(de){q(de)}})}).catch(q)});return w(k,b),k}function ut(b){var R=this,k=new g(function(D,q){R.ready().then(function(){W(R._dbInfo,le,function(L,J){if(L)return q(L);try{var oe=J.objectStore(R._dbInfo.storeName),he=oe.count();he.onsuccess=function(){D(he.result)},he.onerror=function(){q(he.error)}}catch(de){q(de)}})}).catch(q)});return w(k,b),k}function Be(b,R){var k=this,D=new g(function(q,L){if(b<0){q(null);return}k.ready().then(function(){W(k._dbInfo,le,function(J,oe){if(J)return L(J);try{var he=oe.objectStore(k._dbInfo.storeName),de=!1,be=he.openKeyCursor();be.onsuccess=function(){var Te=be.result;if(!Te){q(null);return}b===0||de?q(Te.key):(de=!0,Te.advance(b))},be.onerror=function(){L(be.error)}}catch(Te){L(Te)}})}).catch(L)});return w(D,R),D}function Zn(b){var R=this,k=new g(function(D,q){R.ready().then(function(){W(R._dbInfo,le,function(L,J){if(L)return q(L);try{var oe=J.objectStore(R._dbInfo.storeName),he=oe.openKeyCursor(),de=[];he.onsuccess=function(){var be=he.result;if(!be){D(de);return}de.push(be.key),be.continue()},he.onerror=function(){q(he.error)}}catch(be){q(be)}})}).catch(q)});return w(k,b),k}function Ge(b,R){R=I.apply(this,arguments);var k=this.config();b=typeof b!="function"&&b||{},b.name||(b.name=b.name||k.name,b.storeName=b.storeName||k.storeName);var D=this,q;if(!b.name)q=g.reject("Invalid arguments");else{var L=b.name===k.name&&D._dbInfo.db,J=L?g.resolve(D._dbInfo.db):j(b).then(function(oe){var he=ae[b.name],de=he.forages;he.db=oe;for(var be=0;be<de.length;be++)de[be]._dbInfo.db=oe;return oe});b.storeName?q=J.then(function(oe){if(oe.objectStoreNames.contains(b.storeName)){var he=oe.version+1;ge(b);var de=ae[b.name],be=de.forages;oe.close();for(var Te=0;Te<be.length;Te++){var $e=be[Te];$e._dbInfo.db=null,$e._dbInfo.version=he}var Ye=new g(function(je,ot){var at=f.open(b.name,he);at.onerror=function(Pe){var Bn=at.result;Bn.close(),ot(Pe)},at.onupgradeneeded=function(){var Pe=at.result;Pe.deleteObjectStore(b.storeName)},at.onsuccess=function(){var Pe=at.result;Pe.close(),je(Pe)}});return Ye.then(function(je){de.db=je;for(var ot=0;ot<be.length;ot++){var at=be[ot];at._dbInfo.db=je,$(at._dbInfo)}}).catch(function(je){throw(H(b,je)||g.resolve()).catch(function(){}),je})}}):q=J.then(function(oe){ge(b);var he=ae[b.name],de=he.forages;oe.close();for(var be=0;be<de.length;be++){var Te=de[be];Te._dbInfo.db=null}var $e=new g(function(Ye,je){var ot=f.deleteDatabase(b.name);ot.onerror=function(){var at=ot.result;at&&at.close(),je(ot.error)},ot.onblocked=function(){console.warn('dropInstance blocked for database "'+b.name+'" until all open connections are closed')},ot.onsuccess=function(){var at=ot.result;at&&at.close(),Ye(at)}});return $e.then(function(Ye){he.db=Ye;for(var je=0;je<de.length;je++){var ot=de[je];$(ot._dbInfo)}}).catch(function(Ye){throw(H(b,Ye)||g.resolve()).catch(function(){}),Ye})})}return w(q,R),q}var Xn={_driver:"asyncStorage",_initStorage:ke,_support:p(),iterate:Ce,getItem:ye,setItem:Me,removeItem:Ve,clear:Ue,length:ut,key:Be,keys:Zn,dropInstance:Ge};function Qs(){return typeof openDatabase=="function"}var gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eo="~~local_forage_type~",Ti=/^~~local_forage_type~([^~]+)~/,dr="__lfsc__:",Vr=dr.length,Jn="arbf",Rt="blob",Gr="si08",kn="ui08",Yr="uic8",Sn="si16",mt="si32",Yt="ur16",pr="ui32",An="fl32",yr="fl64",Qn=Vr+Jn.length,Zt=Object.prototype.toString;function er(b){var R=b.length*.75,k=b.length,D,q=0,L,J,oe,he;b[b.length-1]==="="&&(R--,b[b.length-2]==="="&&R--);var de=new ArrayBuffer(R),be=new Uint8Array(de);for(D=0;D<k;D+=4)L=gt.indexOf(b[D]),J=gt.indexOf(b[D+1]),oe=gt.indexOf(b[D+2]),he=gt.indexOf(b[D+3]),be[q++]=L<<2|J>>4,be[q++]=(J&15)<<4|oe>>2,be[q++]=(oe&3)<<6|he&63;return de}function tr(b){var R=new Uint8Array(b),k="",D;for(D=0;D<R.length;D+=3)k+=gt[R[D]>>2],k+=gt[(R[D]&3)<<4|R[D+1]>>4],k+=gt[(R[D+1]&15)<<2|R[D+2]>>6],k+=gt[R[D+2]&63];return R.length%3===2?k=k.substring(0,k.length-1)+"=":R.length%3===1&&(k=k.substring(0,k.length-2)+"=="),k}function zt(b,R){var k="";if(b&&(k=Zt.call(b)),b&&(k==="[object ArrayBuffer]"||b.buffer&&Zt.call(b.buffer)==="[object ArrayBuffer]")){var D,q=dr;b instanceof ArrayBuffer?(D=b,q+=Jn):(D=b.buffer,k==="[object Int8Array]"?q+=Gr:k==="[object Uint8Array]"?q+=kn:k==="[object Uint8ClampedArray]"?q+=Yr:k==="[object Int16Array]"?q+=Sn:k==="[object Uint16Array]"?q+=Yt:k==="[object Int32Array]"?q+=mt:k==="[object Uint32Array]"?q+=pr:k==="[object Float32Array]"?q+=An:k==="[object Float64Array]"?q+=yr:R(new Error("Failed to get type for BinaryArray"))),R(q+tr(D))}else if(k==="[object Blob]"){var L=new FileReader;L.onload=function(){var J=eo+b.type+"~"+tr(this.result);R(dr+Rt+J)},L.readAsArrayBuffer(b)}else try{R(JSON.stringify(b))}catch(J){console.error("Couldn't convert value into a JSON string: ",b),R(null,J)}}function Le(b){if(b.substring(0,Vr)!==dr)return JSON.parse(b);var R=b.substring(Qn),k=b.substring(Vr,Qn),D;if(k===Rt&&Ti.test(R)){var q=R.match(Ti);D=q[1],R=R.substring(q[0].length)}var L=er(R);switch(k){case Jn:return L;case Rt:return d([L],{type:D});case Gr:return new Int8Array(L);case kn:return new Uint8Array(L);case Yr:return new Uint8ClampedArray(L);case Sn:return new Int16Array(L);case Yt:return new Uint16Array(L);case mt:return new Int32Array(L);case pr:return new Uint32Array(L);case An:return new Float32Array(L);case yr:return new Float64Array(L);default:throw new Error("Unkown type: "+k)}}var hn={serialize:zt,deserialize:Le,stringToBuffer:er,bufferToString:tr};function Xt(b,R,k,D){b.executeSql("CREATE TABLE IF NOT EXISTS "+R.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],k,D)}function gr(b){var R=this,k={db:null};if(b)for(var D in b)k[D]=typeof b[D]!="string"?b[D].toString():b[D];var q=new g(function(L,J){try{k.db=openDatabase(k.name,String(k.version),k.description,k.size)}catch(oe){return J(oe)}k.db.transaction(function(oe){Xt(oe,k,function(){R._dbInfo=k,L()},function(he,de){J(de)})},J)});return k.serializer=hn,q}function Se(b,R,k,D,q,L){b.executeSql(k,D,q,function(J,oe){oe.code===oe.SYNTAX_ERR?J.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[R.storeName],function(he,de){de.rows.length?L(he,oe):Xt(he,R,function(){he.executeSql(k,D,q,L)},L)},L):L(J,oe)},L)}function Zr(b,R){var k=this;b=A(b);var D=new g(function(q,L){k.ready().then(function(){var J=k._dbInfo;J.db.transaction(function(oe){Se(oe,J,"SELECT * FROM "+J.storeName+" WHERE key = ? LIMIT 1",[b],function(he,de){var be=de.rows.length?de.rows.item(0).value:null;be&&(be=J.serializer.deserialize(be)),q(be)},function(he,de){L(de)})})}).catch(L)});return w(D,R),D}function Ii(b,R){var k=this,D=new g(function(q,L){k.ready().then(function(){var J=k._dbInfo;J.db.transaction(function(oe){Se(oe,J,"SELECT * FROM "+J.storeName,[],function(he,de){for(var be=de.rows,Te=be.length,$e=0;$e<Te;$e++){var Ye=be.item($e),je=Ye.value;if(je&&(je=J.serializer.deserialize(je)),je=b(je,Ye.key,$e+1),je!==void 0){q(je);return}}q()},function(he,de){L(de)})})}).catch(L)});return w(D,R),D}function mr(b,R,k,D){var q=this;b=A(b);var L=new g(function(J,oe){q.ready().then(function(){R===void 0&&(R=null);var he=R,de=q._dbInfo;de.serializer.serialize(R,function(be,Te){Te?oe(Te):de.db.transaction(function($e){Se($e,de,"INSERT OR REPLACE INTO "+de.storeName+" (key, value) VALUES (?, ?)",[b,be],function(){J(he)},function(Ye,je){oe(je)})},function($e){if($e.code===$e.QUOTA_ERR){if(D>0){J(mr.apply(q,[b,he,k,D-1]));return}oe($e)}})})}).catch(oe)});return w(L,k),L}function Bi(b,R,k){return mr.apply(this,[b,R,k,1])}function Xr(b,R){var k=this;b=A(b);var D=new g(function(q,L){k.ready().then(function(){var J=k._dbInfo;J.db.transaction(function(oe){Se(oe,J,"DELETE FROM "+J.storeName+" WHERE key = ?",[b],function(){q()},function(he,de){L(de)})})}).catch(L)});return w(D,R),D}function to(b){var R=this,k=new g(function(D,q){R.ready().then(function(){var L=R._dbInfo;L.db.transaction(function(J){Se(J,L,"DELETE FROM "+L.storeName,[],function(){D()},function(oe,he){q(he)})})}).catch(q)});return w(k,b),k}function no(b){var R=this,k=new g(function(D,q){R.ready().then(function(){var L=R._dbInfo;L.db.transaction(function(J){Se(J,L,"SELECT COUNT(key) as c FROM "+L.storeName,[],function(oe,he){var de=he.rows.item(0).c;D(de)},function(oe,he){q(he)})})}).catch(q)});return w(k,b),k}function Rn(b,R){var k=this,D=new g(function(q,L){k.ready().then(function(){var J=k._dbInfo;J.db.transaction(function(oe){Se(oe,J,"SELECT key FROM "+J.storeName+" WHERE id = ? LIMIT 1",[b+1],function(he,de){var be=de.rows.length?de.rows.item(0).key:null;q(be)},function(he,de){L(de)})})}).catch(L)});return w(D,R),D}function Cn(b){var R=this,k=new g(function(D,q){R.ready().then(function(){var L=R._dbInfo;L.db.transaction(function(J){Se(J,L,"SELECT key FROM "+L.storeName,[],function(oe,he){for(var de=[],be=0;be<he.rows.length;be++)de.push(he.rows.item(be).key);D(de)},function(oe,he){q(he)})})}).catch(q)});return w(k,b),k}function Jr(b){return new g(function(R,k){b.transaction(function(D){D.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(q,L){for(var J=[],oe=0;oe<L.rows.length;oe++)J.push(L.rows.item(oe).name);R({db:b,storeNames:J})},function(q,L){k(L)})},function(D){k(D)})})}function wr(b,R){R=I.apply(this,arguments);var k=this.config();b=typeof b!="function"&&b||{},b.name||(b.name=b.name||k.name,b.storeName=b.storeName||k.storeName);var D=this,q;return b.name?q=new g(function(L){var J;b.name===k.name?J=D._dbInfo.db:J=openDatabase(b.name,"","",0),b.storeName?L({db:J,storeNames:[b.storeName]}):L(Jr(J))}).then(function(L){return new g(function(J,oe){L.db.transaction(function(he){function de(Ye){return new g(function(je,ot){he.executeSql("DROP TABLE IF EXISTS "+Ye,[],function(){je()},function(at,Pe){ot(Pe)})})}for(var be=[],Te=0,$e=L.storeNames.length;Te<$e;Te++)be.push(de(L.storeNames[Te]));g.all(be).then(function(){J()}).catch(function(Ye){oe(Ye)})},function(he){oe(he)})})}):q=g.reject("Invalid arguments"),w(q,R),q}var et={_driver:"webSQLStorage",_initStorage:gr,_support:Qs(),iterate:Ii,getItem:Zr,setItem:Bi,removeItem:Xr,clear:to,length:no,key:Rn,keys:Cn,dropInstance:wr};function ft(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function Li(b,R){var k=b.name+"/";return b.storeName!==R.storeName&&(k+=b.storeName+"/"),k}function vr(){var b="_localforage_support_test";try{return localStorage.setItem(b,!0),localStorage.removeItem(b),!1}catch{return!0}}function br(){return!vr()||localStorage.length>0}function Er(b){var R=this,k={};if(b)for(var D in b)k[D]=b[D];return k.keyPrefix=Li(b,R._defaultConfig),br()?(R._dbInfo=k,k.serializer=hn,g.resolve()):g.reject()}function ro(b){var R=this,k=R.ready().then(function(){for(var D=R._dbInfo.keyPrefix,q=localStorage.length-1;q>=0;q--){var L=localStorage.key(q);L.indexOf(D)===0&&localStorage.removeItem(L)}});return w(k,b),k}function Jt(b,R){var k=this;b=A(b);var D=k.ready().then(function(){var q=k._dbInfo,L=localStorage.getItem(q.keyPrefix+b);return L&&(L=q.serializer.deserialize(L)),L});return w(D,R),D}function Tn(b,R){var k=this,D=k.ready().then(function(){for(var q=k._dbInfo,L=q.keyPrefix,J=L.length,oe=localStorage.length,he=1,de=0;de<oe;de++){var be=localStorage.key(de);if(be.indexOf(L)===0){var Te=localStorage.getItem(be);if(Te&&(Te=q.serializer.deserialize(Te)),Te=b(Te,be.substring(J),he++),Te!==void 0)return Te}}});return w(D,R),D}function Qt(b,R){var k=this,D=k.ready().then(function(){var q=k._dbInfo,L;try{L=localStorage.key(b)}catch{L=null}return L&&(L=L.substring(q.keyPrefix.length)),L});return w(D,R),D}function xr(b){var R=this,k=R.ready().then(function(){for(var D=R._dbInfo,q=localStorage.length,L=[],J=0;J<q;J++){var oe=localStorage.key(J);oe.indexOf(D.keyPrefix)===0&&L.push(oe.substring(D.keyPrefix.length))}return L});return w(k,b),k}function io(b){var R=this,k=R.keys().then(function(D){return D.length});return w(k,b),k}function en(b,R){var k=this;b=A(b);var D=k.ready().then(function(){var q=k._dbInfo;localStorage.removeItem(q.keyPrefix+b)});return w(D,R),D}function Mi(b,R,k){var D=this;b=A(b);var q=D.ready().then(function(){R===void 0&&(R=null);var L=R;return new g(function(J,oe){var he=D._dbInfo;he.serializer.serialize(R,function(de,be){if(be)oe(be);else try{localStorage.setItem(he.keyPrefix+b,de),J(L)}catch(Te){(Te.name==="QuotaExceededError"||Te.name==="NS_ERROR_DOM_QUOTA_REACHED")&&oe(Te),oe(Te)}})})});return w(q,k),q}function dn(b,R){if(R=I.apply(this,arguments),b=typeof b!="function"&&b||{},!b.name){var k=this.config();b.name=b.name||k.name,b.storeName=b.storeName||k.storeName}var D=this,q;return b.name?q=new g(function(L){b.storeName?L(Li(b,D._defaultConfig)):L(b.name+"/")}).then(function(L){for(var J=localStorage.length-1;J>=0;J--){var oe=localStorage.key(J);oe.indexOf(L)===0&&localStorage.removeItem(oe)}}):q=g.reject("Invalid arguments"),w(q,R),q}var Oi={_driver:"localStorageWrapper",_initStorage:Er,_support:ft(),iterate:Tn,getItem:Jt,setItem:Mi,removeItem:en,clear:ro,length:io,key:Qt,keys:xr,dropInstance:dn},Qr=function(R,k){return R===k||typeof R=="number"&&typeof k=="number"&&isNaN(R)&&isNaN(k)},st=function(R,k){for(var D=R.length,q=0;q<D;){if(Qr(R[q],k))return!0;q++}return!1},tn=Array.isArray||function(b){return Object.prototype.toString.call(b)==="[object Array]"},_t={},ei={},Ht={INDEXEDDB:Xn,WEBSQL:et,LOCALSTORAGE:Oi},ti=[Ht.INDEXEDDB._driver,Ht.WEBSQL._driver,Ht.LOCALSTORAGE._driver],In=["dropInstance"],qt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(In),Di={description:"",driver:ti.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function _r(b,R){b[R]=function(){var k=arguments;return b.ready().then(function(){return b[R].apply(b,k)})}}function kr(){for(var b=1;b<arguments.length;b++){var R=arguments[b];if(R)for(var k in R)R.hasOwnProperty(k)&&(tn(R[k])?arguments[0][k]=R[k].slice():arguments[0][k]=R[k])}return arguments[0]}var qe=(function(){function b(R){c(this,b);for(var k in Ht)if(Ht.hasOwnProperty(k)){var D=Ht[k],q=D._driver;this[k]=q,_t[q]||this.defineDriver(D)}this._defaultConfig=kr({},Di),this._config=kr({},this._defaultConfig,R),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return b.prototype.config=function(k){if((typeof k>"u"?"undefined":o(k))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var D in k){if(D==="storeName"&&(k[D]=k[D].replace(/\W/g,"_")),D==="version"&&typeof k[D]!="number")return new Error("Database version must be a number.");this._config[D]=k[D]}return"driver"in k&&k.driver?this.setDriver(this._config.driver):!0}else return typeof k=="string"?this._config[k]:this._config},b.prototype.defineDriver=function(k,D,q){var L=new g(function(J,oe){try{var he=k._driver,de=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!k._driver){oe(de);return}for(var be=qt.concat("_initStorage"),Te=0,$e=be.length;Te<$e;Te++){var Ye=be[Te],je=!st(In,Ye);if((je||k[Ye])&&typeof k[Ye]!="function"){oe(de);return}}var ot=function(){for(var Bn=function(Sr){return function(){var nn=new Error("Method "+Sr+" is not implemented by the current driver"),ri=g.reject(nn);return w(ri,arguments[arguments.length-1]),ri}},ni=0,so=In.length;ni<so;ni++){var pt=In[ni];k[pt]||(k[pt]=Bn(pt))}};ot();var at=function(Bn){_t[he]&&console.info("Redefining LocalForage driver: "+he),_t[he]=k,ei[he]=Bn,J()};"_support"in k?k._support&&typeof k._support=="function"?k._support().then(at,oe):at(!!k._support):at(!0)}catch(Pe){oe(Pe)}});return x(L,D,q),L},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(k,D,q){var L=_t[k]?g.resolve(_t[k]):g.reject(new Error("Driver not found."));return x(L,D,q),L},b.prototype.getSerializer=function(k){var D=g.resolve(hn);return x(D,k),D},b.prototype.ready=function(k){var D=this,q=D._driverSet.then(function(){return D._ready===null&&(D._ready=D._initDriver()),D._ready});return x(q,k,k),q},b.prototype.setDriver=function(k,D,q){var L=this;tn(k)||(k=[k]);var J=this._getSupportedDrivers(k);function oe(){L._config.driver=L.driver()}function he(Te){return L._extend(Te),oe(),L._ready=L._initStorage(L._config),L._ready}function de(Te){return function(){var $e=0;function Ye(){for(;$e<Te.length;){var je=Te[$e];return $e++,L._dbInfo=null,L._ready=null,L.getDriver(je).then(he).catch(Ye)}oe();var ot=new Error("No available storage method found.");return L._driverSet=g.reject(ot),L._driverSet}return Ye()}}var be=this._driverSet!==null?this._driverSet.catch(function(){return g.resolve()}):g.resolve();return this._driverSet=be.then(function(){var Te=J[0];
3return L._dbInfo=null,L._ready=null,L.getDriver(Te).then(function($e){L._driver=$e._driver,oe(),L._wrapLibraryMethodsWithReady(),L._initDriver=de(J)})}).catch(function(){oe();var Te=new Error("No available storage method found.");return L._driverSet=g.reject(Te),L._driverSet}),x(this._driverSet,D,q),this._driverSet},b.prototype.supports=function(k){return!!ei[k]},b.prototype._extend=function(k){kr(this,k)},b.prototype._getSupportedDrivers=function(k){for(var D=[],q=0,L=k.length;q<L;q++){var J=k[q];this.supports(J)&&D.push(J)}return D},b.prototype._wrapLibraryMethodsWithReady=function(){for(var k=0,D=qt.length;k<D;k++)_r(this,qt[k])},b.prototype.createInstance=function(k){return new b(k)},b})(),Ni=new qe;i.exports=Ni},{3:3}]},{},[4])(4)})})(ra)),ra.exports}var X1=Z1(),J1=js(X1);const Q1="iris-client-blocks",ex=new Y1(Q1);J1.createInstance({name:"iris-client-file-outbox"});const vl=new TextEncoder,os=new TextDecoder;class tx{tree;order;maxKeys;constructor(e,n={}){this.tree=new od({store:e}),this.order=n.order??32,this.maxKeys=this.order-1}async insert(e,n,r){if(!e)return this.createLeaf([[n,r]]);const i=await this.insertRecursive(e,n,r);return i.unchanged?e:i.split?(await this.tree.putDirectory([Pt(Ct(i.split.leftFirstKey),i.split.left,0,se.Dir),Pt(Ct(i.split.rightFirstKey),i.split.right,0,se.Dir)])).cid:i.cid}async get(e,n){if(!e)return null;const r=await this.tree.listDirectory(e);if(this.isLeafNode(r)){const o=Ct(n),c=r.find(f=>f.name===o);if(!c||c.type!==se.Blob)return null;const u=await this.tree.readFile(c.cid);return u?os.decode(u):null}const{child:s}=this.findChild(r,n);return this.get(s.cid,n)}async insertLink(e,n,r,i={}){if(!e)return this.createLeafWithLink([[n,r]]);const s=await this.insertLinkRecursive(e,n,r,i.signal);return s.unchanged?e:s.split?(await this.tree.putDirectory([Pt(Ct(s.split.leftFirstKey),s.split.left,s.split.leftCount,se.Dir),Pt(Ct(s.split.rightFirstKey),s.split.right,s.split.rightCount,se.Dir)])).cid:s.cid}async getLink(e,n,r={}){if(!e)return null;const i=await this.tree.listDirectory(e,r.signal);if(this.isLeafNode(i)){const c=Ct(n),u=i.find(f=>f.name===c);return!u||u.type!==se.File?null:u.cid}const{child:o}=this.findChild(i,n);return this.getLink(o.cid,n,r)}async*linksEntries(e,n={}){if(e){if(n.verifyCount===!0){yield*this.verifiedLinksEntries(e);return}yield*this.traverseLinksInOrder(e)}}async*verifiedLinksEntries(e){if(!e)return;const n=await this.countReportedLinks(e),r=yield*this.traverseLinksInOrderVerified(e,n);if(n!==null&&r!==n)throw new Error(`BTree link traversal yielded ${r} links, expected ${n}`)}async*prefixLinks(e,n){const r=El(n);yield*this.rangeLinkTraverse(e,n,r)}async countLinks(e){return await this.scanLinks(e)}async scanLinks(e){return e?await this.countLinksRecursive(e,as()):0}async scanLinkCount(e){return await this.scanLinks(e)}async countStoredLinks(e){if(!e)return 0;const n=await this.tree.listDirectory(e);if(this.isLeafNode(n))return this.countLinkEntries(n);let r=0;for(const i of n){const s=this.storedLinkSubtreeCount(i);if(s===null)return null;r+=s}return r}async countReportedLinks(e){return await this.countStoredLinks(e)}async getLinkEntryAt(e,n){return!e||n<0?null:await this.getLinkEntryAtRecursive(e,Math.floor(n),as())}async sampleLinks(e,n,r={}){if(!e)return[];const i=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;if(i===0)return[];const s=as(),o=Number.isFinite(r.totalCount)?Math.max(0,Math.floor(r.totalCount??0)):await this.countLinksRecursive(e,s);if(o===0)return[];const c=Math.min(o,i),u=nx(o,c,r.random??Math.random),f=[];for(const p of u){const d=await this.getLinkEntryAtRecursive(e,p,s);d&&f.push(d)}return f}async mergeLinks(e,n,r=!1){if(!n)return e;if(!e)return n;let i=e;for await(const[s,o]of this.linksEntries(n))(await this.getLink(i,s)===null||r)&&(i=await this.insertLink(i,s,o));return i}async build(e){return this.buildTree(e,n=>this.createLeaf(n),!1)}async buildLinks(e){return this.buildTree(e,n=>this.createLeafWithLink(n),!0)}async buildSortedAsync(e){const n=[],r=[],i=async(c,u)=>{const f=n[c]??[];if(n[c]=f,f.push(u),f.length<=this.maxKeys)return;const p=f.splice(0,this.maxKeys);await i(c+1,{firstKey:p[0].firstKey,cid:await this.createInternalNode(p),count:p.reduce((d,g)=>d+g.count,0)})},s=async()=>
3{if(r.length===0)return;const c=r.splice(0,this.maxKeys);await i(0,{firstKey:c[0][0],cid:await this.createLeaf(c),count:0})};let o;for await(const c of e){const[u]=c;if(o!==void 0&&Ft(o,u)>=0)throw new Error("Sorted BTree entries must have strictly increasing unique keys");o=u,r.push(c),r.length>this.maxKeys&&await s()}await s();for(let c=0;c<n.length;c+=1){const u=n[c];if(!u||u.length===0)continue;if(!n.slice(c+1).some(d=>d.length>0))return u.length===1?u[0].cid:await this.createInternalNode(u);const p=u.splice(0);await i(c+1,{firstKey:p[0].firstKey,cid:await this.createInternalNode(p),count:p.reduce((d,g)=>d+g.count,0)})}return null}async buildTree(e,n,r){const i=[...e];if(i.length===0)return null;i.sort((c,u)=>Ft(c[0],u[0]));const s=[];for(const[c,u]of i){const f=s[s.length-1];if(f&&f[0]===c){f[1]=u;continue}s.push([c,u])}let o=[];for(let c=0;c<s.length;c+=this.maxKeys){const u=s.slice(c,c+this.maxKeys);o.push({firstKey:u[0][0],cid:await n(u),count:r?u.length:0})}for(;o.length>1;){const c=[];for(let u=0;u<o.length;u+=this.maxKeys){const f=o.slice(u,u+this.maxKeys);c.push({firstKey:f[0].firstKey,cid:await this.createInternalNode(f),count:f.reduce((p,d)=>p+d.count,0)})}o=c}return o[0]?.cid??null}cidEquals(e,n){return e.hash.length!==n.hash.length||!e.hash.every((r,i)=>r===n.hash[i])?!1:!e.key&&!n.key?!0:!e.key||!n.key||e.key.length!==n.key.length?!1:e.key.every((r,i)=>r===n.key[i])}async createLeafWithLink(e){return(await this.tree.putDirectory(e.map(([n,r])=>Pt(Ct(n),r,0,se.File)))).cid}async insertLinkRecursive(e,n,r,i){const s=await this.tree.listDirectory(e,i);return this.isLeafNode(s)?this.insertLinkIntoLeaf(e,s,n,r):this.insertIntoInternal(e,s,n,c=>this.insertLinkRecursive(c,n,r,i),!0)}async insertLinkIntoLeaf(e,n,r,i){const s=Ct(r),o=n.find(f=>f.name===s);if(o?.type===se.File&&this.cidEquals(o.cid,i))return{cid:e,unchanged:!0};const c=this.sortEntries([...n.filter(f=>f.name!==s),Pt(s,i,0,se.File)]),u=(await this.tree.putDirectory(c)).cid;if(c.length>this.maxKeys){const f=await this.splitLeafWithLinks(c);return{cid:u,count:f.leftCount+f.rightCount,split:f}}return{cid:u,count:this.countLinkEntries(c)}}async insertIntoInternal(e,n,r,i,s){const{child:o}=this.findChild(n,r),c=await i(o.cid);if(c.unchanged)return{cid:e,unchanged:!0};const u=n.filter(d=>d.name!==o.name);c.split?u.push(Pt(Ct(c.split.leftFirstKey),c.split.left,c.split.leftCount,se.Dir),Pt(Ct(c.split.rightFirstKey),c.split.right,c.split.rightCount,se.Dir)):u.push(Pt(o.name,c.cid,s?c.count:0,se.Dir));const f=this.sortEntries(u),p=(await this.tree.putDirectory(f)).cid;if(f.length>this.maxKeys){const d=await this.splitInternal(f,s);return{cid:p,count:d.leftCount+d.rightCount,split:d}}return{cid:p,count:s?await this.countLinkEntriesOrSubtrees(f):0}}async splitLeafWithLinks(e){const n=this.sortEntries(e),r=Math.floor(n.length/2),i=n.slice(0,r),s=n.slice(r),o=(await this.tree.putDirectory(i)).cid,c=(await this.tree.putDirectory(s)).cid;return{left:o,right:c,leftFirstKey:ht(i[0].name),rightFirstKey:ht(s[0].name),leftCount:this.countLinkEntries(i),rightCount:this.countLinkEntries(s)}}async*traverseLinksInOrder(e){const n=await this.tree.listDirectory(e),r=this.isLeafNode(n),i=this.sortEntries(n);if(r)for(const s of i)s.type===se.File&&(yield[ht(s.name),s.cid]);else for(const s of i)yield*this.traverseLinksInOrder(s.cid)}async*traverseLinksInOrderVerified(e,n){const r=await this.tree.listDirectory(e),i=this.isLeafNode(r),s=this.sortEntries(r);let o=0;if(i)for(const c of s)c.type===se.File&&(o+=1,yield[ht(c.name),c.cid]);else for(const c of s){const u=this.storedLinkSubtreeCount(c),f=yield*this.traverseLinksInOrderVerified(c.cid,u);if(u!==null&&f!==u)throw new Error(`BTree link subtree ${He(c.cid.hash)} yielded ${f} links, expected ${u}`);o+=f}if(n!==null&&o!==n)throw new Error(`BTree link subtree ${He(e.hash)} yielded ${o} links, expected ${n}`);return o}async*rangeLinkTraverse(e,n,r){const i=await this.tree.listDirectory(e),s=this.isLeafNode(i),o=this.sortEntries(i);if(s)for(const c of o){if(c.type!==se.File)continue;const u=ht(c.name);if(!(n!==void 0&&Ft(u,n)<0)){if(r!==void 0&&Ft(u,r)>=0)return;yield[u,c.cid]}}else for(let c=0;c<o.length;c++){const u=o[c],f=ht(u.name),p=c<o.length-1?ht(o[c+1].name):void 0;if(!(n!==void 0&&p!==void 0&&Ft(p,n)<=0)){if(r!==void 0&&Ft(f,r)>=0)return;yield*this.rangeLinkTraverse(u.cid,n,r)}}}async countLinksRecursive(e,n){const r=bl(e),i=n.counts.get(r);if(i!==void 0)return i;const s=await this.listCachedEntries(e,n),o=this.isLeafNode(s)?this.countLinkEntries(s):(await Promise.all(s.map(async c=>this.storedLinkSubtreeCount(c)??await this.countLinksRecursive(c.cid,n)))).reduce((c,u)=>c+u,0);return n.counts.set(r,o),o}countLinkEntries(e){return e.filter(n=>n.type===se.File).length}storedLinkSubtreeCount(e){return e.type!==se.Dir||!Number.isFinite(e.size)||e.size<=0?null:Math.floor(e.size)}async countLinkEntriesOrSubtrees(e){return this.isLeafNode(e)?this.countLinkEntries(e):(await Promise.all(e.map(async r=>this.storedLinkSubtreeCount(r)??await this.countLinksRecursive(r.cid,as())))).reduce((r,i)=>r+i,0)}async getLinkEntryAtRecursive(e,n,r){const i=await this.listCachedEntries(e,r);if(this.isLeafNode(i)){const c=i.filter(u=>u.type===se.File)[n];return c?[ht(c.name),c.cid]:null}let s=n;for(const o of i){const c=this.storedLinkSubtreeCount(o)??await this.countLinksRecursive(o.cid,r);if(s<c)return await this.getLinkEntryAtRecursive(o.cid,s,r);s-=c}return null}async listCachedEntries(e,n){const r=bl(e),i=n.entries.get(r);if(i)return i;const s=this.sortEntries(await this.tree.listDirectory(e));return n.entries.set(r,s),s}async insertRecursive(e,n,r){const i=await this.tree.listDirectory(e);return this.isLeafNode(i)?this.insertIntoLeaf(e,i,n,r):this.insertIntoInternal(e,i,n,o=>this.insertRecursive(o,n,r),!1)}async insertIntoLeaf(e,n,r,i){const s=Ct(r),o=n.find(d=>d.name===s);if(o?.type===se.Blob){const d=await this.tree.readFile(o.cid);if(d&&os.decode(d)===i)return{cid:e,unchanged:!0}}const{cid:c,size:u}=await this.tree.putFile(vl.encode(i)),f=this.sortEntries([...n.filter(d=>
3d.name!==s),Pt(s,c,u,se.Blob)]),p=(await this.tree.putDirectory(f)).cid;return f.length>this.maxKeys?{cid:p,count:0,split:await this.splitLeaf(f)}:{cid:p,count:0}}async splitLeaf(e){const n=this.sortEntries(e),r=Math.floor(n.length/2),i=n.slice(0,r),s=n.slice(r),o=(await this.tree.putDirectory(i.map(u=>({...u,type:se.Blob})))).cid,c=(await this.tree.putDirectory(s.map(u=>({...u,type:se.Blob})))).cid;return{left:o,right:c,leftFirstKey:ht(i[0].name),rightFirstKey:ht(s[0].name),leftCount:0,rightCount:0}}async splitInternal(e,n=!1){const r=this.sortEntries(e),i=Math.floor(r.length/2),s=r.slice(0,i),o=r.slice(i),c=n?await this.countLinkEntriesOrSubtrees(s):0,u=n?await this.countLinkEntriesOrSubtrees(o):0,f=(await this.tree.putDirectory(s.map(d=>({...d,size:n?d.size:0,type:se.Dir})))).cid,p=(await this.tree.putDirectory(o.map(d=>({...d,size:n?d.size:0,type:se.Dir})))).cid;return{left:f,right:p,leftFirstKey:ht(s[0].name),rightFirstKey:ht(o[0].name),leftCount:c,rightCount:u}}findChild(e,n){const r=this.sortEntries(e);for(let i=0;i<r.length-1;i++){const s=ht(r[i+1].name);if(Ft(n,s)<0)return{child:r[i],childIndex:i}}return{child:r[r.length-1],childIndex:r.length-1}}sortEntries(e){return[...e].sort((n,r)=>Ft(ht(n.name),ht(r.name)))}isLeafNode(e){return e.length===0||e.some(n=>n.type!==se.Dir)}async createLeaf(e){const n=[];for(const[r,i]of e){const{cid:s,size:o}=await this.tree.putFile(vl.encode(i));n.push(Pt(Ct(r),s,o,se.Blob))}return(await this.tree.putDirectory(n)).cid}async createInternalNode(e){const n=e.map(r=>Pt(Ct(r.firstKey),r.cid,r.count,se.Dir));return(await this.tree.putDirectory(n)).cid}async delete(e,n){const r=await this.tree.listDirectory(e);if(this.isLeafNode(r)){const c=Ct(n);if(!r.find(d=>d.name===c))return e;const f=await this.tree.removeEntry(e,[],c);return(await this.tree.listDirectory(f)).length===0?null:f}const{child:s}=this.findChild(r,n),o=await this.delete(s.cid,n);if(!o){const c=await this.tree.removeEntry(e,[],s.name),u=await this.tree.listDirectory(c);return u.length===0?null:u.length===1&&u[0].type===se.Dir?u[0].cid:c}return o===s.cid?e:this.tree.setEntry(e,[],s.name,o,0,se.Dir)}async*entries(e){e&&(yield*this.traverseInOrder(e))}async*traverseInOrder(e){const n=await this.tree.listDirectory(e),r=this.isLeafNode(n),i=this.sortEntries(n);if(r)for(const s of i){if(s.type!==se.Blob)continue;const o=await this.tree.readFile(s.cid);o&&(yield[ht(s.name),os.decode(o)])}else for(const s of i)yield*this.traverseInOrder(s.cid)}async*range(e,n,r){yield*this.rangeTraverse(e,n,r)}async*rangeTraverse(e,n,r){const i=await this.tree.listDirectory(e),s=this.isLeafNode(i),o=this.sortEntries(i);if(s)for(const c of o){if(c.type!==se.Blob)continue;const u=ht(c.name);if(n!==void 0&&Ft(u,n)<0)continue;if(r!==void 0&&Ft(u,r)>=0)return;const f=await this.tree.readFile(c.cid);f&&(yield[u,os.decode(f)])}else for(let c=0;c<o.length;c++){const u=o[c],f=ht(u.name),p=c<o.length-1?ht(o[c+1].name):void 0;if(!(n!==void 0&&p!==void 0&&Ft(p,n)<=0)){if(r!==void 0&&Ft(f,r)>=0)return;yield*this.rangeTraverse(u.cid,n,r)}}}async*prefix(e,n){const r=El(n);yield*this.range(e,n,r)}async merge(e,n,r=!1){if(!n)return e;if(!e)return n;let i=e;for await(const[s,o]of this.entries(n))(await this.get(i,s)===null||r)&&(i=await this.insert(i,s,o));return i}}function Pt(t,e,n,r){return{name:t,cid:e,size:n,type:r}}function Ct(t){return t.replace(/%/g,"%25").replace(/\//g,"%2F").replace(/\0/g,"%00")}function as(){return{entries:new Map,counts:new Map}}function bl(t){return`${He(t.hash)}:${t.key?He(t.key):""}`}function nx(t,e,n){const r=Number.isFinite(t)?Math.max(0,Math.floor(t)):0,i=Number.isFinite(e)?Math.min(r,Math.max(0,Math.floor(e))):r;if(r===0||i===0)return[];if(i>=r)return ia(Array.from({length:r},(u,f)=>f),n);const s=new Set;let o=0;const c=Math.max(i*8,32);for(;s.size<i&&o<c;)s.add(Math.floor(n()*r)),o+=1;if(s.size<i){const u=[];for(let f=0;f<r;f+=1)s.has(f)||u.push(f);for(const f of ia(u,n))if(s.add(f),s.size>=i)break}return ia([...s],n)}function ia(t,e){const n=[...t];for(let r=n.length-1;r>0;r-=1){const i=Math.floor(e()*(r+1));[n[r],n[i]]=[n[i],n[r]]}return n}function ht(t){return t.replace(/%2F/gi,"/").replace(/%00/gi,"\0").replace(/%25/g,"%")}function Ft(t,e){return t<e?-1:t>e?1:0}function El(t){if(t.length===0)return t;const e=t.charCodeAt(t.length-1);return t.slice(0,-1)+String.fromCharCode(e+1)}const rx=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","is","it","as","be","was","are","this","that","these","those","i","you","he","she","we","they","my","your","his","her","its","our","their","what","which","who","whom","how","when","where","why","will","would","could","should","can","may","might","must","have","has","had","do","does","did","been","being","get","got","just","now","then","so","if","not","no","yes","all","any","some","more","most","other","into","over","after","before","about","up","down","out","off","through","during","under","again","further","once"]),ix=2;class sx{btree;stopWords;minKeywordLength;constructor(e,n={}){this.btree=new tx(e,{order:n.order??64}),this.stopWords=n.stopWords??rx,this.minKeywordLength=n.minKeywordLength??ix}parseKeywords(e){if(!e)return[];const n=[],r=new Set;for(const i of e.split(/[^\p{L}\p{N}]+/u))if(i)for(const s of this.expandKeywordVariants(i))s.length>=this.minKeywordLength&&!this.stopWords.has(s)&&!this.isPureNumber(s)&&!r.has(s)&&(r.add(s),n.push(s));return n}expandKeywordVariants(e){const n=new Set,r=e.toLowerCase();r&&n.add(r);const i=e.replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2").replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu,"$1 $2").replace(new RegExp("([\\p{L}])(\\p{N})","gu"),"$1 $2").replace(new RegExp("(\\p{N})([\\p{L}])","gu"),"$1 $2");for(const s of i.split(/\s+/)){const o=s.toLowerCase();o&&n.add(o)}return[...n]}isPureNumber(e){return!(!/^\d+$/.test(e)||/^(19|20)\d{2}$/.test(e))}async index(e,n,r,i,s){let o=e;for(const c of r){const u=`${n}${c}:${i}`;try{o=await this.btree.insert(o,u,s)}catch(f){console.error("Failed to index term:",c,f)}}return o}async search(e,n,r,i={}){return await this.searchTerms(e,n,this.parseKeywords(r),i)}async searchTerms(e,n,r,i={}){if(!e)return[];const s=xl(i.limit);if(s===0)return[];const o=kl(r);
3if(o.length===0)return[];const c=i.fullMatch??!1,u=_l(i.scanLimit,s),f=await Sl({prefix:n,keywords:o,fullMatch:c,scanLimit:u,iterate:p=>this.btree.prefix(e,p),onError:(p,d)=>{console.error("Search error for keyword:",p,d)}});return Al(f,s).map(([p,{value:d,score:g,exactMatches:w,prefixDistance:x}])=>({id:p,value:d,score:g,exactMatches:w,prefixDistance:x}))}async remove(e,n,r,i){let s=e;for(const o of r){const c=`${n}${o}:${i}`;try{if(s=await this.btree.delete(s,c),!s)break}catch(u){console.error("Failed to remove term:",o,u)}}return s}async merge(e,n,r=!1){return this.btree.merge(e,n,r)}async build(e){return this.btree.build(e)}async indexLink(e,n,r,i,s){let o=e;for(const c of r){const u=`${n}${c}:${i}`;try{o=await this.btree.insertLink(o,u,s)}catch(f){console.error("Failed to index link for term:",c,f)}}return o}async buildLinks(e){return this.btree.buildLinks(e)}async searchLinks(e,n,r,i={}){return await this.searchLinkTerms(e,n,this.parseKeywords(r),i)}async searchLinkTerms(e,n,r,i={}){if(!e)return[];const s=xl(i.limit);if(s===0)return[];const o=kl(r);if(o.length===0)return[];const c=i.fullMatch??!1,u=_l(i.scanLimit,s),f=await Sl({prefix:n,keywords:o,fullMatch:c,scanLimit:u,iterate:p=>this.btree.prefixLinks(e,p),onError:(p,d)=>{console.error("Search error for keyword:",p,d)}});return Al(f,s).map(([p,{value:d,score:g,exactMatches:w,prefixDistance:x}])=>({id:p,cid:d,score:g,exactMatches:w,prefixDistance:x}))}async mergeLinks(e,n,r=!1){return this.btree.mergeLinks(e,n,r)}}function xl(t){return t===void 0?20:Number.isFinite(t)?Math.max(0,Math.floor(t)):Number.POSITIVE_INFINITY}function _l(t,e){const n=Number.isFinite(e)?e*2:Number.POSITIVE_INFINITY;return t===void 0?n:Number.isFinite(t)?Math.max(e,Math.floor(t??n)):Number.POSITIVE_INFINITY}function kl(t){const e=new Set,n=[];for(const r of t){const i=`${r??""}`.trim().toLowerCase();!i||e.has(i)||(e.add(i),n.push(i))}return n}async function Sl(t){const e=new Map;for(const n of t.keywords)try{const r=`${t.prefix}${n}${t.fullMatch?":":""}`;let i=0;for await(const[s,o]of t.iterate(r)){if(i++>=t.scanLimit)break;const c=s.slice(t.prefix.length),u=c.indexOf(":");if(u===-1)continue;const f=c.slice(0,u),p=c.slice(u+1),d=f===n?1:0,g=Math.max(0,f.length-n.length),w=e.get(p);w?(w.score+=1,w.exactMatches+=d,w.prefixDistance+=g):e.set(p,{value:o,score:1,exactMatches:d,prefixDistance:g})}}catch(r){t.onError(n,r)}return e}function Al(t,e){return[...t.entries()].sort((n,r)=>r[1].score!==n[1].score?r[1].score-n[1].score:r[1].exactMatches!==n[1].exactMatches?r[1].exactMatches-n[1].exactMatches:n[1].prefixDistance!==r[1].prefixDistance?n[1].prefixDistance-r[1].prefixDistance:n[0].localeCompare(r[0])).slice(0,e)}new TextEncoder;new TextDecoder;new TextEncoder;new TextDecoder;function Gn(t){return Array.isArray?Array.isArray(t):yd(t)==="[object Array]"}function ox(t){if(typeof t=="string")return t;if(typeof t=="bigint")return t.toString();const e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function Oa(t){return t==null?"":ox(t)}function Et(t){return typeof t=="string"}function gs(t){return typeof t=="number"}function ax(t){return t===!0||t===!1||cx(t)&&yd(t)=="[object Boolean]"}function pd(t){return typeof t=="object"}function cx(t){return pd(t)&&t!==null}function Ot(t){return t!=null}function cs(t){return!t.trim().length}function yd(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const ux="Incorrect 'index' type",Da="Invalid doc index: must be a non-negative integer within the bounds of the docs array",lx=t=>`Invalid value for key ${t}`,fx=t=>`Pattern length exceeds max of ${t}.`,hx=t=>`Missing ${t} property in key`,dx=t=>`Property 'weight' in key '${t}' must be a positive integer`,px="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",Rl=Object.prototype.hasOwnProperty;var yx=class{constructor(t){this._keys=[],this._keyMap={};let e=0;t.forEach(n=>{const r=gd(n);this._keys.push(r),this._keyMap[r.id]=r,e+=r.weight}),this._keys.forEach(n=>
3{n.weight/=e})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function gd(t){let e=null,n=null,r=null,i=1,s=null;if(Et(t)||Gn(t))r=t,e=Cl(t),n=ms(t);else{if(!Rl.call(t,"name"))throw new Error(hx("name"));const o=t.name;if(r=o,Rl.call(t,"weight")&&t.weight!==void 0&&(i=t.weight,i<=0))throw new Error(dx(ms(o)));e=Cl(o),n=ms(o),s=t.getFn??null}return{path:e,id:n,weight:i,src:r,getFn:s}}function Cl(t){return Gn(t)?t:t.split(".")}function ms(t){return Gn(t)?t.join("."):t}function gx(t,e){const n=[];let r=!1;const i=(s,o,c,u)=>{if(Ot(s))if(!o[c])n.push(u!==void 0?{v:s,i:u}:s);else{const f=s[o[c]];if(!Ot(f))return;if(c===o.length-1&&(Et(f)||gs(f)||ax(f)||typeof f=="bigint"))n.push(u!==void 0?{v:Oa(f),i:u}:Oa(f));else if(Gn(f)){r=!0;for(let p=0,d=f.length;p<d;p+=1)i(f[p],o,c+1,p)}else o.length&&i(f,o,c+1,u)}};return i(t,Et(e)?e.split("."):e,0),r?n:n[0]}const mx={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},wx={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(t,e)=>t.score===e.score?t.idx<e.idx?-1:1:t.score<e.score?-1:1},vx={location:0,threshold:.6,distance:100},bx={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:gx,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Oe=Object.freeze({...wx,...mx,...vx,...bx});function Ex(t){return t>=9&&t<=13||t===32||t===160}function xx(t=1,e=3){const n=new Map,r=Math.pow(10,e);return{get(i){let s=0,o=!1;for(let u=0;u<i.length;u++)Ex(i.charCodeAt(u))?o=!1:o||(s++,o=!0);if(s===0&&(s=1),n.has(s))return n.get(s);const c=Math.round(r/Math.pow(s,.5*t))/r;return n.set(s,c),c},clear(){n.clear()}}}var Kc=class{constructor({getFn:t=Oe.getFn,fieldNormWeight:e=Oe.fieldNormWeight}={}){this.norm=xx(e,3),this.getFn=t,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(t=[]){this.docs=t}setIndexRecords(t=[]){this.records=t}setKeys(t=[]){this.keys=t,this._keysMap={},t.forEach((e,n)=>{this._keysMap[e.id]=n})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;const t=this.docs.length;this.records=new Array(t);let e=0;if(Et(this.docs[0]))for(let n=0;n<t;n++){const r=this._createStringRecord(this.docs[n],n);r&&(this.records[e++]=r)}
3else for(let n=0;n<t;n++)this.records[e++]=this._createObjectRecord(this.docs[n],n);this.records.length=e,this.norm.clear()}add(t,e){if(!Number.isInteger(e)||e<0)throw new Error(Da);if(Et(t)){const r=this._createStringRecord(t,e);return r&&this.records.push(r),r}const n=this._createObjectRecord(t,e);return this.records.push(n),n}removeAt(t){if(!Number.isInteger(t)||t<0)throw new Error(Da);for(let e=0,n=this.records.length;e<n;e+=1)if(this.records[e].i===t){this.records.splice(e,1);break}for(let e=0,n=this.records.length;e<n;e+=1)this.records[e].i>t&&(this.records[e].i-=1)}removeAll(t){const e=new Set;for(const r of t)Number.isInteger(r)&&r>=0&&e.add(r);if(e.size===0)return;this.records=this.records.filter(r=>!e.has(r.i));const n=Array.from(e).sort((r,i)=>r-i);for(const r of this.records){let i=0,s=n.length;for(;i<s;){const o=i+s>>>1;n[o]<r.i?i=o+1:s=o}r.i-=i}}getValueForItemAtKeyId(t,e){return t[this._keysMap[e]]}size(){return this.records.length}_createStringRecord(t,e){return!Ot(t)||cs(t)?null:{v:t,i:e,n:this.norm.get(t)}}_createObjectRecord(t,e){const n={i:e,$:{}};for(let r=0,i=this.keys.length;r<i;r++){const s=this.keys[r],o=s.getFn?s.getFn(t):this.getFn(t,s.path);if(Ot(o)){if(Gn(o)){const c=[];for(let u=0,f=o.length;u<f;u+=1){const p=o[u];if(Ot(p)){if(Et(p)){if(!cs(p)){const d={v:p,i:u,n:this.norm.get(p)};c.push(d)}}else if(Ot(p.v)){const d=Et(p.v)?p.v:Oa(p.v);if(!cs(d)){const g={v:d,i:p.i,n:this.norm.get(d)};c.push(g)}}}}n.$[r]=c}else if(Et(o)&&!cs(o)){const c={v:o,n:this.norm.get(o)};n.$[r]=c}}}return n}toJSON(){return{keys:this.keys.map(({getFn:t,...e})=>e),records:this.records}}};function md(t,e,{getFn:n=Oe.getFn,fieldNormWeight:r=Oe.fieldNormWeight}={}){const i=new Kc({getFn:n,fieldNormWeight:r});return i.setKeys(t.map(gd)),i.setSources(e),i.create(),i}function _x(t,{getFn:e=Oe.getFn,fieldNormWeight:n=Oe.fieldNormWeight}={}){const{keys:r,records:i}=t,s=new Kc({getFn:e,fieldNormWeight:n});return s.setKeys(r),s.setIndexRecords(i),s}function kx(t=[],e=Oe.minMatchCharLength){const n=[];let r=-1,i=-1,s=0;for(let o=t.length;s<o;s+=1){const c=t[s];c&&r===-1?r=s:!c&&r!==-1&&(i=s-1,i-r+1>=e&&n.push([r,i]),r=-1)}return t[s-1]&&s-r>=e&&n.push([r,s-1]),n}function Sx(t,e,n,{location:r=Oe.location,distance:i=Oe.distance,threshold:s=Oe.threshold,findAllMatches:o=Oe.findAllMatches,minMatchCharLength:c=Oe.minMatchCharLength,includeMatches:u=Oe.includeMatches,ignoreLocation:f=Oe.ignoreLocation}={}){if(e.length>32)throw new Error(fx(32));const p=e.length,d=t.length,g=Math.max(0,Math.min(r,d));let w=s,x=g;const A=(ee,ge)=>{const $=ee/p;if(f)return $;const H=Math.abs(g-ge);return i?$+H/i:H?1:$},I=c>1||u,T=I?Array(d):[];let te;for(;(te=t.indexOf(e,x))>-1;){const ee=A(0,te);if(w=Math.min(ee,w),x=te+p,I){let ge=0;for(;ge<p;)T[te+ge]=1,ge+=1}}x=-1;let ae=[],Re=1,le=0,Y=p+d;const Q=1<<p-1;for(let ee=0;ee<p;ee+=1){let ge=0,$=Y;for(;ge<$;)A(ee,g+$)<=w?ge=$:Y=$,$=Math.floor((Y-ge)/2+ge);Y=$;let H=Math.max(1,g-$+1);const C=o?d:Math.min(g+$,d)+p,j=Array(C+2);j[C+1]=(1<<ee)-1;for(let P=C;P>=H;P-=1){const X=P-1,re=n[t[X]];if(j[P]=(j[P+1]<<1|1)&re,ee&&(j[P]|=(ae[P+1]|ae[P])<<1|1|ae[P+1]),j[P]&Q&&(Re=A(ee,X),Re<=w)){if(w=Re,x=X,le=ee,x<=g)break;H=Math.max(1,2*g-x)}}if(A(ee+1,g)>w)break;ae=j}if(I&&x>=0){const ee=Math.min(d-1,x+p-1+le);for(let ge=x;ge<=ee;ge+=1)n[t[ge]]&&(T[ge]=1)}const ie={isMatch:x>=0,score:Math.max(.001,Re)};if(I){const ee=kx(T,c);ee.length?u&&(ie.indices=ee):ie.isMatch=!1}return ie}function Ax(t){const e={};for(let n=0,r=t.length;n<r;n+=1){const i=t.charAt(n);e[i]=(e[i]||0)|1<<r-n-1}return e}function zc(t){if(t.length<=1)return t;t.sort((n,r)=>n[0]-r[0]||n[1]-r[1]);const e=[t[0]];for(let n=1,r=t.length;n<r;n+=1){const i=e[e.length-1],s=t[n];s[0]<=i[1]+1?i[1]=Math.max(i[1],s[1]):e.push(s)}return e}const wd={ł:"l",Ł:"L",đ:"d",Đ:"D",ø:"o",Ø:"O",ħ:"h",Ħ:"H",ŧ:"t",Ŧ:"T",ı:"i",ß:"ss"},Rx=new RegExp("["+Object.keys(wd).join("")+"]","g"),ki=typeof String.prototype.normalize=="function"?t=>t.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A7
vendor: 5,304 bytes, line 3
35\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(Rx,e=>wd[e]):t=>t;var Hc=class{constructor(t,{location:e=Oe.location,threshold:n=Oe.threshold,distance:r=Oe.distance,includeMatches:i=Oe.includeMatches,findAllMatches:s=Oe.findAllMatches,minMatchCharLength:o=Oe.minMatchCharLength,isCaseSensitive:c=Oe.isCaseSensitive,ignoreDiacritics:u=Oe.ignoreDiacritics,ignoreLocation:f=Oe.ignoreLocation}={}){if(this.options={location:e,threshold:n,distance:r,includeMatches:i,findAllMatches:s,minMatchCharLength:o,isCaseSensitive:c,ignoreDiacritics:u,ignoreLocation:f},t=c?t:t.toLowerCase(),t=u?ki(t):t,this.pattern=t,this.chunks=[],!this.pattern.length)return;const p=(g,w)=>{this.chunks.push({pattern:g,alphabet:Ax(g),startIndex:w})},d=this.pattern.length;if(d>32){let g=0;const w=d%32,x=d-w;for(;g<x;)p(this.pattern.substr(g,32),g),g+=32;if(w){const A=d-32;p(this.pattern.substr(A),A)}}else p(this.pattern,0)}searchIn(t){const{isCaseSensitive:e,ignoreDiacritics:n,includeMatches:r}=this.options;if(t=e?t:t.toLowerCase(),t=n?ki(t):t,this.pattern===t){if(t.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};const x={isMatch:!0,score:0};return r&&(x.indices=[[0,t.length-1]]),x}const{location:i,distance:s,threshold:o,findAllMatches:c,minMatchCharLength:u,ignoreLocation:f}=this.options,p=[];let d=0,g=!1;this.chunks.forEach(({pattern:x,alphabet:A,startIndex:I})=>{const{isMatch:T,score:te,indices:ae}=Sx(t,x,A,{location:i+I,distance:s,threshold:o,findAllMatches:c,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});T&&(g=!0),d+=te,T&&ae&&p.push(...ae)});const w={isMatch:g,score:g?d/this.chunks.length:1};return g&&r&&(w.indices=zc(p)),w}};const Cx=new Set(["fuzzy","include"]);function Tx(t){return t.startsWith("inverse")}const Na=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:t=>({type:"exact",search(e){const n=e===t;return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:t=>({type:"include",search(e){let n=0,r;const i=[],s=t.length;for(;(r=e.indexOf(t,n))>-1;)n=r+s,i.push([r,n-1]);const o=!!i.length;return{isMatch:o,score:o?0:1,indices:i}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:t=>({type:"prefix-exact",search(e){const n=e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:t=>({type:"inverse-prefix-exact",search(e){const n=!e.startsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:t=>({type:"inverse-suffix-exact",search(e){const n=!e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:t=>({type:"suffix-exact",search(e){const n=e.endsWith(t);return{isMatch:n,score:n?0:1,indices:[e.length-t.length,e.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:t=>({type:"inverse-exact",search(e){const n=e.indexOf(t)===-1;return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(t,e={})=>{const n=new Hc(t,{location:e.location??Oe.location,threshold:e.threshold??Oe.threshold,distance:e.distance??Oe.distance,includeMatches:e.includeMatches??Oe.includeMatches,findAllMatches:e.findAllMatches??Oe.findAllMatches,minMatchCharLength:e.minMatchCharLength??Oe.minMatchCharLength,isCaseSensitive:e.isCaseSensitive??Oe.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics??Oe.ignoreDiacritics,ignoreLocation:e.ignoreLocation??Oe.ignoreLocation});return{type:"fuzzy",search(r){return n.searchIn(r)}
3}}}],Tl=Na.length,Ix="\0",Bx="|";function Lx(t){const e=[],n=t.length;let r=0;for(;r<n;){for(;r<n&&t[r]===" ";)r++;if(r>=n)break;let i=r;for(;i<n&&t[i]!==" "&&t[i]!=='"';)i++;if(i<n&&t[i]==='"'){for(i++;i<n;){if(t[i]==='"'){const s=i+1;if(s>=n||t[s]===" "){i++;break}if(t[s]==="$"&&(s+1>=n||t[s+1]===" ")){i+=2;break}}i++}e.push(t.substring(r,i)),r=i}else{for(;i<n&&t[i]!==" ";)i++;e.push(t.substring(r,i)),r=i}}return e}function Il(t,e){const n=t.match(e);return n?n[1]:null}function Mx(t,e={}){return t.replace(/\\\|/g,Ix).split(Bx).map(n=>{const r=Lx(n.replace(/\u0000/g,"|").trim()).filter(s=>s&&!!s.trim()),i=[];for(let s=0,o=r.length;s<o;s+=1){const c=r[s];let u=!1,f=-1;for(;!u&&++f<Tl;){const p=Na[f],d=Il(c,p.multiRegex);d&&(i.push(p.create(d,e)),u=!0)}if(!u)for(f=-1;++f<Tl;){const p=Na[f],d=Il(c,p.singleRegex);if(d){i.push(p.create(d,e));break}}}return i})}var Ox=class{constructor(t,{isCaseSensitive:e=Oe.isCaseSensitive,ignoreDiacritics:n=Oe.ignoreDiacritics,includeMatches:r=Oe.includeMatches,minMatchCharLength:i=Oe.minMatchCharLength,ignoreLocation:s=Oe.ignoreLocation,findAllMatches:o=Oe.findAllMatches,location:c=Oe.location,threshold:u=Oe.threshold,distance:f=Oe.distance}={}){this.query=null,this.options={isCaseSensitive:e,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:s,location:c,threshold:u,distance:f},t=e?t:t.toLowerCase(),t=n?ki(t):t,this.pattern=t,this.query=Mx(this.pattern,this.options)}static condition(t,e){return e.useExtendedSearch}searchIn(t){const e=this.query;if(!e)return{isMatch:!1,score:1};const{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;t=r?t:t.toLowerCase(),t=i?ki(t):t;let s=0;const o=[];let c=0,u=!1;for(let f=0,p=e.length;f<p;f+=1){const d=e[f];o.length=0,s=0,u=!1;for(let g=0,w=d.length;g<w;g+=1){const x=d[g],{isMatch:A,indices:I,score:T}=x.search(t);if(A)s+=1,c+=T,Tx(x.type)&&(u=!0),n&&(Cx.has(x.type)?o.push(...I):o.push(I));else{c=0,s=0,o.length=0,u=!1;break}}if(s){const g={isMatch:!0,score:c/s};return u&&(g.hasInverse=!0),n&&(g.indices=zc(o)),g}}return{isMatch:!1,score:1}}};const Pa=[];function qc(...t){Pa.push(...t)}function Ls(t,e){for(let n=0,r=Pa.length;n<r;n+=1){const i=Pa[n];if(i.condition(t,e))return new i(t,e)}return new Hc(t,e)}const Ms={AND:"$and",OR:"$or"},Fa={PATH:"$path",PATTERN:"$val"},Ua=t=>!!(t[Ms.AND]||t[Ms.OR]),Dx=t=>!!t[Fa.PATH],Nx=t=>!Gn(t)&&pd(t)&&!Ua(t),Bl=t=>({[Ms.AND]:Object.keys(t).map(e=>({[e]:t[e]}))});function vd(t,e,{auto:n=!0}={}){const r=i=>{if(Et(i)){const u={keyId:null,pattern:i};return n&&(u.searcher=Ls(i,e)),u}const s=Object.keys(i),o=Dx(i);if(!o&&s.length>1&&!Ua(i))return r(Bl(i));if(Nx(i)){const u=o?i[Fa.PATH]:s[0],f=o?i[Fa.PATTERN]:i[u];if(!Et(f))throw new Error(lx(u));const p={keyId:ms(u),pattern:f};return n&&(p.searcher=Ls(f,e)),p}const c={children:[],operator:s[0]};return s.forEach(u=>{const f=i[u];Gn(f)&&f.forEach(p=>
3{c.children.push(r(p))})}),c};return Ua(t)||(t=Bl(t)),r(t)}function $a(t,{ignoreFieldNorm:e=Oe.ignoreFieldNorm}){let n=1;return t.forEach(({key:r,norm:i,score:s})=>{const o=r?r.weight:null;n*=Math.pow(s===0&&o?Number.EPSILON:s,(o||1)*(e?1:i))}),n}function Px(t,{ignoreFieldNorm:e=Oe.ignoreFieldNorm}){t.forEach(n=>{n.score=$a(n.matches,{ignoreFieldNorm:e})})}var Fx=class{constructor(t,e){this.limit=t,this.heap=[],this.comparator=e}get size(){return this.heap.length}insert(t){this.size<this.limit?(this.heap.push(t),this._bubbleUp(this.size-1)):this.comparator(t,this.heap[0])<0&&(this.heap[0]=t,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(t){const e=this.heap;for(;t>0;){const n=t-1>>1;if(this.comparator(e[t],e[n])<=0)break;const r=e[t];e[t]=e[n],e[n]=r,t=n}}_sinkDown(t){const e=this.heap,n=e.length;let r=t;do{t=r;const i=2*t+1,s=2*t+2;if(i<n&&this.comparator(e[i],e[r])>0&&(r=i),s<n&&this.comparator(e[s],e[r])>0&&(r=s),r!==t){const o=e[t];e[t]=e[r],e[r]=o}}while(r!==t)}};function Ux(t){const e=[];return t.matches.forEach(n=>{if(!Ot(n.indices)||!n.indices.length)return;const r={indices:n.indices,value:n.value};n.key&&(r.key=n.key.id),n.idx>-1&&(r.refIndex=n.idx),e.push(r)}),e}function $x(t,e,{includeMatches:n=Oe.includeMatches,includeScore:r=Oe.includeScore}={}){return t.map(i=>{const{idx:s}=i,o={item:e[s],refIndex:s};return n&&(o.matches=Ux(i)),r&&(o.score=i.score),o})}const Kx=/[\p{L}\p{M}\p{N}_]+/gu,Ll=new WeakSet;function zx(t){Ll.has(t)||(Ll.add(t),console.warn(`[Fuse] tokenize regex ${t} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function Hx(t){if(typeof t=="function"){let e=!1;return n=>{const r=t(n);if(!e&&(e=!0,!Array.isArray(r)||r.some(i=>typeof i!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?"array containing non-strings":typeof r}.`);return r}}return t instanceof RegExp?(t.global||zx(t),e=>e.match(t)||[]):e=>e.match(Kx)||[]}function Ka({isCaseSensitive:t=!1,ignoreDiacritics:e=!1,tokenize:n}={}){const r=Hx(n);return{tokenize(i){return t||(i=i.toLowerCase()),e&&(i=ki(i)),r(i)}}}var qx=class{static condition(t,e){return e.useTokenSearch}constructor(t,e){this.options=e,this.analyzer=Ka({isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,tokenize:e.tokenize});const n=this.analyzer.tokenize(t),{df:r,fieldCount:i}=e._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(const s of n){this.termSearchers.push(new Hc(s,{location:e.location,threshold:e.threshold,distance:e.distance,includeMatches:e.includeMatches,findAllMatches:e.findAllMatches,minMatchCharLength:e.minMatchCharLength,isCaseSensitive:e.isCaseSensitive,ignoreDiacritics:e.ignoreDiacritics,ignoreLocation:!0}));const o=r.get(s)||0,c=Math.log(1+(i-o+.5)/(o+.5));this.idfWeights.push(c)}this.combineAll=e.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(t){if(!this.termSearchers.length)return{isMatch:!1,score:1};const e=[];let n=0,r=0,i=0,s=0;const o=this.combineAll&&!this.useMask?new Set:null;for(let f=0;f<this.termSearchers.length;f++){const p=this.termSearchers[f].searchIn(t),d=this.idfWeights[f];r+=d,p.isMatch&&(i++,n+=d*(1-p.score),p.indices&&e.push(...p.indices),this.combineAll&&(this.useMask?s|=1<<f:o.add(f)))}if(i===0)return{isMatch:!1,score:1};const c=r>0?1-n/r:0,u={isMatch:!0,score:Math.max(.001,c)};return this.options.includeMatches&&e.length&&(u.indices=zc(e)),this.combineAll&&(this.useMask?u.matchedMask=s:u.matchedTerms=o,u.termCount=this.numTerms),u}};function sa(t,e,n,r){const i=r.tokenize(e);if(!i.length)return;t.fieldCount++,t.docFieldCount.set(n,(t.docFieldCount.get(n)||0)+1);const s=new Set(i);let o=t.docTermFieldHits.get(n);o||(o=new Map,t.docTermFieldHits.set(n,o));for(const c of s)o.set(c,(o.get(c)||0)+1),t.df.set(c,(t.df.get(c)||0)+1)}function bd(t,e,n,r){const{i,v:s,$:o}=e;if(s!==void 0){sa(t,s,i,r);return}if(o)for(let c=0;c<n;c++){const u=o[c];if(u)if(Array.isArray(u))for(const f of u)sa(t,f.v,i,r);else sa(t,u.v,i,r)}}function Wx(t,e,n){const r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(const i of t)bd(r,i,e,n);return r}function jx(t,e,n,r){bd(t,e,n,r)}function Vx(t,e){const n=t.docFieldCount.get(e);if(n===void 0)return;t.fieldCount-=n,t.docFieldCount.delete(e);const r=t.docTermFieldHits.get(e);if(r){for(const[i,s]of r){const o=(t.df.get(i)||0)-s;o<=0?t.df.delete(i):t.df.set(i,o)}t.docTermFieldHits.delete(e)}}function Ml(t,e){if(e.length===0)return;const n=Array.from(new Set(e)).sort((c,u)=>c-u);for(const c of n)Vx(t,c);const r=c=>{let u=0,f=n.length;for(;u<f;){const p=u+f>>>1;n[p]<c?u=p+1:f=p}return c-u},i=n[0],s=new Map;for(const[c,u]of t.docFieldCount)s.set(c>i?r(c):c,u);t.docFieldCount=s;const o=new Map;for(const[c,u]of t.docTermFieldHits)o.set(c>i?r(c):c,u);t.docTermFieldHits=o}var Yn=class{constructor(t,e,n){this.options={...Oe,...e},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new yx(this.options.keys),this._docs=t,this._myIndex=null,this._invertedIndex=null,this.setCollection(t,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(t){if(this._lastQuery===t)return this._lastSearcher;const e=Ls(t,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=t,this._lastSearcher=e,e}setCollection(t,e){if(this._docs=t,e&&!(e instanceof Kc))throw new Error(ux);if(this._myIndex=e||md(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){const n=Ka({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=Wx(this._myIndex.records,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}add(t){if(!Ot(t))return;this._docs.push(t);const e=this._myIndex.add(t,this._docs.length-1);if(this._invertedIndex&&e){const n=Ka({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});jx(this._invertedIndex,e,this._myIndex.keys.length,n)}this._invalidateSearcherCache()}remove(t=()=>!1){const e=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)t(this._docs[r],r)&&(e.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&Ml(this._invertedIndex,n);const r=new Set(n);this._docs=this._docs.filter((i,s)=>!r.has(s)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return e}removeAt(t){if(!Number.isInteger(t)||t<0||t>=this._docs.length)throw new Error(Da);this._invertedIndex&&Ml(this._invertedIndex,[t]);const e=this._docs.splice(t,1)[0];return this._myIndex.removeAt(t),this._invalidateSearcherCache(),e}
3_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(t=>this._keyStore.get(t.id)||t)}search(t,e){const{limit:n=-1}=e||{},{includeMatches:r,includeScore:i,shouldSort:s,sortFn:o,ignoreFieldNorm:c}=this.options;if(Et(t)&&!t.trim()){let g=this._docs.map((w,x)=>({item:w,refIndex:x}));return gs(n)&&n>-1&&(g=g.slice(0,n)),g}const u=s&&gs(n)&&n>0&&Et(t),f=o,p=(g,w)=>f(g,w)||g.idx-w.idx;let d;if(u){const g=new Fx(n,p);Et(this._docs[0])?this._searchStringList(t,{heap:g,ignoreFieldNorm:c}):this._searchObjectList(t,{heap:g,ignoreFieldNorm:c}),d=g.extractSorted()}else d=Et(t)?Et(this._docs[0])?this._searchStringList(t):this._searchObjectList(t):this._searchLogical(t),Px(d,{ignoreFieldNorm:c}),s&&d.sort(Et(t)?p:f),gs(n)&&n>-1&&(d=d.slice(0,n));return $x(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(t,{heap:e,ignoreFieldNorm:n}={}){const r=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:s}=this._myIndex,o=e?null:[];return s.forEach(({v:c,i:u,n:f})=>{if(!Ot(c))return;const p=r.searchIn(c);if(p.isMatch){const d={score:p.score,value:c,norm:f,indices:p.indices};i&&(d.matchedMask=p.matchedMask,d.matchedTerms=p.matchedTerms,d.termCount=p.termCount);const g=[d];if(!i||this._coversAllTokens(g)){const w={item:c,idx:u,matches:g};e?(w.score=$a(w.matches,{ignoreFieldNorm:n}),e.insert(w)):o.push(w)}}}),o}_searchLogical(t){const e=vd(t,this.options),n=this._normalizedKeys(),r=(c,u,f)=>{if(!("children"in c)){const{keyId:w,searcher:x}=c;let A;return w===null?(A=[],n.forEach((I,T)=>{A.push(...this._findMatches({key:I,value:u[T],searcher:x}))})):A=this._findMatches({key:this._keyStore.get(w),value:this._myIndex.getValueForItemAtKeyId(u,w),searcher:x}),A&&A.length?[{idx:f,item:u,matches:A}]:[]}const{children:p,operator:d}=c,g=[];for(let w=0,x=p.length;w<x;w+=1){const A=p[w],I=r(A,u,f);if(I.length)g.push(...I);else if(d===Ms.AND)return[]}return g},i=this._myIndex.records,s=new Map,o=[];return i.forEach(({$:c,i:u})=>{if(Ot(c)){const f=r(e,c,u);f.length&&(s.has(u)||(s.set(u,{idx:u,item:c,matches:[]}),o.push(s.get(u))),f.forEach(({matches:p})=>{s.get(u).matches.push(...p)}))}}),o}_searchObjectList(t,{heap:e,ignoreFieldNorm:n}={}){const r=this._getSearcher(t),i=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:s}=this._myIndex,o=this._normalizedKeys(),c=e?null:[];return s.forEach(({$:u,i:f})=>{if(!Ot(u))return;const p=[];let d=!1,g=!1;if(o.forEach((w,x)=>{const A=this._findMatches({key:w,value:u[x],searcher:r});A.length?(p.push(...A),A[0].hasInverse&&(g=!0)):d=!0}),!(g&&d)&&p.length&&(!i||this._coversAllTokens(p))){const w={idx:f,item:u,matches:p};e?(w.score=$a(w.matches,{ignoreFieldNorm:n}),e.insert(w)):c.push(w)}}),c}_findMatches({key:t,value:e,searcher:n}){if(!Ot(e))return[];const r=[];if(Gn(e))e.forEach(({v:i,i:s,n:o})=>{if(!Ot(i))return;const c=n.searchIn(i);if(c.isMatch){const u={score:c.score,key:t,value:i,idx:s,norm:o,indices:c.indices,hasInverse:c.hasInverse};c.termCount!==void 0&&(u.matchedMask=c.matchedMask,u.matchedTerms=c.matchedTerms,u.termCount=c.termCount),r.push(u)}});else{const{v:i,n:s}=e,o=n.searchIn(i);if(o.isMatch){const c={score:o.score,key:t,value:i,norm:s,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(c.matchedMask=o.matchedMask,c.matchedTerms=o.matchedTerms,c.termCount=o.termCount),r.push(c)}}return r}_coversAllTokens(t){const e=t.length?t[0].termCount:void 0;if(e===void 0)return!0;if(e<=31){let r=0;for(let i=0;i<t.length;i++)r|=t[i].matchedMask||0;return r===2**e-1}const n=new Set;for(let r=0;r<t.length;r++){const i=t[r].matchedTerms;if(i)for(const s of i)n.add(s)}return n.size===e}};Yn.version="7.5.0";Yn.createIndex=md;Yn.parseIndex=_x;Yn.config=Oe;Yn.match=function(t,e,n){if(n&&n.useTokenSearch)throw new Error(px);return Ls(t,{...Oe,...n}).searchIn(e)};Yn.parseQuery=vd;qc(Ox);qc(qx);Yn.use=function(...t){t.forEach(e=>qc(e))};var Ed=Yn;class Gx extends fr{profiles;events;unpublishedEvents;cacheData;constructor(e){super(e),this.version(1).stores({profiles:"&pubkey",events:"&id, kind, pubkey, createdAt, [kind+createdAt], [pubkey+createdAt], *tagIndex",unpublishedEvents:"&id",cacheData:"&key, cachedAt"})}}
3let Xe;function Yx(t){Xe||(Xe=new Gx("iris-pubsub"))}class Zx{store;constructor(){Yx(),this.store={query:(e,n)=>this.queryEvents(e,n),put:e=>this.put(e),delete:async e=>{await Xe.events.bulkDelete(e)},listPending:async()=>Xe.unpublishedEvents.toArray(),putPending:async e=>{await Xe.unpublishedEvents.put({...e,id:e.event.id})},deletePending:async e=>{await Xe.unpublishedEvents.delete(e)}}}async put(e){const n=e.tags.filter(r=>r.length>1).map(r=>`${r[0]}:${r[1]}`);await Xe.transaction("rw",[Xe.events,Xe.profiles],async()=>{if(await Xe.events.put({id:e.id,pubkey:e.pubkey,kind:e.kind,createdAt:e.created_at,event:JSON.stringify(e),sig:e.sig,tagIndex:n}),e.kind===0){const r=await Xe.profiles.get(e.pubkey);(!r||Number(r.created_at??0)<=e.created_at)&&await Xe.profiles.put({...Bh(e),profileEvent:JSON.stringify(e),pubkey:e.pubkey,created_at:e.created_at,cachedAt:Date.now()})}})}async queryEvents(e,n){const r=new Map;for(const i of e){if(n?.signal?.aborted)throw n.signal.reason;const s=Object.entries(i).find(([w,x])=>w.startsWith("#")&&Array.isArray(x)&&x.length),o=i.limit??n?.limit??5e3,c=!i.ids&&!s&&(i.authors?.length===1||!i.authors&&i.kinds?.length===1||!i.authors&&!s&&!i.kinds);let u=Xe.events.orderBy("createdAt").reverse();i.ids?.every(w=>w.length===64)?u=Xe.events.where("id").anyOf(i.ids):s?u=Xe.events.where("tagIndex").anyOf(s[1].map(w=>`${s[0].slice(1)}:${w}`)):i.authors?.length===1?u=Xe.events.where("[pubkey+createdAt]").between([i.authors[0],i.since??0],[i.authors[0],i.until??Number.MAX_SAFE_INTEGER],!0,!0).reverse():i.authors?.every(w=>w.length===64)?u=Xe.events.where("pubkey").anyOf(i.authors):i.kinds?.length===1?u=Xe.events.where("[kind+createdAt]").between([i.kinds[0],i.since??0],[i.kinds[0],i.until??Number.MAX_SAFE_INTEGER],!0,!0).reverse():i.kinds?.length&&(u=Xe.events.where("kind").anyOf(i.kinds));const f=w=>jf([i],w)&&(!i.search||i.search.toLowerCase().split(/\s+/).every(x=>w.content.toLowerCase().includes(x))),g=(await(c?u.filter(w=>f(JSON.parse(w.event))).limit(o):u).toArray()).map(w=>JSON.parse(w.event)).filter(f).sort((w,x)=>x.created_at-w.created_at||w.id.localeCompare(x.id));for(const w of g.slice(0,i.limit??n?.limit??5e3))r.set(w.id,w)}return[...r.values()].sort((i,s)=>s.created_at-i.created_at||i.id.localeCompare(s.id)).slice(0,n?.limit??5e3)}async fetchProfile(e){return await Xe.profiles.get(e)??null}async setEvent(e,n,r){const i=e instanceof Dt?e.rawEvent():e;if(!Hr(i))throw new Error("Invalid event signature");await this.put(i)}}const xd=100;function Xx(t){if(typeof t!="string")return;const e=t.split(/\s+/).filter(Boolean).join(" ");if(e)return e.slice(0,xd)}function Jx(t){return typeof t!="string"?void 0:t.trim()||void 0}function Qx(t){const e=[t.display_name,t.displayName,t.name,t.username],n=[],r=new Set;for(const i of e){const s=Xx(i);if(!s)continue;const o=s.toLowerCase();r.has(o)||(r.add(o),n.push(s))}return n}function e_(t,e){return t.length===1||t.startsWith("npub1")?!0:e.toLowerCase().replace(/\s+/g,"").includes(t)}function t_(t,e){if(typeof t!="string")return;const n=t.split("@")[0]?.trim().toLowerCase().slice(0,xd);if(n&&!(e&&e_(n,e)))return n}function Wc(t,e,n){const r=Qx(e),i=r[0];if(!i)return;const s=r.slice(1);let o;return typeof n=="number"?o=n:typeof e.created_at=="number"&&(o=e.created_at),{pubKey:t,name:i,aliases:s.length>0?s:void 0,nip05:t_(e.nip05,i),picture:Jx(e.picture),created_at:o}}const _d=["name","aliases","nip05","pubKey"],Os="p:",n_=8,r_=16,i_=64,s_=16,o_=12,a_="profile-search-root",c_=[{url:"https://upload.iris.to",read:!1,write:!0},{url:"https://cdn.iris.to",read:!0,write:!1}];let Ds=new Ed([],{keys:_d,includeScore:!0});const jc=new Map,Vc=new Map,oa=new Map;let aa,za=null;const u_=150,l_=120,f_=100,h_=4e3;function d_(t){za=t}function p_(t){return c_}function y_(){return null}function g_(){return null}function m_(t){const e=t.indexOf("/");if(e<=0||e===t.length-1)return null;const n=t.slice(0,e),r=t.slice(e+1);return!n.startsWith("npub1")||r.length===0?null:{npub:n,treeName:r}}function w_(){const t=y_();if(!t)return null;try{const e=new VE({servers:p_(void 0)}),n=new GE({primary:ex,fallbacks:[e],timeout:h_}),r=m_(t);let i=null;return r?i={kind:"tree",...r}:t.startsWith("nhash1")&&(i={kind:"root",root:Xs(t)}),i?{index:new sx(n),tree:new od({store:n}),target:i}:null}catch(e){return console.warn("Invalid profile search index ref:",e),null}}function v_(){return aa===void 0&&(aa=w_()),aa}function kd(t){Vc.set(t.pubKey,t),t.created_at&&jc.set(t.pubKey,t.created_at)}function Js(t){if(!t.name)return;const e=jc.get(t.pubKey)||0;t.created_at&&t.created_at<=e||(kd(t),Ds.remove(n=>n.pubKey===t.pubKey),Ds.add({...t,name:String(t.name)}))}function b_(t){const e=t.filter(n=>n.name);Ds=new Ed(e,{keys:_d,includeScore:!0}),jc.clear(),Vc.clear();for(const n of e)kd(n)}function E_(t){return Ds.search(t).map(e=>({item:e.item,score:e.score,source:"local"}))}function Gc(t){return{compactLength:t.replace(/\s+/g,"").length,keywordCount:t.trim().split(/\s+/).filter(
3Boolean).length}}function Ns(t){const{compactLength:e,keywordCount:n}=Gc(t);return n<=1&&e<=1}function x_(t){if(Ns(t))return 0;const{compactLength:e,keywordCount:n}=Gc(t);return n<=1&&e<=2?u_:n<=1&&e<=3?l_:f_}function Yc(t,e){return`${a_}:${t}/${e}`}function __(t,e){const n=t?.createdAt??0,r=e?.createdAt??0;return n!==r?n-r:(t?.eventId??"").localeCompare(e?.eventId??"")}function Sd(t,e){return Ma(t)===Ma(e)}function k_(){const t=g_();if(!t?.startsWith("nhash1"))return null;try{return{nhash:t,root:Xs(t)}}catch(e){return console.warn("[Relay Worker] Invalid profile search snapshot root:",e),null}}function S_(t,e){return e||t}async function A_(t,e){try{const r=(await Xe.cacheData.get(Yc(t,e)))?.data;return r?.nhash?{...r,root:Xs(r.nhash)}:null}catch(n){return console.warn("[Relay Worker] Failed to read cached profile search root:",n),null}}async function R_(t,e,n){try{await Xe.cacheData.put({key:Yc(t,e),data:{nhash:Ma(n.root),eventId:n.eventId,createdAt:n.createdAt},cachedAt:Date.now()})}catch(r){console.warn("[Relay Worker] Failed to cache profile search root:",r)}}function Ad(t,e){const n=new TextDecoder().decode(t),r=JSON.parse(n),i=r.pubkey||e,s=typeof r.content=="string"?JSON.parse(r.content):void 0;if(!s||typeof s!="object")return;const o=s,c=Wc(i,o,r.created_at);if(c)return{rawProfile:o,searchProfile:c}}async function Rd(t,e){if(Xe?.profiles)try{let n=t.name;typeof e?.displayName=="string"&&e.displayName.trim().length>0&&(n=e.displayName),typeof e?.display_name=="string"&&e.display_name.trim().length>0&&(n=e.display_name),await Xe.profiles.put({...e??{},pubkey:t.pubKey,cachedAt:Date.now(),created_at:t.created_at,name:typeof e?.name=="string"&&e.name.trim().length>0?e.name:t.name,display_name:n,nip05:typeof e?.nip05=="string"?e.nip05:t.nip05,picture:typeof e?.picture=="string"?e.picture:t.picture})}catch(n){console.warn("[Relay Worker] Failed to cache remote profile search result:",n)}}function C_(t){try{const e=JSON.parse(t.value),n=e.pubkey||t.id,r=typeof e.name=="string"&&e.name.trim()?e.name:n,i=Array.isArray(e.aliases)?e.aliases.filter(o=>typeof o=="string"&&o.length>0):void 0,s={pubKey:n,name:r,aliases:i&&i.length>0?i:void 0,nip05:typeof e.nip05=="string"&&e.nip05.length>0?e.nip05:void 0,picture:typeof e.picture=="string"&&e.picture.length>0?e.picture:void 0,created_at:typeof e.created_at=="number"?e.created_at:void 0};return Js(s),{item:s,score:t.score,source:"remote",eventNhash:typeof e.event_nhash=="string"&&e.event_nhash.startsWith("nhash1")?e.event_nhash:void 0}}catch(e){return console.warn("[Relay Worker] Failed to decode stored remote profile search result:",e),null}}async function Ol(t,e,n){const r=Vc.get(t);if(r)return r;try{const i=await n.tree.readFile(e);if(!i)return{pubKey:t,name:t};const s=Ad(i,t);if(s)return Js(s.searchProfile),Rd(s.searchProfile,s.rawProfile),s.searchProfile}catch(i){console.warn("[Relay Worker] Failed to resolve remote profile search result:",i)}return{pubKey:t,name:t}}async function T_(t,e){if(!t.eventNhash)return null;try{const n=await e.tree.readFile(Xs(t.eventNhash));if(!n)return null;const r=Ad(n,t.item.pubKey);if(r)return Js(r.searchProfile),Rd(r.searchProfile,r.rawProfile),{item:{...t.item,...r.searchProfile,aliases:r.searchProfile.aliases??t.item.aliases,nip05:r.searchProfile.nip05??t.item.nip05,picture:r.searchProfile.picture??t.item.picture,created_at:Math.max(t.item.created_at??0,r.searchProfile.created_at??0)||void 0},score:t.score,source:"remote"}}catch(n){console.warn("[Relay Worker] Failed to hydrate immediate remote profile hit:",n)}return null}function I_(t,e){const n=t.item.aliases??[],r=e.item.aliases??[];return t.item.pubKey===e.item.pubKey&&t.item.name===e.item.name&&t.item.nip05===e.item.nip05&&t.item.picture===e.item.picture&&t.item.created_at===e.item.created_at&&t.score===e.score&&n.length===r.length&&n.every((i,s)=>i===r[s])}function B_(t,e,n){const r=t.map(({eventNhash:s,...o})=>o),i=t.slice(0,o_);r.length===0||i.length===0||queueMicrotask(()=>{(async()=>{for(let s=0;s<i.length;s+=1){const o=await T_(i[s],e);!o||I_(r[s],o)||(r[s]=o,n?.([...r]))}})()})}async function us(t,e,n,r){const i=await L_(t,e,n);if(i.length>0)return r?.(i),i;const s=Id(n),o=(await t.index.search(e,Os,n,{limit:s})).map(C_).filter(g=>!!g);if(o.length>0){const g=o.map(({eventNhash:w,...x})=>x);return r?.(g),B_(o,t,r),g}const c=await t.index.searchLinks(e,Os,n,{limit:s});if(c.length===0)return[];const u=c.slice(0,s_),f=new Array(u.length),p=await Promise.all(u.map(async(g,w)=>
3{const x={item:await Ol(g.id,g.cid,t),score:g.score,source:"remote"};return f[w]=x,r?.(f.filter(A=>!!A)),x}));if(c.length<=u.length)return p;const d=await Promise.all(c.slice(u.length).map(async g=>({item:await Ol(g.id,g.cid,t),score:g.score,source:"remote"})));return[...p,...d]}async function L_(t,e,n){const r=Id(n),i=t.index.parseKeywords(n);if(i.length===0)return[];const s=new Map;for(const o of i){const c=`${Os}${o}`;let u=0;for await(const f of M_(t.tree,e,c)){if(u++>=r*2)break;const p=f.slice(Os.length),d=p.indexOf(":");if(d===-1)continue;const g=p.slice(0,d),w=p.slice(d+1),x=g===o?1:0,A=Math.max(0,g.length-o.length),I=s.get(w);if(I){I.score+=1,I.exactMatches+=x,I.prefixDistance+=A,I.matchedTerms.add(g);continue}s.set(w,{score:1,exactMatches:x,prefixDistance:A,matchedTerms:new Set([g])})}}return[...s.entries()].sort((o,c)=>c[1].score!==o[1].score?c[1].score-o[1].score:c[1].exactMatches!==o[1].exactMatches?c[1].exactMatches-o[1].exactMatches:o[1].prefixDistance!==c[1].prefixDistance?o[1].prefixDistance-c[1].prefixDistance:o[0].localeCompare(c[0])).slice(0,r).map(([o,c])=>({item:{pubKey:o,name:"",aliases:[...c.matchedTerms]},score:c.score,source:"remote"}))}async function*M_(t,e,n){yield*Cd(t,e,n,N_(n))}async function*Cd(t,e,n,r){const i=O_(await t.listDirectory(e));if(D_(i)){for(const s of i){if(s.type===se.Dir)continue;const o=mi(s.name);if(!(n!==void 0&&o<n)){if(r!==void 0&&o>=r)return;yield o}}return}for(let s=0;s<i.length;s+=1){const o=i[s],c=mi(o.name),u=s<i.length-1?mi(i[s+1].name):void 0;if(!(n!==void 0&&u!==void 0&&u<=n)){if(r!==void 0&&c>=r)return;yield*Cd(t,o.cid,n,r)}}}function O_(t){return[...t].sort((e,n)=>mi(e.name).localeCompare(mi(n.name)))}function D_(t){return t.length===0||t.some(e=>e.type!==se.Dir)}function mi(t){return t.replace(/%2F/gi,"/").replace(/%00/gi,"\0").replace(/%25/g,"%")}function N_(t){if(t.length===0)return t;const e=t.charCodeAt(t.length-1);return t.slice(0,-1)+String.fromCharCode(e+1)}function Td(...t){const e=new Map;for(const n of t)for(const r of n){const i=e.get(r.item.pubKey);if(!i){e.set(r.item.pubKey,r);continue}const s=i.item.created_at??0,o=r.item.created_at??0,c=(i.item.name!==i.item.pubKey?1:0)+(i.item.nip05?1:0)+(i.item.picture?1:0)+((i.item.aliases?.length??0)>0?1:0),u=(r.item.name!==r.item.pubKey?1:0)+(r.item.nip05?1:0)+(r.item.picture?1:0)+((r.item.aliases?.length??0)>0?1:0);(o>s||o===s&&u>c)&&e.set(r.item.pubKey,{item:r.item,score:i.score??r.score})}return Array.from(e.values())}function Dl(...t){return Td(...t)}function Id(t){const{compactLength:e,keywordCount:n}=Gc(t);return n<=1&&e<=2?n_:n<=1&&e<=3?r_:i_}async function P_(t,e,n){if(!za)return null;try{return await za(t,e,n)}catch(r){return console.warn("[Relay Worker] Failed to refresh profile search tree root:",r),null}}async function Nl(t,e,n){const r=Yc(t,e),i=oa.get(r);if(i)return i;const s=(async()=>{const o=await P_(t,e,n);return o?((!n||__(o,n)>0||(!n.root||!Sd(o.root,n.root)))&&await R_(t,e,o),o):null})();return oa.set(r,s),s.finally(()=>{oa.delete(r)}),s}async function F_(t,e){if(Ns(t))return[];const n=v_();if(!n)return[];if(n.target.kind==="root")return us(n,n.target.root,t,e);const{npub:r,treeName:i}=n.target,s=await A_(r,i),o=k_(),c=S_(s,o);if(c){const f=await us(n,c.root,t,e),p=Nl(r,i,c);if(f.length>0)return f;const d=await p;if(!d||Sd(c.root,d.root))return f;const g=await us(n,d.root,t,e);return Td(f,g)}const u=await Nl(r,i,null);return u?us(n,u.root,t,e):[]}function U_(t){return Array.from(new Set(t.filter(e=>typeof e=="string"&&e.length>0)))}function $_(t){const e=t.relayUrls&&t.relayUrls.length>0?t.relayUrls:t.defaultRelayUrls,n=t.disableExtraRelayUrls?[]:t.extraRelayUrls||[];return U_([...e,...n])}const K_=["wss://temp.iris.to/","wss://vault.iris.to/","wss://relay.damus.io/","wss://relay.snort.social/","wss://relay.primal.net/","wss://nos.lol/"],z_=["wss://search.nos.today/"];function H_(t){return t.replace(/\/$/,"")}function q_(){return K_}const W_=q_(),j_=W_.map(H_);function V_(t,e){try{const n={id:t.id,sig:t.sig,pubkey:t.pubkey,content:t.content,kind:t.kind,created_at:t.created_at,tags:t.tags};return e?(e.verifyEvent(n),!0):Hr(n)}catch{return!1}}const{log:yt,warn:Zc,error:Gt}=Ib(Bb.NDK_RELAY);self.onunhandledrejection=t=>{Gt("[Relay Worker] Unhandled rejection:",t.reason),self.postMessage({type:"error",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),t.preventDefault()};let Ha=null,ca=!1,Bd=!1;async function G_(){if(!(Ha||ca)){ca=!0;try{const{initNostrWasm:t}=await import("./main-C9k9ZopU.js");Ha=await t(),yt("[Relay Worker] WASM sig verifier loaded")}catch(t){Gt("[Relay Worker] WASM load failed:",t)}finally{ca=!1}}}let tt,Pl;const vn=new Map,Y_=new Set;let qa,ls=0;async function Z_(){try{const t=performance.now(),e=await Xe.profiles.toArray(),n=[];for(const i of e){const s=Wc(i.pubkey,i,i.created_at);s&&n.push(s)}b_(n);const r=performance.now()-t;yt(`[Relay Worker] Search index initialized: ${n.length} profiles in ${r.toFixed(0)}ms`),self.postMessage({type:"searchReady"})}catch(t){Gt("[Relay Worker] Failed to init search from Dexie:",t)}}async function X_(t,e){const n=++ls,r=new Set,i=(f,p)=>{const d=JSON.stringify(f.map(g=>[g.item.pubKey,g.score??null,g.item.name,g.item.nip05??null,g.item.picture??null,g.item.created_at??null,g.item.aliases??[]]));!p&&r.has(d)||(r.add(d),self.postMessage({type:"searchResult",searchRequestId:t,searchResults:f,searchComplete:p}))},s=e.trim(),o=s?E_(s):[];if(i(o,Ns(s)),!s||Ns(s))return;const c=x_(s);if(c>0&&await new Promise(f=>setTimeout(f,c)),n!==ls){i(o,!0);return}const u=await F_(s,f=>{n===ls&&i(Dl(o,f),!1)});if(n!==ls){i(o,!0);return}i(Dl(o,u),!0)}function Ld(t){const e=n=>{yt(`[Relay Worker] ${t.url} ${n}, status: ${t.status}`),jr()};t.on("connect",()=>{Y_.add(t.url),e("connected")}),t.on("disconnect",()=>e("disconnected")),t.on("flapping",()=>e("flapping")),t.on("authed",()=>e("authed"))}function J_(t){return[]}function Q_(t){if(t.kind!==30078||!Array.isArray(t.tags))return null;const e=t.tags.some(s=>s[0]==="l"&&s[1]==="hashtree");if(t.tags.some(s=>s[0]==="l")&&!e)return null;const r=t.tags.find(s=>s[0]==="hash")?.[1];if(typeof r!="string"||!/^[0-9a-f]{64}$/i.test(r)||typeof t.id!="string"||typeof t.created_at!="number")return null;const i=t.tags.find(s=>s[0]==="key")?.[1];try{return{root:{hash:_a(r),key:i?_a(i):void 0},eventId:t.id,createdAt:t.created_at}}catch{return null}}function ek(t,e){return t.createdAt!==e.createdAt?t.createdAt-e.createdAt:t.eventId.localeCompare(e.eventId)}async function tk(t,e){try{const n=Wn.decode(t);if(n.type!=="npub"||typeof n.data!="string")return null;const r=await tt.fetchEvents({kinds:[30078],authors:[n.data],"#d":[e],limit:20}),i=[];for(const s of r??[]){const o=Q_(s.rawEvent());o&&i.push(o)}return i.sort(ek),i[i.length-1]??null}catch(n){return Zc("[Relay Worker] Failed to resolve latest profile search tree root:",n),null}}let ws,Wa,wi;const Kr=new Map;function nk(t,e){return new Promise((n,r)=>{const i=crypto.randomUUID(),s=setTimeout(()=>{Kr.delete(i),r(new Error("Authentication signing timed out"))},1e4);Kr.set(i,{resolve:o=>{clearTimeout(s),n(o)},reject:o=>{clearTimeout(s),r(o)}}),self.postMessage({type:"signAuth",id:i,event:e})})}async function rk(t,e,n=!1){try{yt("[Relay Worker] Starting initialization with relays:",t),Bd=!n&&!0,e&&(qa=e,yt("[Relay Worker] Settings initialized:",qa)),yt("[Relay Worker] Initializing event store..."),Pl=new Zx,yt("[Relay Worker] Event store ready");const r=$_({relayUrls:t,defaultRelayUrls:j_,extraRelayUrls:J_(void 0),disableExtraRelayUrls:n});yt("[Relay Worker] Creating NostrClient with relays:",r),tt=new Fb({explicitRelayUrls:r,signAuthEvent:nk,verifyEvent:i=>
3V_(i,Ha),cacheAdapter:Pl,enableOutboxModel:!1}),G_(),d_(async(i,s)=>tk(i,s)),Z_(),tt.pool?.on("notice",(i,s)=>{self.postMessage({type:"notice",relay:i.url,notice:s})}),yt("[Relay Worker] Starting relay connections..."),tt.connect().then(()=>{yt("[Relay Worker] Runtime initialized")}).catch(i=>{Gt("[Relay Worker] Relay connection error:",i)}),tt.pool?.relays.forEach(i=>{Ld(i)}),yt(`[Relay Worker] Initialized with ${tt.pool?.relays.size||0} relays`),wi&&clearInterval(wi),wi=setInterval(jr,2e3),self.postMessage({type:"ready"})}catch(r){Gt("[Relay Worker] Initialization failed:",r),self.postMessage({type:"error",error:r instanceof Error?r.message:String(r)})}}function ik(t,e,n){if(!tt){Gt("[Relay Worker] NostrClient not initialized");return}const r=vn.size;r>10&&Zc(`[Relay Worker] HIGH SUB COUNT: ${r} active subscriptions. New sub: ${t}, filters: ${JSON.stringify(e).slice(0,200)}`),yt(`[Relay Worker] handleSubscribe subId=${t}, filters=${JSON.stringify(e)}, opts=${JSON.stringify(n)}`),vn.has(t)&&vn.get(t).stop();const i=n?.destinations||["cache","relay"],s=i.includes("cache")&&!i.includes("relay"),o=i.includes("relay")&&!i.includes("cache");let c;s?c=Zo.ONLY_CACHE:o?c=Zo.ONLY_RELAY:c=Zo.PARALLEL,yt(`[Relay Worker] Using cacheUsage: ${c}`);const u=s?!1:n?.groupable??!0,f=u?n?.groupableDelay??100:void 0,p=tt.subscribe(e,{isolated:n?.isolated,relayUrls:n?.relayUrls??(Bd&&e.some(d=>!!d.search)?z_:void 0),closeOnEose:n?.closeOnEose??s,groupable:u,groupableDelay:f,cacheUsage:c,waitForCacheBeforeRelays:n?.waitForCacheBeforeRelays});p.on("event",(d,g,w,x)=>{const A=d.rawEvent();if(self.postMessage({type:"event",subId:t,event:A,relay:g?.url,fromCache:x}),A.kind===0)try{const I=JSON.parse(A.content),T=Wc(A.pubkey,I,A.created_at);T&&Js(T)}catch{}}),n?.isolated&&p.on("event:dup",(d,g,w,x,A)=>{self.postMessage({type:"event",subId:t,event:d instanceof Dt?d.rawEvent():d,relay:g?.url,fromCache:A})}),p.on("eose",()=>{self.postMessage({type:"eose",subId:t,completion:p.completion}),s&&vn.delete(t)}),vn.set(t,p)}function sk(t){const e=vn.get(t);e&&(e.stop(),vn.delete(t))}async function ok(t,e,n,r){if(!tt){self.postMessage({type:"error",id:t,error:"NostrClient not initialized"});return}try{const i=tt.getRuntime();if(!(r?.publishTo??["relay"]).includes("relay")){await i.ingest(e,r?.source??"local"),self.postMessage({type:"published",id:t});return}if(r?.connectedOnly&&(n=i.getRelayStats().filter(c=>c.connected&&(!n||n.includes(c.url))).map(c=>c.url),!n.length))throw new Error("No connected message server");const o=await i.publish(e,{relays:n,requireAck:r?.requireAck});if(r?.requireAck&&!o.remoteAccepted)throw new Error("No relay confirmed the event.");if(!o.remoteAccepted&&!o.queued)throw new Error("Publication was not accepted");self.postMessage({type:"published",id:t,publishResult:o})}catch(i){Gt("[Relay Worker] Publish failed:",i),self.postMessage({type:"error",id:t,error:i instanceof Error?i.message:String(i)})}}function Md(){return tt?tt.getRuntime().getRelayStats().map(t=>({url:t.url,status:t.connected?5:0,stats:{attempts:0,success:t.connected?1:0}})):[]}function ak(t){self.postMessage({type:"relayStatus",id:t,relayStatuses:Md()})}function jr(){const t=Md();yt(`[Relay Worker] Broadcasting status update: ${t.length} relays`),self.postMessage({type:"relayStatusUpdate",relayStatuses:t})}function ck(t){if(!tt?.pool)return;const e=new Mh(t,void 0,tt);Ld(e),tt.pool.addRelay(e),jr()}function uk(t){tt?.pool.removeRelay(t),jr()}const Xc=new Set;function Jc(){tt?.getRuntime().setRelays([...tt.pool.relays.keys()].filter(t=>!Xc.has(t))),jr()}function lk(t){Xc.delete(t),tt?.pool.getRelay(t),Jc()}function fk(t){Xc.add(t),Jc()}function Qc(t){Jc(),tt?.getRuntime().retryPending()}function hk(){tt?.getRuntime().setRelays([]),jr()}function dk(){Qc()}async function pk(t){try{if(!Xe){self.postMessage({type:"stats",id:t,stats:{totalEvents:0,eventsByKind:{}}});return}const e=await Xe.events.count(),n=await Xe.events.orderBy("kind").uniqueKeys(),r={};await Promise.all(n.map(async i=>{const s=Number(i),o=await Xe.events.where("kind").equals(s).count();r[s]=o})),self.postMessage({type:"stats",id:t,stats:{totalEvents:e,eventsByKind:r,pubsub:tt?.getRuntime().metrics()}})}catch(e){Gt("[Relay Worker] Failed to get stats:",e),self.postMessage({type:"stats",id:t,stats:{totalEvents:0,eventsByKind:{}}})}}
3function yk(){vn.forEach(t=>t.stop()),vn.clear(),wi&&clearInterval(wi),ws?.close(),Wa?.();for(const t of Kr.values())t.reject(new Error("Worker closed"));Kr.clear(),tt?.close()}function gk(t){yt("[Relay Worker] Updating settings:",t),qa=t}let ja=!1;self.addEventListener("online",()=>{ja&&(yt("[Relay Worker] Network connection restored"),ja=!1,Qc())});self.addEventListener("offline",()=>{ja=!0,yt("[Relay Worker] Network connection lost")});self.onmessage=async t=>{try{const e=t.data,{type:n,id:r,filters:i,event:s,relays:o,subscribeOpts:c,publishOpts:u}=e;switch(n){case"init":await rk(o,e.settings,e.disableExtraRelayUrls);break;case"authSigned":{const f=r?Kr.get(r):void 0;f&&r&&(Kr.delete(r),e.error?f.reject(new Error(e.error)):f.resolve(e.event));break}case"peerCache":{if(!e.port)break;Wa?.(),Wa=ob(e.port,{id:"client-cache",query:async(f,p)=>{const d=await tt.getRuntime().query(f,{...p,cache:"cache-only"});return{events:d.events.map(g=>({event:Mr(g),source:yf("client-cache"),priority:Hp})),complete:d.complete}}});break}case"peerSource":e.port&&tt&&(ws?.close(),ws=ab(e.port,"fips","queued"),tt.getRuntime().addSource(ws.source));break;case"subscribe":r&&i&&ik(r,i,c);break;case"unsubscribe":r&&sk(r);break;case"publish":r&&s&&await ok(r,s,o,u);break;case"getRelayStatus":r&&ak(r);break;case"addRelay":e.url&&ck(e.url);break;case"removeRelay":e.url&&uk(e.url);break;case"connectRelay":e.url&&lk(e.url);break;case"disconnectRelay":e.url&&fk(e.url);break;case"reconnectDisconnected":Qc(e.reason||"Reconnect requested");break;case"browserOffline":hk();break;case"browserOnline":dk();break;case"getStats":r&&pk(r);break;case"close":yk();break;case"updateSettings":e.settings&&gk(e.settings);break;case"search":e.searchQuery!==void 0&&e.searchRequestId!==void 0&&X_(e.searchRequestId,e.searchQuery).catch(f=>{Gt("[Relay Worker] Search failed:",f),self.postMessage({type:"searchResult",searchRequestId:e.searchRequestId,searchResults:[],searchComplete:!0})});break;case"ping":self.postMessage({type:"pong",id:r});break;default:Zc("[Relay Worker] Unknown message type:",n)}}catch(e){Gt("[Relay Worker] Message handler error:",e),self.postMessage({type:"error",error:e instanceof Error?e.message:String(e)})}};self.onerror=t=>{Gt("[Relay Worker] Error:",t),self.postMessage({type:"error",error:t instanceof Error?t.message:String(t)})};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.