planx 20.53.1 → 20.53.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent.main.mjs +2 -2
- package/blob.main.mjs +2 -2
- package/config.main.mjs +2 -2
- package/domain.main.mjs +2 -2
- package/exit.main.mjs +2 -2
- package/explorer.bundle.js +10 -10
- package/explorer.main.mjs +2 -2
- package/filesystem.main.mjs +2 -2
- package/llm.main.mjs +1 -1
- package/log.main.mjs +1 -1
- package/main.js +9 -9
- package/nosturn.main.mjs +1 -1
- package/package.json +6 -6
- package/planx-networkd.main.mjs +2 -2
- package/presentation.main.mjs +1 -1
- package/session.main.mjs +2 -2
- package/transport.main.mjs +2 -2
package/nosturn.main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
globalThis.__PLANX_SERVICE_VERSION__="20.53.
|
|
1
|
+
globalThis.__PLANX_SERVICE_VERSION__="20.53.2";
|
|
2
2
|
var _t={prod:{hasuraUrl:"https://graphql-prod.machina.at/v1/graphql",apiNextUrl:"https://api.machina.at",signalingUrl:"https://signaling.machina.at",firebaseDatabaseUrl:"https://x-x-machina-default-rtdb.asia-southeast1.firebasedatabase.app",webServerUrl:"https://webkernel.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable",appUrl:"https://machina.at"},stg:{hasuraUrl:"https://graphql-stg.machina.at/v1/graphql",apiNextUrl:"https://api.stg.machina.at",signalingUrl:"https://signaling-stg.machina.at",firebaseDatabaseUrl:"https://x-x-machina-stg.asia-southeast1.firebasedatabase.app",webServerUrl:"https://webkernel.machina.at",invoiceAppUrl:"https://presenter.machina.at/stable",appUrl:"https://machina.at/develop"}};var Qr={PLANX_GRAPHQL_URL:_t.prod.hasuraUrl,PLANX_CLOUD_API_URL:_t.prod.apiNextUrl,PLANX_SIGNALING_URL:_t.prod.signalingUrl,PLANX_FIREBASE_DATABASE_URL:_t.prod.firebaseDatabaseUrl,PLANX_SIGNALING_BACKEND:"",PLANX_NOSTR_RELAYS:["wss://nos.lol","wss://relay.snort.social","wss://relay.primal.net","wss://relay.mostr.pub","wss://yabu.me","wss://nostr.mom","wss://nostr.data.haus","wss://nostr-pub.wellorder.net","wss://nostr.mikoshi.de","wss://nostream.ocha.one"].join(",")};var Yi=e=>e.split(/[\n,]/).map(t=>t.trim()).filter(Boolean);function eo(e=process.env){return{portFile:e.PLANX_NOSTURN_PORT_FILE,pidFile:e.PLANX_NOSTURN_PID_FILE,serverId:e.PLANX_SERVER_ID??"",relays:Yi(e.PLANX_NOSTR_RELAYS??Qr.PLANX_NOSTR_RELAYS)}}var no=Uint8Array.of(253,110,111,115,116,117),ro=18,to=1024,Xi=e=>globalThis.crypto.getRandomValues(new Uint8Array(e));function oo(e=Xi){let t=new Uint8Array(16);t.set(no,0);let n=e(12);t.set(n.subarray(0,10),6);let r=to+(n[10]<<8|n[11])%(65536-to);return{family:6,address:t,port:r}}function so(e){return e.family===6&&no.every((t,n)=>e.address[n]===t)}function ot(e){let t=new Uint8Array(ro);return t.set(e.address.subarray(0,16),0),t[16]=e.port>>8,t[17]=e.port&255,t}function io(e){return e.length!==ro?null:{family:6,address:e.slice(0,16),port:e[16]<<8|e[17]}}function st(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function fe(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >= 0, got ${e}`)}}function M(e,t,n=""){let r=st(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Oe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");fe(e.outputLen),fe(e.blockLen)}function Ke(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function co(e,t){M(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function ce(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function me(e,t){return e<<32-t|e>>>t}function it(e,t){return e<<t|e>>>32-t>>>0}var lo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ji=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function P(e){if(M(e),lo)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ji[e[n]];return t}var Se={_0:48,_9:57,A:65,F:70,a:97,f:102};function ao(e){if(e>=Se._0&&e<=Se._9)return e-Se._0;if(e>=Se.A&&e<=Se.F)return e-(Se.A-10);if(e>=Se.a&&e<=Se.f)return e-(Se.a-10)}function $(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(lo)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){let i=ao(e.charCodeAt(s)),a=ao(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function X(...e){let t=0;for(let r=0;r<e.length;r++){let o=e[r];M(o),t+=o.length}let n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){let s=e[r];n.set(s,o),o+=s.length}return n}function at(e,t={}){let n=(o,s)=>e(s).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function ge(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var uo=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function We(e,t,n){return e&t^~e&n}function kt(e,t,n){return e&t^e&n^t&n}var Pe=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Bt(this.buffer)}update(t){Ke(this),M(t);let{view:n,buffer:r,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Bt(t);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ke(this),co(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:s}=this,{pos:i}=this;n[i++]=128,ce(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let f=i;f<o;f++)n[f]=0;r.setBigUint64(o-8,BigInt(this.length*8),s),this.process(r,0);let a=Bt(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Ae=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Qi=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]),Ue=new Uint32Array(64),yn=class extends Pe{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[t,n,r,o,s,i,a,c]}set(t,n,r,o,s,i,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,n){for(let f=0;f<16;f++,n+=4)Ue[f]=t.getUint32(n,!1);for(let f=16;f<64;f++){let h=Ue[f-15],d=Ue[f-2],m=me(h,7)^me(h,18)^h>>>3,g=me(d,17)^me(d,19)^d>>>10;Ue[f]=g+Ue[f-7]+m+Ue[f-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=me(a,6)^me(a,11)^me(a,25),d=u+h+We(a,c,l)+Qi[f]+Ue[f]|0,g=(me(r,2)^me(r,13)^me(r,22))+kt(r,o,s)|0;u=l,l=c,c=a,a=i+d|0,i=s,s=o,o=r,r=d+g|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,s,i,a,c,l,u)}roundClean(){ce(Ue)}destroy(){this.set(0,0,0,0,0,0,0,0),ce(this.buffer)}},bn=class extends yn{A=Ae[0]|0;B=Ae[1]|0;C=Ae[2]|0;D=Ae[3]|0;E=Ae[4]|0;F=Ae[5]|0;G=Ae[6]|0;H=Ae[7]|0;constructor(){super(32)}};var ee=at(()=>new bn,uo(1));var ct="x",je=12,ea=new TextEncoder().encode("nosturn/tag\0"),ta=new TextEncoder().encode("nosturn/key\0");function fo(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),ee(n)}var na=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function lt(e){return na(fo(ea,e).subarray(0,16))}function ho(e){let t=Uint8Array.from(fo(ta,e));return globalThis.crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}var po=e=>Uint8Array.from(new TextEncoder().encode(lt(e)));async function mo(e,t){let n=globalThis.crypto.getRandomValues(new Uint8Array(je)),r=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:po(e)},await ho(e),Uint8Array.from(t))),o=new Uint8Array(je+r.length);return o.set(n,0),o.set(r,je),Buffer.from(o).toString("base64")}async function go(e,t){let n=Uint8Array.from(Buffer.from(t,"base64"));if(n.length<=je+16)return null;try{let r=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:n.subarray(0,je),additionalData:po(e)},await ho(e),n.subarray(je));return new Uint8Array(r)}catch{return null}}function yo(e){let t=e.receipts.slice(0,255),n=25+t.length*11+e.packets.reduce((i,a)=>i+2+a.length,0),r=new Uint8Array(n),o=new DataView(r.buffer);r[0]=2,r.set(e.src18.subarray(0,18),1),o.setUint32(19,e.seq>>>0),r[23]=e.path&255,r[24]=t.length;let s=25;for(let i of t)r[s]=i.path&255,o.setUint32(s+1,i.recv>>>0),o.setUint32(s+5,i.lastSeq>>>0),o.setUint16(s+9,Math.min(65535,Math.max(0,Math.round(i.holdMs)))),s+=11;for(let i of e.packets)o.setUint16(s,i.length),r.set(i,s+2),s+=2+i.length;return r}function bo(e){if(e.length<25||e[0]!==2)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=e[24],r=25;if(r+n*11>e.length)return null;let o=[];for(let i=0;i<n;i++,r+=11)o.push({path:e[r],recv:t.getUint32(r+1),lastSeq:t.getUint32(r+5),holdMs:t.getUint16(r+9)});let s=[];for(;r<e.length;){if(r+2>e.length)return null;let i=t.getUint16(r);if(r+2+i>e.length)return null;s.push(e.slice(r+2,r+2+i)),r+=2+i}return{src18:e.slice(1,19),seq:t.getUint32(19),path:e[23],receipts:o,packets:s}}function ra(e){let[t,n,r]=e.split("::");if(r!==void 0)return null;let o=t?t.split(":"):[],s=n!==void 0&&n?n.split(":"):[],i=n===void 0?0:8-o.length-s.length,a=[...o,...Array(Math.max(i,0)).fill("0"),...s];if(a.length!==8||a.some(l=>!/^[0-9a-f]{1,4}$/i.test(l)))return null;let c=new Uint8Array(16);return a.forEach((l,u)=>{let f=parseInt(l,16);c[u*2]=f>>8,c[u*2+1]=f&255}),c}function oa(e){let t=e.split(".");return t.length!==4||t.some(n=>!/^\d{1,3}$/.test(n)||Number(n)>255)?null:Uint8Array.from(t.map(Number))}function wn(e,t){let n=oa(e.startsWith("::ffff:")?e.slice(7):e);if(n)return{family:4,address:n,port:t};let r=ra(e);return r?{family:6,address:r,port:t}:null}function wo(e){if(e.family===4)return[...e.address].join(".");let t=[];for(let n=0;n<16;n+=2)t.push((e.address[n]<<8|e.address[n+1]).toString(16));return t.join(":")}function xe(e){return e.family===6?`[${wo(e)}]:${e.port}`:`${wo(e)}:${e.port}`}var vn=BigInt(0),xn=BigInt(1);function ut(e,t=""){if(typeof e!="boolean"){let n=t&&`"${t}" `;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function xo(e){if(typeof e=="bigint"){if(!Ut(e))throw new Error("positive bigint expected, got "+e)}else fe(e);return e}function ft(e){let t=xo(e).toString(16);return t.length&1?"0"+t:t}function vo(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?vn:BigInt("0x"+e)}function Le(e){return vo(P(e))}function En(e){return vo(P(sa(M(e)).reverse()))}function Lt(e,t){fe(t),e=xo(e);let n=$(e.toString(16).padStart(t*2,"0"));if(n.length!==t)throw new Error("number too large");return n}function Sn(e,t){return Lt(e,t).reverse()}function sa(e){return Uint8Array.from(e)}function Eo(e){return Uint8Array.from(e,(t,n)=>{let r=t.charCodeAt(0);if(t.length!==1||r>127)throw new Error(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r})}var Ut=e=>typeof e=="bigint"&&vn<=e;function ia(e,t,n){return Ut(e)&&Ut(t)&&Ut(n)&&t<=e&&e<n}function So(e,t,n,r){if(!ia(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function An(e){let t;for(t=0;e>vn;e>>=xn,t+=1);return t}var dt=e=>(xn<<BigInt(e))-xn;function Ao(e,t,n){if(fe(e,"hashLen"),fe(t,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");let r=p=>new Uint8Array(p),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=r(e),l=r(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},h=(...p)=>n(l,X(c,...p)),d=(p=o)=>{l=h(s,p),c=h(),p.length!==0&&(l=h(i,p),c=h())},m=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let p=0,y=[];for(;p<t;){c=h();let E=c.slice();y.push(E),p+=c.length}return X(...y)};return(p,y)=>{f(),d(p);let E;for(;!(E=y(m()));)d();return f(),E}}function ht(e,t={},n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(s,i,a){let c=e[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>r(a,c,i));o(t,!1),o(n,!0)}function Tn(e){let t=new WeakMap;return(n,...r)=>{let o=t.get(n);if(o!==void 0)return o;let s=e(n,...r);return t.set(n,s),s}}var ae=BigInt(0),ie=BigInt(1),He=BigInt(2),_o=BigInt(3),Bo=BigInt(4),ko=BigInt(5),aa=BigInt(7),Uo=BigInt(8),ca=BigInt(9),Lo=BigInt(16);function ye(e,t){let n=e%t;return n>=ae?n:t+n}function ue(e,t,n){let r=e;for(;t-- >ae;)r*=r,r%=n;return r}function To(e,t){if(e===ae)throw new Error("invert: expected non-zero number");if(t<=ae)throw new Error("invert: expected positive modulus, got "+t);let n=ye(e,t),r=t,o=ae,s=ie,i=ie,a=ae;for(;n!==ae;){let l=r/n,u=r%n,f=o-i*l,h=s-a*l;r=n,n=u,o=i,s=a,i=f,a=h}if(r!==ie)throw new Error("invert: does not exist");return ye(o,t)}function _n(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Co(e,t){let n=(e.ORDER+ie)/Bo,r=e.pow(t,n);return _n(e,r,t),r}function la(e,t){let n=(e.ORDER-ko)/Uo,r=e.mul(t,He),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,He),o),a=e.mul(s,e.sub(i,e.ONE));return _n(e,a,t),a}function ua(e){let t=ze(e),n=Io(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+aa)/Lo;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,r),f=a.mul(l,o),h=a.mul(l,s),d=a.eql(a.sqr(u),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,u,d),u=a.cmov(h,f,m);let g=a.eql(a.sqr(u),c),p=a.cmov(l,u,g);return _n(a,p,c),p}}function Io(e){if(e<_o)throw new Error("sqrt is not defined for small field");let t=e-ie,n=0;for(;t%He===ae;)t/=He,n++;let r=He,o=ze(e);for(;Ro(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Co;let s=o.pow(r,t),i=(t+ie)/He;return function(c,l){if(c.is0(l))return l;if(Ro(c,l)!==1)throw new Error("Cannot find square root");let u=n,f=c.mul(c.ONE,s),h=c.pow(l,t),d=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let m=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");let p=ie<<BigInt(u-m-1),y=c.pow(f,p);u=m,f=c.sqr(y),h=c.mul(h,f),d=c.mul(d,y)}return d}}function fa(e){return e%Bo===_o?Co:e%Uo===ko?la:e%Lo===ca?ua(e):Io(e)}var da=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bn(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},n=da.reduce((r,o)=>(r[o]="function",r),t);return ht(e,n),e}function ha(e,t,n){if(n<ae)throw new Error("invalid exponent, negatives unsupported");if(n===ae)return e.ONE;if(n===ie)return t;let r=e.ONE,o=t;for(;n>ae;)n&ie&&(r=e.mul(r,o)),o=e.sqr(o),n>>=ie;return r}function Ct(e,t,n=!1){let r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(r[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(r[c]=e.mul(i,r[c]),e.mul(i,a)),s),r}function Ro(e,t){let n=(e.ORDER-ie)/He,r=e.pow(t,n),o=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function pa(e,t){t!==void 0&&fe(t);let n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var Rn=class{ORDER;BITS;BYTES;isLE;ZERO=ae;ONE=ie;_lengths;_sqrt;_mod;constructor(t,n={}){if(t<=ae)throw new Error("invalid field: expected ORDER > 0, got "+t);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));let{nBitLength:o,nByteLength:s}=pa(t,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return ye(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return ae<=t&&t<this.ORDER}is0(t){return t===ae}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&ie)===ie}neg(t){return ye(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return ye(t*t,this.ORDER)}add(t,n){return ye(t+n,this.ORDER)}sub(t,n){return ye(t-n,this.ORDER)}mul(t,n){return ye(t*n,this.ORDER)}pow(t,n){return ha(this,t,n)}div(t,n){return ye(t*To(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return To(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=fa(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Sn(t,this.BYTES):Lt(t,this.BYTES)}fromBytes(t,n=!1){M(t);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let l=new Uint8Array(o);l.set(t,s?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?En(t):Le(t);if(a&&(c=ye(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ct(this,t)}cmov(t,n,r){return r?n:t}};function ze(e,t={}){return new Rn(e,t)}function No(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function kn(e){let t=No(e);return t+Math.ceil(t/2)}function It(e,t,n=!1){M(e);let r=e.length,o=No(t),s=kn(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);let i=n?En(e):Le(e),a=ye(i,t-ie)+ie;return n?Sn(a,o):Lt(a,o)}var Ze=BigInt(0),De=BigInt(1);function pt(e,t){let n=t.negate();return e?n:t}function In(e,t){let n=Ct(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function Ho(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Un(e,t){Ho(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,s=dt(e),i=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function Mo(e,t,n){let{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n,a=Number(e&o),c=e>>i;a>r&&(a-=s,c+=De);let l=t*r,u=l+Math.abs(a)-1,f=a===0,h=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:h,isNegF:d,offsetF:l}}var Ln=new WeakMap,Do=new WeakMap;function Cn(e){return Do.get(e)||1}function Oo(e){if(e!==Ze)throw new Error("invalid wNAF")}var Nt=class{BASE;ZERO;Fn;bits;constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>Ze;)n&De&&(r=r.add(o)),o=o.double(),n>>=De;return r}precomputeWindow(t,n){let{windows:r,windowSize:o}=Un(n,this.bits),s=[],i=t,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Un(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:h,offsetF:d}=Mo(r,a,i);r=c,u?s=s.add(pt(h,n[d])):o=o.add(pt(f,n[l]))}return Oo(r),{p:o,f:s}}wNAFUnsafe(t,n,r,o=this.ZERO){let s=Un(t,this.bits);for(let i=0;i<s.windows&&r!==Ze;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Mo(r,i,s);if(r=a,!l){let f=n[c];o=o.add(u?f.negate():f)}}return Oo(r),o}getPrecomputes(t,n,r){let o=Ln.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),Ln.set(n,o))),o}cached(t,n,r){let o=Cn(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){let s=Cn(t);return s===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,o)}createCache(t,n){Ho(n,this.bits),Do.set(t,n),Ln.delete(t)}hasCache(t){return Cn(t)!==1}};function qo(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>Ze||r>Ze;)n&De&&(s=s.add(o)),r&De&&(i=i.add(o)),o=o.double(),n>>=De,r>>=De;return{p1:s,p2:i}}function Po(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Bn(t),t}else return ze(e,{isLE:n})}function Fo(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>Ze))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Po(t.p,n.Fp,r),s=Po(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Mt(e,t){return function(r){let o=e(r);return{secretKey:o,publicKey:t(o)}}}var Ot=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,n){if(Oe(t),M(n,void 0,"key"),this.iHash=t.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;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ce(o)}update(t){return Ke(this),this.iHash.update(t),this}digestInto(t){Ke(this),M(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ve=(e,t,n)=>new Ot(e,t).update(n).digest();ve.create=(e,t)=>new Ot(e,t);var $o=(e,t)=>(e+(e>=0?t:-t)/Vo)/t;function ma(e,t,n){let[[r,o],[s,i]]=t,a=$o(i*e,n),c=$o(-o*e,n),l=e-a*r-c*s,u=-a*o-c*i,f=l<Te,h=u<Te;f&&(l=-l),h&&(u=-u);let d=dt(Math.ceil(An(n)/2))+Ye;if(l<Te||l>=d||u<Te||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:l,k2neg:h,k2:u}}function Mn(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Nn(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return ut(n.lowS,"lowS"),ut(n.prehash,"prehash"),n.format!==void 0&&Mn(n.format),n}var On=class extends Error{constructor(t=""){super(t)}},Ce={Err:On,_tlv:{encode:(e,t)=>{let{Err:n}=Ce;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");let r=t.length/2,o=ft(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let s=r>127?ft(o.length/2|128):"";return ft(e)+s+o+t},decode(e,t){let{Err:n}=Ce,r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");let o=t[r++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}let a=t.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+i)}}},_int:{encode(e){let{Err:t}=Ce;if(e<Te)throw new t("integer: negative integers are not allowed");let n=ft(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){let{Err:t}=Ce;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Le(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=Ce,o=M(e,void 0,"signature"),{v:s,l:i}=r.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){let{_tlv:t,_int:n}=Ce,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),s=r+o;return t.encode(48,s)}},Te=BigInt(0),Ye=BigInt(1),Vo=BigInt(2),Pt=BigInt(3),ga=BigInt(4);function Go(e,t={}){let n=Fo("weierstrass",e,t),{Fp:r,Fn:o}=n,s=n.CURVE,{h:i,n:a}=s;ht(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Wo(r,o);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(C,x,w){let{x:b,y:S}=x.toAffine(),R=r.toBytes(b);if(ut(w,"isCompressed"),w){u();let _=!r.isOdd(S);return X(Ko(_),R)}else return X(Uint8Array.of(4),R,r.toBytes(S))}function h(C){M(C,void 0,"Point");let{publicKey:x,publicKeyUncompressed:w}=l,b=C.length,S=C[0],R=C.subarray(1);if(b===x&&(S===2||S===3)){let _=r.fromBytes(R);if(!r.isValid(_))throw new Error("bad point: is not on curve, wrong x");let v=g(_),T;try{T=r.sqrt(v)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();let B=r.isOdd(T);return(S&1)===1!==B&&(T=r.neg(T)),{x:_,y:T}}else if(b===w&&S===4){let _=r.BYTES,v=r.fromBytes(R.subarray(0,_)),T=r.fromBytes(R.subarray(_,_*2));if(!p(v,T))throw new Error("bad point: is not on curve");return{x:v,y:T}}else throw new Error(`bad point: got length ${b}, expected compressed=${x} or uncompressed=${w}`)}let d=t.toBytes||f,m=t.fromBytes||h;function g(C){let x=r.sqr(C),w=r.mul(x,C);return r.add(r.add(w,r.mul(C,s.a)),s.b)}function p(C,x){let w=r.sqr(x),b=g(C);return r.eql(w,b)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=r.mul(r.pow(s.a,Pt),ga),E=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(y,E)))throw new Error("bad curve params: a or b");function A(C,x,w=!1){if(!r.isValid(x)||w&&r.is0(x))throw new Error(`bad point coordinate ${C}`);return x}function I(C){if(!(C instanceof L))throw new Error("Weierstrass Point expected")}function q(C){if(!c||!c.basises)throw new Error("no endo");return ma(C,c.basises,o.ORDER)}let O=Tn((C,x)=>{let{X:w,Y:b,Z:S}=C;if(r.eql(S,r.ONE))return{x:w,y:b};let R=C.is0();x==null&&(x=R?r.ONE:r.inv(S));let _=r.mul(w,x),v=r.mul(b,x),T=r.mul(S,x);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(T,r.ONE))throw new Error("invZ was invalid");return{x:_,y:v}}),V=Tn(C=>{if(C.is0()){if(t.allowInfinityPoint&&!r.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x,y:w}=C.toAffine();if(!r.isValid(x)||!r.isValid(w))throw new Error("bad point: x or y not field elements");if(!p(x,w))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function H(C,x,w,b,S){return w=new L(r.mul(w.X,C),w.Y,w.Z),x=pt(b,x),w=pt(S,w),x.add(w)}class L{static BASE=new L(s.Gx,s.Gy,r.ONE);static ZERO=new L(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(x,w,b){this.X=A("x",x),this.Y=A("y",w,!0),this.Z=A("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:w,y:b}=x||{};if(!x||!r.isValid(w)||!r.isValid(b))throw new Error("invalid affine point");if(x instanceof L)throw new Error("projective point not allowed");return r.is0(w)&&r.is0(b)?L.ZERO:new L(w,b,r.ONE)}static fromBytes(x){let w=L.fromAffine(m(M(x,void 0,"point")));return w.assertValidity(),w}static fromHex(x){return L.fromBytes($(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,w=!0){return D.createCache(this,x),w||this.multiply(Pt),this}assertValidity(){V(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){I(x);let{X:w,Y:b,Z:S}=this,{X:R,Y:_,Z:v}=x,T=r.eql(r.mul(w,v),r.mul(R,S)),B=r.eql(r.mul(b,v),r.mul(_,S));return T&&B}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:w}=s,b=r.mul(w,Pt),{X:S,Y:R,Z:_}=this,v=r.ZERO,T=r.ZERO,B=r.ZERO,U=r.mul(S,S),K=r.mul(R,R),F=r.mul(_,_),N=r.mul(S,R);return N=r.add(N,N),B=r.mul(S,_),B=r.add(B,B),v=r.mul(x,B),T=r.mul(b,F),T=r.add(v,T),v=r.sub(K,T),T=r.add(K,T),T=r.mul(v,T),v=r.mul(N,v),B=r.mul(b,B),F=r.mul(x,F),N=r.sub(U,F),N=r.mul(x,N),N=r.add(N,B),B=r.add(U,U),U=r.add(B,U),U=r.add(U,F),U=r.mul(U,N),T=r.add(T,U),F=r.mul(R,_),F=r.add(F,F),U=r.mul(F,N),v=r.sub(v,U),B=r.mul(F,K),B=r.add(B,B),B=r.add(B,B),new L(v,T,B)}add(x){I(x);let{X:w,Y:b,Z:S}=this,{X:R,Y:_,Z:v}=x,T=r.ZERO,B=r.ZERO,U=r.ZERO,K=s.a,F=r.mul(s.b,Pt),N=r.mul(w,R),W=r.mul(b,_),Y=r.mul(S,v),ne=r.add(w,b),j=r.add(R,_);ne=r.mul(ne,j),j=r.add(N,W),ne=r.sub(ne,j),j=r.add(w,S);let se=r.add(R,v);return j=r.mul(j,se),se=r.add(N,Y),j=r.sub(j,se),se=r.add(b,S),T=r.add(_,v),se=r.mul(se,T),T=r.add(W,Y),se=r.sub(se,T),U=r.mul(K,j),T=r.mul(F,Y),U=r.add(T,U),T=r.sub(W,U),U=r.add(W,U),B=r.mul(T,U),W=r.add(N,N),W=r.add(W,N),Y=r.mul(K,Y),j=r.mul(F,j),W=r.add(W,Y),Y=r.sub(N,Y),Y=r.mul(K,Y),j=r.add(j,Y),N=r.mul(W,j),B=r.add(B,N),N=r.mul(se,j),T=r.mul(ne,T),T=r.sub(T,N),N=r.mul(ne,W),U=r.mul(se,U),U=r.add(U,N),new L(T,B,U)}subtract(x){return this.add(x.negate())}is0(){return this.equals(L.ZERO)}multiply(x){let{endo:w}=t;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let b,S,R=_=>D.cached(this,_,v=>In(L,v));if(w){let{k1neg:_,k1:v,k2neg:T,k2:B}=q(x),{p:U,f:K}=R(v),{p:F,f:N}=R(B);S=K.add(N),b=H(w.beta,U,F,_,T)}else{let{p:_,f:v}=R(x);b=_,S=v}return In(L,[b,S])[0]}multiplyUnsafe(x){let{endo:w}=t,b=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Te||b.is0())return L.ZERO;if(x===Ye)return b;if(D.hasCache(this))return this.multiply(x);if(w){let{k1neg:S,k1:R,k2neg:_,k2:v}=q(x),{p1:T,p2:B}=qo(L,b,R,v);return H(w.beta,T,B,S,_)}else return D.unsafe(b,x)}toAffine(x){return O(this,x)}isTorsionFree(){let{isTorsionFree:x}=t;return i===Ye?!0:x?x(L,this):D.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=t;return i===Ye?this:x?x(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return ut(x,"isCompressed"),this.assertValidity(),d(L,this,x)}toHex(x=!0){return P(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let G=o.BITS,D=new Nt(L,t.endo?Math.ceil(G/2):G);return L.BASE.precompute(8),L}function Ko(e){return Uint8Array.of(e?2:3)}function Wo(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ya(e,t={}){let{Fn:n}=e,r=t.randomBytes||ge,o=Object.assign(Wo(e.Fp,n),{seed:kn(n.ORDER)});function s(d){try{let m=n.fromBytes(d);return n.isValidNot0(m)}catch{return!1}}function i(d,m){let{publicKey:g,publicKeyUncompressed:p}=o;try{let y=d.length;return m===!0&&y!==g||m===!1&&y!==p?!1:!!e.fromBytes(d)}catch{return!1}}function a(d=r(o.seed)){return It(M(d,o.seed,"seed"),n.ORDER)}function c(d,m=!0){return e.BASE.multiply(n.fromBytes(d)).toBytes(m)}function l(d){let{secretKey:m,publicKey:g,publicKeyUncompressed:p}=o;if(!st(d)||"_lengths"in n&&n._lengths||m===g)return;let y=M(d,void 0,"key").length;return y===g||y===p}function u(d,m,g=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let p=n.fromBytes(d);return e.fromBytes(m).multiply(p).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=Mt(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:e,utils:f,lengths:o})}function jo(e,t,n={}){Oe(t),ht(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);let r=n.randomBytes||ge,o=n.hmac||((w,b)=>ve(t,w,b)),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:d}=ya(e,n),m={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},g=a*Vo<s.ORDER;function p(w){let b=a>>Ye;return w>b}function y(w,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function E(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(w,b){Mn(b);let S=d.signature,R=b==="compact"?S:b==="recovered"?S+1:void 0;return M(w,R)}class I{r;s;recovery;constructor(b,S,R){if(this.r=y("r",b),this.s=y("s",S),R!=null){if(E(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(b,S=m.format){A(b,S);let R;if(S==="der"){let{r:B,s:U}=Ce.toSig(M(b));return new I(B,U)}S==="recovered"&&(R=b[0],S="compact",b=b.subarray(1));let _=d.signature/2,v=b.subarray(0,_),T=b.subarray(_,_*2);return new I(i.fromBytes(v),i.fromBytes(T),R)}static fromHex(b,S){return this.fromBytes($(b),S)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new I(this.r,this.s,b)}recoverPublicKey(b){let{r:S,s:R}=this,_=this.assertRecovery(),v=_===2||_===3?S+a:S;if(!s.isValid(v))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=s.toBytes(v),B=e.fromBytes(X(Ko((_&1)===0),T)),U=i.inv(v),K=O(M(b,void 0,"msgHash")),F=i.create(-K*U),N=i.create(R*U),W=e.BASE.multiplyUnsafe(F).add(B.multiplyUnsafe(N));if(W.is0())throw new Error("invalid recovery: point at infinify");return W.assertValidity(),W}hasHighS(){return p(this.s)}toBytes(b=m.format){if(Mn(b),b==="der")return $(Ce.hexFromSig(this));let{r:S,s:R}=this,_=i.toBytes(S),v=i.toBytes(R);return b==="recovered"?(E(),X(Uint8Array.of(this.assertRecovery()),_,v)):X(_,v)}toHex(b){return P(this.toBytes(b))}}let q=n.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let S=Le(b),R=b.length*8-c;return R>0?S>>BigInt(R):S},O=n.bits2int_modN||function(b){return i.create(q(b))},V=dt(c);function H(w){return So("num < 2^"+c,w,Te,V),i.toBytes(w)}function L(w,b){return M(w,void 0,"message"),b?M(t(w),void 0,"prehashed message"):w}function G(w,b,S){let{lowS:R,prehash:_,extraEntropy:v}=Nn(S,m);w=L(w,_);let T=O(w),B=i.fromBytes(b);if(!i.isValidNot0(B))throw new Error("invalid private key");let U=[H(B),H(T)];if(v!=null&&v!==!1){let W=v===!0?r(d.secretKey):v;U.push(M(W,void 0,"extraEntropy"))}let K=X(...U),F=T;function N(W){let Y=q(W);if(!i.isValidNot0(Y))return;let ne=i.inv(Y),j=e.BASE.multiply(Y).toAffine(),se=i.create(j.x);if(se===Te)return;let Rt=i.create(ne*i.create(F+se*B));if(Rt===Te)return;let Xr=(j.x===se?0:2)|Number(j.y&Ye),Jr=Rt;return R&&p(Rt)&&(Jr=i.neg(Rt),Xr^=1),new I(se,Jr,g?void 0:Xr)}return{seed:K,k2sig:N}}function D(w,b,S={}){let{seed:R,k2sig:_}=G(w,b,S);return Ao(t.outputLen,i.BYTES,o)(R,_).toBytes(S.format)}function C(w,b,S,R={}){let{lowS:_,prehash:v,format:T}=Nn(R,m);if(S=M(S,void 0,"publicKey"),b=L(b,v),!st(w)){let B=w instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+B)}A(w,T);try{let B=I.fromBytes(w,T),U=e.fromBytes(S);if(_&&B.hasHighS())return!1;let{r:K,s:F}=B,N=O(b),W=i.inv(F),Y=i.create(N*W),ne=i.create(K*W),j=e.BASE.multiplyUnsafe(Y).add(U.multiplyUnsafe(ne));return j.is0()?!1:i.create(j.x)===K}catch{return!1}}function x(w,b,S={}){let{prehash:R}=Nn(S,m);return b=L(b,R),I.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:h,lengths:d,Point:e,sign:D,verify:C,recoverPublicKey:x,Signature:I,hash:t})}var qt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ba={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},wa=BigInt(0),Pn=BigInt(2);function xa(e){let t=qt.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,f=ue(u,n,t)*u%t,h=ue(f,n,t)*u%t,d=ue(h,Pn,t)*l%t,m=ue(d,o,t)*d%t,g=ue(m,s,t)*m%t,p=ue(g,a,t)*g%t,y=ue(p,c,t)*p%t,E=ue(y,a,t)*g%t,A=ue(E,n,t)*u%t,I=ue(A,i,t)*m%t,q=ue(I,r,t)*l%t,O=ue(q,Pn,t);if(!Ht.eql(Ht.sqr(O),e))throw new Error("Cannot find square root");return O}var Ht=ze(qt.p,{sqrt:xa}),qe=Go(qt,{Fp:Ht,endo:ba}),gt=jo(qe,ee),zo={};function Dt(e,...t){let n=zo[e];if(n===void 0){let r=ee(Eo(e));n=X(r,r),zo[e]=n}return ee(X(n,...t))}var Dn=e=>e.toBytes(!0).slice(1),qn=e=>e%Pn===wa;function Hn(e){let{Fn:t,BASE:n}=qe,r=t.fromBytes(e),o=n.multiply(r);return{scalar:qn(o.y)?r:t.neg(r),bytes:Dn(o)}}function Yo(e){let t=Ht;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x \u2265 p");let n=t.create(e*e),r=t.create(n*e+BigInt(7)),o=t.sqrt(r);qn(o)||(o=t.neg(o));let s=qe.fromAffine({x:e,y:o});return s.assertValidity(),s}var mt=Le;function Xo(...e){return qe.Fn.create(mt(Dt("BIP0340/challenge",...e)))}function Zo(e){return Hn(e).bytes}function va(e,t,n=ge(32)){let{Fn:r}=qe,o=M(e,void 0,"message"),{bytes:s,scalar:i}=Hn(t),a=M(n,32,"auxRand"),c=r.toBytes(i^mt(Dt("BIP0340/aux",a))),l=Dt("BIP0340/nonce",c,s,o),{bytes:u,scalar:f}=Hn(l),h=Xo(u,s,o),d=new Uint8Array(64);if(d.set(u,0),d.set(r.toBytes(r.create(f+h*i)),32),!Jo(d,o,s))throw new Error("sign: Invalid signature produced");return d}function Jo(e,t,n){let{Fp:r,Fn:o,BASE:s}=qe,i=M(e,64,"signature"),a=M(t,void 0,"message"),c=M(n,32,"publicKey");try{let l=Yo(mt(c)),u=mt(i.subarray(0,32));if(!r.isValidNot0(u))return!1;let f=mt(i.subarray(32,64));if(!o.isValidNot0(f))return!1;let h=Xo(o.toBytes(u),Dn(l),a),d=s.multiplyUnsafe(f).add(l.multiplyUnsafe(o.neg(h))),{x:m,y:g}=d.toAffine();return!(d.is0()||!qn(g)||m!==u)}catch{return!1}}var Xe=(()=>{let n=(r=ge(48))=>It(r,qt.n);return{keygen:Mt(n,Zo),getPublicKey:Zo,sign:va,verify:Jo,Point:qe,utils:{randomSecretKey:n,taggedHash:Dt,lift_x:Yo,pointToBytes:Dn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Gn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ea(e){if(!Gn(e))throw new Error("Uint8Array expected")}function ns(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(n=>typeof n=="string"):t.every(n=>Number.isSafeInteger(n)):!1}function Sa(e){if(typeof e!="function")throw new Error("function expected");return!0}function Fe(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function Kn(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Fn(e){if(!Array.isArray(e))throw new Error("array expected")}function $t(e,t){if(!ns(!0,t))throw new Error(`${e}: array of strings expected`)}function rs(e,t){if(!ns(!1,t))throw new Error(`${e}: array of numbers expected`)}function os(...e){let t=s=>s,n=(s,i)=>a=>s(i(a)),r=e.map(s=>s.encode).reduceRight(n,t),o=e.map(s=>s.decode).reduce(n,t);return{encode:r,decode:o}}function ss(e){let t=typeof e=="string"?e.split(""):e,n=t.length;$t("alphabet",t);let r=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(Fn(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:o=>(Fn(o),o.map(s=>{Fe("alphabet.decode",s);let i=r.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function is(e=""){return Fe("join",e),{encode:t=>($t("join.decode",t),t.join(e)),decode:t=>(Fe("join.decode",t),t.split(e))}}function Aa(e,t="="){return Kn(e),Fe("padding",t),{encode(n){for($t("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){$t("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}var as=(e,t)=>t===0?e:as(t,e%t),Vt=(e,t)=>e+(t-as(e,t)),Ft=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function $n(e,t,n,r){if(Fn(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Vt(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Vt(t,n)}`);let o=0,s=0,i=Ft[t],a=Ft[n]-1,c=[];for(let l of e){if(Kn(l),l>=i)throw new Error(`convertRadix2: invalid data word=${l} from=${t}`);if(o=o<<t|l,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((o>>s-n&a)>>>0);let u=Ft[s];if(u===void 0)throw new Error("invalid carry");o&=u-1}if(o=o<<n-s&a,!r&&s>=t)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&s>0&&c.push(o>>>0),c}function cs(e,t=!1){if(Kn(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Vt(8,e)>32||Vt(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Gn(n))throw new Error("radix2.encode input should be Uint8Array");return $n(Array.from(n),8,e,!t)},decode:n=>(rs("radix2.decode",n),Uint8Array.from($n(n,e,8,t)))}}function Qo(e){return Sa(e),function(...t){try{return e.apply(null,t)}catch{}}}var Ta=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Ra=(e,t)=>{Fe("base64",e);let n=t?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=t?"base64url":"base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},be=Ta?{encode(e){return Ea(e),e.toBase64()},decode(e){return Ra(e,!1)}}:os(cs(6),ss("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Aa(6),is(""));var Vn=os(ss("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),is("")),es=[996825010,642813549,513874426,1027748829,705979059];function yt(e){let t=e>>25,n=(e&33554431)<<5;for(let r=0;r<es.length;r++)(t>>r&1)===1&&(n^=es[r]);return n}function ts(e,t,n=1){let r=e.length,o=1;for(let s=0;s<r;s++){let i=e.charCodeAt(s);if(i<33||i>126)throw new Error(`Invalid prefix (${e})`);o=yt(o)^i>>5}o=yt(o);for(let s=0;s<r;s++)o=yt(o)^e.charCodeAt(s)&31;for(let s of t)o=yt(o)^s;for(let s=0;s<6;s++)o=yt(o);return o^=n,Vn.encode($n([o%Ft[30]],30,5,!1))}function _a(e){let t=e==="bech32"?1:734539939,n=cs(5),r=n.decode,o=n.encode,s=Qo(r);function i(f,h,d=90){Fe("bech32.encode prefix",f),Gn(h)&&(h=Array.from(h)),rs("bech32.encode",h);let m=f.length;if(m===0)throw new TypeError(`Invalid prefix length ${m}`);let g=m+7+h.length;if(d!==!1&&g>d)throw new TypeError(`Length ${g} exceeds limit ${d}`);let p=f.toLowerCase(),y=ts(p,h,t);return`${p}1${Vn.encode(h)}${y}`}function a(f,h=90){Fe("bech32.decode input",f);let d=f.length;if(d<8||h!==!1&&d>h)throw new TypeError(`invalid string length: ${d} (${f}). Expected (8..${h})`);let m=f.toLowerCase();if(f!==m&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let g=m.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');let p=m.slice(0,g),y=m.slice(g+1);if(y.length<6)throw new Error("Data must be at least 6 characters long");let E=Vn.decode(y).slice(0,-6),A=ts(p,E,t);if(!y.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:p,words:E}}let c=Qo(a);function l(f){let{prefix:h,words:d}=a(f,!1);return{prefix:h,words:d,bytes:r(d)}}function u(f,h){return i(f,o(h))}return{encode:i,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:o}}var Ie=_a("bech32");function Ba(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Gt(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function bt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Z(e,t,n=""){let r=Ba(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Wn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ls(e,t){Z(e,void 0,"output");let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Q(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function re(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function us(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var ka=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fs(e,t){return e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function jn(e,t){if(fs(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function ds(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function wt(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}var xt=(e,t)=>{function n(r,...o){if(Z(r,void 0,"key"),!ka)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];Z(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&Z(o[1],void 0,"AAD");let i=t(r,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Z(f,void 0,"output")}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Z(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Z(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(n,e),n};function Je(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&!$e(t))throw new Error("invalid output, must be aligned");return t}function zn(e,t,n){Gt(n);let r=new Uint8Array(16),o=us(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function $e(e){return e.byteOffset%4===0}function de(e){return Uint8Array.from(e)}var te=16;var La=283;function ps(e){if(![16,24,32].includes(e.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+e.length)}function Qn(e){return e<<1^La&-(e>>7)}function Qe(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Qn(e);return n}var Xn=(()=>{let e=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=Qn(r))e[n]=r;let t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return re(e),t})(),Ca=Xn.map((e,t)=>Xn.indexOf(t)),Ia=e=>e<<24|e>>>8,Zn=e=>e<<8|e>>>24;function ms(e,t){if(e.length!==256)throw new Error("Wrong sbox length");let n=new Uint32Array(256).map((l,u)=>t(e[u])),r=n.map(Zn),o=r.map(Zn),s=o.map(Zn),i=new Uint32Array(256*256),a=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let l=0;l<256;l++)for(let u=0;u<256;u++){let f=l*256+u;i[f]=n[l]^r[u],a[f]=o[l]^s[u],c[f]=e[l]<<8|e[u]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:o,T3:s,T01:i,T23:a}}var er=ms(Xn,e=>Qe(e,3)<<24|e<<16|e<<8|Qe(e,2)),gs=ms(Ca,e=>Qe(e,11)<<24|Qe(e,13)<<16|Qe(e,9)<<8|Qe(e,14)),Na=(()=>{let e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Qn(n))e[t]=n;return e})();function tr(e){Z(e);let t=e.length;ps(e);let{sbox2:n}=er,r=[];$e(e)||r.push(e=de(e));let o=Q(e),s=o.length,i=c=>Ee(n,c,c,c,c),a=new Uint32Array(t+28);a.set(o);for(let c=s;c<a.length;c++){let l=a[c-1];c%s===0?l=i(Ia(l))^Na[c/s-1]:s>6&&c%s===4&&(l=i(l)),a[c]=a[c-s]^l}return re(...r),a}function Ma(e){let t=tr(e),n=t.slice(),r=t.length,{sbox2:o}=er,{T0:s,T1:i,T2:a,T3:c}=gs;for(let l=0;l<r;l+=4)for(let u=0;u<4;u++)n[l+u]=t[r-l-4+u];re(t);for(let l=4;l<r-4;l++){let u=n[l],f=Ee(o,u,u,u,u);n[l]=s[f&255]^i[f>>>8&255]^a[f>>>16&255]^c[f>>>24]}return n}function Ne(e,t,n,r,o,s){return e[n<<8&65280|r>>>8&255]^t[o>>>8&65280|s>>>24&255]}function Ee(e,t,n,r,o){return e[t&255|n&65280]|e[r>>>16&255|o>>>16&65280]<<16}function Jn(e,t,n,r,o){let{sbox2:s,T01:i,T23:a}=er,c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];let l=e.length/4-2;for(let m=0;m<l;m++){let g=e[c++]^Ne(i,a,t,n,r,o),p=e[c++]^Ne(i,a,n,r,o,t),y=e[c++]^Ne(i,a,r,o,t,n),E=e[c++]^Ne(i,a,o,t,n,r);t=g,n=p,r=y,o=E}let u=e[c++]^Ee(s,t,n,r,o),f=e[c++]^Ee(s,n,r,o,t),h=e[c++]^Ee(s,r,o,t,n),d=e[c++]^Ee(s,o,t,n,r);return{s0:u,s1:f,s2:h,s3:d}}function Oa(e,t,n,r,o){let{sbox2:s,T01:i,T23:a}=gs,c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];let l=e.length/4-2;for(let m=0;m<l;m++){let g=e[c++]^Ne(i,a,t,o,r,n),p=e[c++]^Ne(i,a,n,t,o,r),y=e[c++]^Ne(i,a,r,n,t,o),E=e[c++]^Ne(i,a,o,r,n,t);t=g,n=p,r=y,o=E}let u=e[c++]^Ee(s,t,o,r,n),f=e[c++]^Ee(s,n,t,o,r),h=e[c++]^Ee(s,r,n,t,o),d=e[c++]^Ee(s,o,r,n,t);return{s0:u,s1:f,s2:h,s3:d}}function Pa(e){if(Z(e),e.length%te!==0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size "+te)}function Ha(e,t,n){Z(e);let r=e.length,o=r%te;if(!t&&o!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");$e(e)||(e=de(e));let s=Q(e);if(t){let a=te-o;a||(a=te),r=r+a}n=Je(r,n),jn(e,n);let i=Q(n);return{b:s,o:i,out:n}}function Da(e,t){if(!t)return e;let n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");let r=e[n-1];if(r<=0||r>16)throw new Error("aes/pcks5: wrong padding");let o=e.subarray(0,-r);for(let s=0;s<r;s++)if(e[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return o}function qa(e){let t=new Uint8Array(16),n=Q(t);t.set(e);let r=te-e.length;for(let o=te-r;o<te;o++)t[o]=r;return n}var nr=xt({blockSize:16,nonceLength:16},function(t,n,r={}){let o=!r.disablePadding;return{encrypt(s,i){let a=tr(t),{b:c,o:l,out:u}=Ha(s,o,i),f=n,h=[a];$e(f)||h.push(f=de(f));let d=Q(f),m=d[0],g=d[1],p=d[2],y=d[3],E=0;for(;E+4<=c.length;)m^=c[E+0],g^=c[E+1],p^=c[E+2],y^=c[E+3],{s0:m,s1:g,s2:p,s3:y}=Jn(a,m,g,p,y),l[E++]=m,l[E++]=g,l[E++]=p,l[E++]=y;if(o){let A=qa(s.subarray(E*4));m^=A[0],g^=A[1],p^=A[2],y^=A[3],{s0:m,s1:g,s2:p,s3:y}=Jn(a,m,g,p,y),l[E++]=m,l[E++]=g,l[E++]=p,l[E++]=y}return re(...h),u},decrypt(s,i){Pa(s);let a=Ma(t),c=n,l=[a];$e(c)||l.push(c=de(c));let u=Q(c);i=Je(s.length,i),$e(s)||l.push(s=de(s)),jn(s,i);let f=Q(s),h=Q(i),d=u[0],m=u[1],g=u[2],p=u[3];for(let y=0;y+4<=f.length;){let E=d,A=m,I=g,q=p;d=f[y+0],m=f[y+1],g=f[y+2],p=f[y+3];let{s0:O,s1:V,s2:H,s3:L}=Oa(a,d,m,g,p);h[y++]=O^E,h[y++]=V^A,h[y++]=H^I,h[y++]=L^q}return re(...l),Da(i,o)}}});function Fa(e){return e instanceof Uint32Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint32Array"}function Yn(e,t){if(Z(t,16,"block"),!Fa(e))throw new Error("_encryptBlock accepts result of expandKeyLE");let n=Q(t),{s0:r,s1:o,s2:s,s3:i}=Jn(e,n[0],n[1],n[2],n[3]);return n[0]=r,n[1]=o,n[2]=s,n[3]=i,t}function hs(e){let t=0;for(let n=te-1;n>=0;n--){let r=(e[n]&128)>>>7;e[n]=e[n]<<1|t,t=r}return t&&(e[te-1]^=135),e}function Kt(e,t){if(e.length!==t.length)throw new Error("xorBlock: blocks must have same length");for(let n=0;n<e.length;n++)e[n]=e[n]^t[n];return e}var Wt=class{buffer;destroyed;k1;k2;xk;constructor(t){Z(t),ps(t),this.xk=tr(t),this.buffer=new Uint8Array(0),this.destroyed=!1;let n=new Uint8Array(te);Yn(this.xk,n),this.k1=hs(n),this.k2=hs(new Uint8Array(this.k1))}update(t){let{destroyed:n,buffer:r}=this;if(n)throw new Error("CMAC instance was destroyed");Z(t);let o=new Uint8Array(r.length+t.length);return o.set(r),o.set(t,r.length),this.buffer=o,this}digest(){if(this.destroyed)throw new Error("CMAC instance was destroyed");let{buffer:t}=this,n=t.length,r=Math.ceil(n/te),o;r===0?(r=1,o=!1):o=n%te===0;let s=(r-1)*te,i=t.subarray(s),a;if(o)a=Kt(new Uint8Array(i),this.k1);else{let l=new Uint8Array(te);l.set(i),l[i.length]=128,a=Kt(l,this.k2)}let c=new Uint8Array(te);for(let l=0;l<r-1;l++){let u=t.subarray(l*te,(l+1)*te);Kt(c,u),Yn(this.xk,c)}return Kt(c,a),Yn(this.xk,c),re(a),c}destroy(){let{buffer:t,destroyed:n,xk:r,k1:o,k2:s}=this;n||(this.destroyed=!0,re(t,r,o,s))}},$a=(e,t)=>new Wt(e).update(t).digest();$a.create=e=>new Wt(e);var bs=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),Va=bs("expand 16-byte k"),Ga=bs("expand 32-byte k"),Ka=Q(Va),Wa=Q(Ga);function k(e,t){return e<<t|e>>>32-t}function rr(e){return e.byteOffset%4===0}var jt=64,ja=16,ws=2**32-1,ys=Uint32Array.of();function za(e,t,n,r,o,s,i,a){let c=o.length,l=new Uint8Array(jt),u=Q(l),f=rr(o)&&rr(s),h=f?Q(o):ys,d=f?Q(s):ys;for(let m=0;m<c;i++){if(e(t,n,r,u,i,a),i>=ws)throw new Error("arx: counter overflow");let g=Math.min(jt,c-m);if(f&&g===jt){let p=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let y=0,E;y<ja;y++)E=p+y,d[E]=h[E]^u[y];m+=jt;continue}for(let p=0,y;p<g;p++)y=m+p,s[y]=o[y]^l[p];m+=g}}function or(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=ds({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return bt(o),bt(i),Gt(s),Gt(n),(a,c,l,u,f=0)=>{Z(a,void 0,"key"),Z(c,void 0,"nonce"),Z(l,void 0,"data");let h=l.length;if(u===void 0&&(u=new Uint8Array(h)),Z(u,void 0,"output"),bt(f),f<0||f>=ws)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let d=[],m=a.length,g,p;if(m===32)d.push(g=de(a)),p=Wa;else if(m===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),p=Ka,d.push(g);else throw Z(a,32,"arx key"),new Error("invalid key size");rr(c)||d.push(c=de(c));let y=Q(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(p,y,Q(c.subarray(0,16)),y),c=c.subarray(16)}let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,d.push(c)}let A=Q(c);return za(e,p,y,A,l,u,f,i),re(...d),u}}function oe(e,t){return e[t++]&255|(e[t++]&255)<<8}var sr=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(t){t=de(Z(t,32,"key"));let n=oe(t,0),r=oe(t,2),o=oe(t,4),s=oe(t,6),i=oe(t,8),a=oe(t,10),c=oe(t,12),l=oe(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=oe(t,16+2*u)}process(t,n,r=!1){let o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=i[5],d=i[6],m=i[7],g=i[8],p=i[9],y=oe(t,n+0),E=oe(t,n+2),A=oe(t,n+4),I=oe(t,n+6),q=oe(t,n+8),O=oe(t,n+10),V=oe(t,n+12),H=oe(t,n+14),L=s[0]+(y&8191),G=s[1]+((y>>>13|E<<3)&8191),D=s[2]+((E>>>10|A<<6)&8191),C=s[3]+((A>>>7|I<<9)&8191),x=s[4]+((I>>>4|q<<12)&8191),w=s[5]+(q>>>1&8191),b=s[6]+((q>>>14|O<<2)&8191),S=s[7]+((O>>>11|V<<5)&8191),R=s[8]+((V>>>8|H<<8)&8191),_=s[9]+(H>>>5|o),v=0,T=v+L*a+G*(5*p)+D*(5*g)+C*(5*m)+x*(5*d);v=T>>>13,T&=8191,T+=w*(5*h)+b*(5*f)+S*(5*u)+R*(5*l)+_*(5*c),v+=T>>>13,T&=8191;let B=v+L*c+G*a+D*(5*p)+C*(5*g)+x*(5*m);v=B>>>13,B&=8191,B+=w*(5*d)+b*(5*h)+S*(5*f)+R*(5*u)+_*(5*l),v+=B>>>13,B&=8191;let U=v+L*l+G*c+D*a+C*(5*p)+x*(5*g);v=U>>>13,U&=8191,U+=w*(5*m)+b*(5*d)+S*(5*h)+R*(5*f)+_*(5*u),v+=U>>>13,U&=8191;let K=v+L*u+G*l+D*c+C*a+x*(5*p);v=K>>>13,K&=8191,K+=w*(5*g)+b*(5*m)+S*(5*d)+R*(5*h)+_*(5*f),v+=K>>>13,K&=8191;let F=v+L*f+G*u+D*l+C*c+x*a;v=F>>>13,F&=8191,F+=w*(5*p)+b*(5*g)+S*(5*m)+R*(5*d)+_*(5*h),v+=F>>>13,F&=8191;let N=v+L*h+G*f+D*u+C*l+x*c;v=N>>>13,N&=8191,N+=w*a+b*(5*p)+S*(5*g)+R*(5*m)+_*(5*d),v+=N>>>13,N&=8191;let W=v+L*d+G*h+D*f+C*u+x*l;v=W>>>13,W&=8191,W+=w*c+b*a+S*(5*p)+R*(5*g)+_*(5*m),v+=W>>>13,W&=8191;let Y=v+L*m+G*d+D*h+C*f+x*u;v=Y>>>13,Y&=8191,Y+=w*l+b*c+S*a+R*(5*p)+_*(5*g),v+=Y>>>13,Y&=8191;let ne=v+L*g+G*m+D*d+C*h+x*f;v=ne>>>13,ne&=8191,ne+=w*u+b*l+S*c+R*a+_*(5*p),v+=ne>>>13,ne&=8191;let j=v+L*p+G*g+D*m+C*d+x*h;v=j>>>13,j&=8191,j+=w*f+b*u+S*l+R*c+_*a,v+=j>>>13,j&=8191,v=(v<<2)+v|0,v=v+T|0,T=v&8191,v=v>>>13,B+=v,s[0]=T,s[1]=B,s[2]=U,s[3]=K,s[4]=F,s[5]=N,s[6]=W,s[7]=Y,s[8]=ne,s[9]=j}finalize(){let{h:t,pad:n}=this,r=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+n[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+n[a]|0)+(i>>>16)|0,t[a]=i&65535;re(r)}update(t){Wn(this),Z(t),t=de(t);let{buffer:n,blockLen:r}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(t,s);continue}n.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){re(this.h,this.r,this.buffer,this.pad)}digestInto(t){Wn(this),ls(t,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=r[i]>>>0,t[s++]=r[i]>>>8;return t}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}};function Za(e){let t=(r,o)=>e(o).update(r).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}var xs=Za(e=>new sr(e));function Ss(e,t,n,r,o,s=20){let i=e[0],a=e[1],c=e[2],l=e[3],u=t[0],f=t[1],h=t[2],d=t[3],m=t[4],g=t[5],p=t[6],y=t[7],E=o,A=n[0],I=n[1],q=n[2],O=i,V=a,H=c,L=l,G=u,D=f,C=h,x=d,w=m,b=g,S=p,R=y,_=E,v=A,T=I,B=q;for(let K=0;K<s;K+=2)O=O+G|0,_=k(_^O,16),w=w+_|0,G=k(G^w,12),O=O+G|0,_=k(_^O,8),w=w+_|0,G=k(G^w,7),V=V+D|0,v=k(v^V,16),b=b+v|0,D=k(D^b,12),V=V+D|0,v=k(v^V,8),b=b+v|0,D=k(D^b,7),H=H+C|0,T=k(T^H,16),S=S+T|0,C=k(C^S,12),H=H+C|0,T=k(T^H,8),S=S+T|0,C=k(C^S,7),L=L+x|0,B=k(B^L,16),R=R+B|0,x=k(x^R,12),L=L+x|0,B=k(B^L,8),R=R+B|0,x=k(x^R,7),O=O+D|0,B=k(B^O,16),S=S+B|0,D=k(D^S,12),O=O+D|0,B=k(B^O,8),S=S+B|0,D=k(D^S,7),V=V+C|0,_=k(_^V,16),R=R+_|0,C=k(C^R,12),V=V+C|0,_=k(_^V,8),R=R+_|0,C=k(C^R,7),H=H+x|0,v=k(v^H,16),w=w+v|0,x=k(x^w,12),H=H+x|0,v=k(v^H,8),w=w+v|0,x=k(x^w,7),L=L+G|0,T=k(T^L,16),b=b+T|0,G=k(G^b,12),L=L+G|0,T=k(T^L,8),b=b+T|0,G=k(G^b,7);let U=0;r[U++]=i+O|0,r[U++]=a+V|0,r[U++]=c+H|0,r[U++]=l+L|0,r[U++]=u+G|0,r[U++]=f+D|0,r[U++]=h+C|0,r[U++]=d+x|0,r[U++]=m+w|0,r[U++]=g+b|0,r[U++]=p+S|0,r[U++]=y+R|0,r[U++]=E+_|0,r[U++]=A+v|0,r[U++]=I+T|0,r[U++]=q+B|0}function Ya(e,t,n,r){let o=e[0],s=e[1],i=e[2],a=e[3],c=t[0],l=t[1],u=t[2],f=t[3],h=t[4],d=t[5],m=t[6],g=t[7],p=n[0],y=n[1],E=n[2],A=n[3];for(let q=0;q<20;q+=2)o=o+c|0,p=k(p^o,16),h=h+p|0,c=k(c^h,12),o=o+c|0,p=k(p^o,8),h=h+p|0,c=k(c^h,7),s=s+l|0,y=k(y^s,16),d=d+y|0,l=k(l^d,12),s=s+l|0,y=k(y^s,8),d=d+y|0,l=k(l^d,7),i=i+u|0,E=k(E^i,16),m=m+E|0,u=k(u^m,12),i=i+u|0,E=k(E^i,8),m=m+E|0,u=k(u^m,7),a=a+f|0,A=k(A^a,16),g=g+A|0,f=k(f^g,12),a=a+f|0,A=k(A^a,8),g=g+A|0,f=k(f^g,7),o=o+l|0,A=k(A^o,16),m=m+A|0,l=k(l^m,12),o=o+l|0,A=k(A^o,8),m=m+A|0,l=k(l^m,7),s=s+u|0,p=k(p^s,16),g=g+p|0,u=k(u^g,12),s=s+u|0,p=k(p^s,8),g=g+p|0,u=k(u^g,7),i=i+f|0,y=k(y^i,16),h=h+y|0,f=k(f^h,12),i=i+f|0,y=k(y^i,8),h=h+y|0,f=k(f^h,7),a=a+c|0,E=k(E^a,16),d=d+E|0,c=k(c^d,12),a=a+c|0,E=k(E^a,8),d=d+E|0,c=k(c^d,7);let I=0;r[I++]=o,r[I++]=s,r[I++]=i,r[I++]=a,r[I++]=p,r[I++]=y,r[I++]=E,r[I++]=A}var zt=or(Ss,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Xa=or(Ss,{counterRight:!1,counterLength:8,extendNonceFn:Ya,allowShortKeys:!1});var Ja=new Uint8Array(16),vs=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Ja.subarray(n))},Qa=new Uint8Array(32);function Es(e,t,n,r,o){o!==void 0&&Z(o,void 0,"AAD");let s=e(t,n,Qa),i=zn(r.length,o?o.length:0,!0),a=xs.create(s);o&&vs(a,o),vs(a,r),a.update(i);let c=a.digest();return re(s,i),c}var As=e=>(t,n,r)=>({encrypt(s,i){let a=s.length;i=Je(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,n,c,c,1);let l=Es(e,t,n,c,r);return i.set(l,a),re(l),i},decrypt(s,i){i=Je(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Es(e,t,n,a,r);if(!wt(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,n,i,i,1),re(l),i}}),cp=xt({blockSize:64,nonceLength:12,tagLength:16},As(zt)),lp=xt({blockSize:64,nonceLength:24,tagLength:16},As(Xa));function Rs(e,t,n){return Oe(e),n===void 0&&(n=new Uint8Array(e.outputLen)),ve(e,n,t)}var ir=Uint8Array.of(0),Ts=Uint8Array.of();function _s(e,t,n,r=32){Oe(e),fe(r,"length");let o=e.outputLen;if(r>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(r/o);n===void 0?n=Ts:M(n,void 0,"info");let i=new Uint8Array(s*o),a=ve.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)ir[0]=u+1,c.update(u===0?Ts:l).update(n).update(ir).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),ce(l,ir),i.slice(0,r)}var ec=Object.defineProperty,z=(e,t)=>{for(var n in t)ec(e,n,{get:t[n],enumerable:!0})},tc={};z(tc,{binarySearch:()=>dr,bytesToHex:()=>P,hexToBytes:()=>$,insertEventIntoAscendingList:()=>oc,insertEventIntoDescendingList:()=>rc,isHex32:()=>le,mergeReverseSortedLists:()=>sc,normalizeURL:()=>nc,utf8Decoder:()=>Be,utf8Encoder:()=>he});var Be=new TextDecoder("utf-8"),he=new TextEncoder;function nc(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.protocol==="http:"?t.protocol="ws:":t.protocol==="https:"&&(t.protocol="wss:"),t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}function rc(e,t){let[n,r]=dr(e,o=>t.id===o.id?0:t.created_at===o.created_at?-1:o.created_at-t.created_at);return r||e.splice(n,0,t),e}function oc(e,t){let[n,r]=dr(e,o=>t.id===o.id?0:t.created_at===o.created_at?-1:t.created_at-o.created_at);return r||e.splice(n,0,t),e}function dr(e,t){let n=0,r=e.length-1;for(;n<=r;){let o=Math.floor((n+r)/2),s=t(e[o]);if(s===0)return[o,!0];s<0?r=o-1:n=o+1}return[n,!1]}function sc(e,t){let n=new Array(e.length+t.length);n.length=0;let r=0,o=0,s=[];for(;r<e.length&&o<t.length;){let i;if(e[r]?.created_at>t[o]?.created_at?(i=e[r],r++):(i=t[o],o++),n.length>0&&n[n.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;n.push(i),s.push(i.id)}for(;r<e.length;){let i=e[r];if(r++,n.length>0&&n[n.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;n.push(i),s.push(i.id)}for(;o<t.length;){let i=t[o];if(o++,n.length>0&&n[n.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;n.push(i),s.push(i.id)}return n}function le(e){for(let t=0;t<64;t++){let n=e.charCodeAt(t);if(isNaN(n)||n<48||n>102||n>57&&n<97)return!1}return!0}var et=Symbol("verified"),ic=e=>e instanceof Object;function hr(e){if(!ic(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!le(e.pubkey)||!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var ac=class{generateSecretKey(){return Xe.utils.randomSecretKey()}getPublicKey(e){return P(Xe.getPublicKey(e))}finalizeEvent(e,t){let n=e;return n.pubkey=P(Xe.getPublicKey(t)),n.id=Yt(n),n.sig=P(Xe.sign($(Yt(n)),t)),n[et]=!0,n}verifyEvent(e){if(typeof e[et]=="boolean")return e[et];try{let t=Yt(e);if(t!==e.id)return e[et]=!1,!1;let n=Xe.verify($(e.sig),$(t),$(e.pubkey));return e[et]=n,n}catch{return e[et]=!1,!1}}};function cc(e){if(!hr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function Yt(e){let t=ee(he.encode(cc(e)));return P(t)}var Qt=new ac,pr=Qt.generateSecretKey,mr=Qt.getPublicKey,pe=Qt.finalizeEvent,gr=Qt.verifyEvent,lc={};z(lc,{AIEmbeddings:()=>rl,AppCurationSet:()=>Hu,Application:()=>Ou,AuthoredPodcasts:()=>ru,BadgeAward:()=>yc,BadgeDefinition:()=>Au,Bid:()=>Cc,BidConfirmation:()=>Ic,BlobsAuth:()=>mu,BlockedRelaysList:()=>Dl,BlossomServerList:()=>Jl,BookmarkList:()=>Ol,Bookmarksets:()=>wu,Calendar:()=>tf,CalendarEventRSVP:()=>nf,CashuMintAnnouncement:()=>pf,CashuWalletEvent:()=>fu,CashuWalletHistory:()=>ml,CashuWalletTokens:()=>pl,ChannelCreation:()=>Hs,ChannelHideMessage:()=>Fs,ChannelMessage:()=>qs,ChannelMetadata:()=>Ds,ChannelMuteUser:()=>$s,ChatMessage:()=>bc,Chess:()=>kc,ClassifiedListing:()=>Gu,ClientAuth:()=>Gs,CodeSnippet:()=>$c,CoinjoinPool:()=>il,Comment:()=>Pc,CommunitiesList:()=>Pl,CommunityDefinition:()=>uf,CommunityPostApproval:()=>ll,ConferenceEvent:()=>Fu,Contacts:()=>pc,CreateOrUpdateProduct:()=>_u,CreateOrUpdateStall:()=>Ru,CuratedVideoSets:()=>vu,Curationsets:()=>xu,Date:()=>Qu,DecoupledEncryptionKeyDistribution:()=>cl,DecoupledKeyAnnouncement:()=>Zl,DecoupledKeyClientAnnouncement:()=>al,DirectMessageRelaysList:()=>Yl,DraftClassifiedListing:()=>Ku,DraftEvent:()=>Yu,DraftLong:()=>Lu,Emojisets:()=>Cu,EncryptedDirectMessage:()=>mc,EventDeletion:()=>gc,FavoriteFollowSets:()=>jl,FavoritePodcasts:()=>Xl,FavoriteRelays:()=>$l,FedimintAnnouncement:()=>mf,Feed:()=>Ju,FileMessage:()=>Ec,FileMetadata:()=>Mc,FileServerPreference:()=>Ql,Followsets:()=>gu,ForumThread:()=>xc,GenericRepost:()=>vr,Genericlists:()=>yu,GeocacheListing:()=>df,GeocacheLog:()=>gl,GeocacheLogEntry:()=>hf,GeocacheProofOfFind:()=>yl,GiftWrap:()=>Vs,GitPullRequest:()=>Gc,GitPullRequestUpdate:()=>Kc,GoodWikiAuthorList:()=>eu,GoodWikiRelayList:()=>tu,GroupMetadata:()=>yf,HTTPAuth:()=>Er,Handlerinformation:()=>sf,Handlerrecommendation:()=>of,Highlights:()=>Cl,InteractiveRoom:()=>qu,InterestsList:()=>Gl,Interestsets:()=>Tu,Issue:()=>Wc,JobFeedback:()=>dl,JobRequest:()=>ul,JobResult:()=>fl,Label:()=>tl,LegacyNsiteFile:()=>cf,LightningPubRPC:()=>du,LinkSet:()=>Xu,LiveChatMessage:()=>Fc,LiveEvent:()=>Du,LongFormArticle:()=>Uu,MarketplaceUI:()=>Bu,MediaFollows:()=>Wl,MediaStarterPacks:()=>Sf,MergeRequests:()=>Uc,Metadata:()=>dc,ModularArticleContent:()=>Nu,ModularArticleHeader:()=>Iu,MuteSets:()=>Eu,Mutelist:()=>Il,NWCWalletInfo:()=>lu,NWCWalletRequest:()=>Ks,NWCWalletResponse:()=>hu,NormalVideo:()=>Tc,NostrConnect:()=>pu,NsiteNamed:()=>ff,NsiteRoot:()=>uu,NutZap:()=>Bl,NutZapInfo:()=>Kl,OpenTimestamps:()=>Nc,Patch:()=>Vc,PeerToPeerOrderEvents:()=>gf,Photo:()=>Ac,Pinlist:()=>Nl,PodcastEpisode:()=>Bc,PodcastMetadata:()=>nu,Poll:()=>Oc,PollResponse:()=>Lc,PrivateDirectMessage:()=>Ps,PrivateEventRelayList:()=>Vl,ProblemTracker:()=>Jc,ProductSoldAsAuction:()=>ku,ProfileBadges:()=>Su,ProxyAnnouncement:()=>au,PublicChatsList:()=>Hl,PublicMessage:()=>_c,Reaction:()=>xr,ReactionToWebsite:()=>Sc,RecommendRelay:()=>hc,Redirects:()=>Zu,RelayDiscovery:()=>Pu,RelayList:()=>Ml,RelayMonitorAnnouncement:()=>ou,RelayReview:()=>rf,RelayReviews:()=>nl,Relaysets:()=>bu,ReleaseArtifactSets:()=>Mu,Reply:()=>jc,Report:()=>Qc,Reporting:()=>el,RepositoryAnnouncement:()=>Wu,RepositoryState:()=>ju,Repost:()=>wr,ReservedCashuWalletTokens:()=>hl,RoomPresence:()=>su,Scroll:()=>Dc,Seal:()=>Os,SearchRelaysList:()=>ql,ShortTextNote:()=>Ms,ShortVideo:()=>Rc,SimpleGroupAdmins:()=>bf,SimpleGroupCreateGroup:()=>El,SimpleGroupCreateInvite:()=>Al,SimpleGroupDeleteEvent:()=>vl,SimpleGroupDeleteGroup:()=>Sl,SimpleGroupEditMetadata:()=>xl,SimpleGroupJoinRequest:()=>Tl,SimpleGroupLeaveRequest:()=>Rl,SimpleGroupList:()=>Fl,SimpleGroupLiveKitParticipants:()=>vf,SimpleGroupMembers:()=>wf,SimpleGroupPutUser:()=>bl,SimpleGroupRemoveUser:()=>wl,SimpleGroupReply:()=>vc,SimpleGroupRoles:()=>xf,SimpleGroupThreadedReply:()=>wc,SlideSet:()=>Vu,SoftwareApplication:()=>af,StarterPacks:()=>Ef,StatusApplied:()=>Zc,StatusClosed:()=>Yc,StatusDraft:()=>Xc,StatusOpen:()=>zc,TidalLogin:()=>kl,Time:()=>ef,Torrent:()=>ol,TorrentComment:()=>sl,TransportMethodAnnouncement:()=>cu,UserEmojiList:()=>zl,UserGraspList:()=>iu,UserStatuses:()=>$u,VideoViewEvent:()=>lf,Voice:()=>Hc,VoiceComment:()=>qc,WebBookmarks:()=>Af,WikiArticle:()=>zu,Zap:()=>Ll,ZapGoal:()=>_l,ZapRequest:()=>Ul,classifyKind:()=>uc,isAddressableKind:()=>br,isEphemeralKind:()=>Ns,isKind:()=>fc,isRegularKind:()=>Is,isReplaceableKind:()=>yr});function Is(e){return e<1e4&&e!==0&&e!==3}function yr(e){return e===0||e===3||1e4<=e&&e<2e4}function Ns(e){return 2e4<=e&&e<3e4}function br(e){return 3e4<=e&&e<4e4}function uc(e){return Is(e)?"regular":yr(e)?"replaceable":Ns(e)?"ephemeral":br(e)?"parameterized":"unknown"}function fc(e,t){let n=t instanceof Array?t:[t];return hr(e)&&n.includes(e.kind)||!1}var dc=0,Ms=1,hc=2,pc=3,mc=4,gc=5,wr=6,xr=7,yc=8,bc=9,wc=10,xc=11,vc=12,Os=13,Ps=14,Ec=15,vr=16,Sc=17,Ac=20,Tc=21,Rc=22,_c=24,Hs=40,Ds=41,qs=42,Fs=43,$s=44,Bc=54,kc=64,Uc=818,Lc=1018,Cc=1021,Ic=1022,Nc=1040,Vs=1059,Mc=1063,Oc=1068,Pc=1111,Hc=1222,Dc=1227,qc=1244,Fc=1311,$c=1337,Vc=1617,Gc=1618,Kc=1619,Wc=1621,jc=1622,zc=1630,Zc=1631,Yc=1632,Xc=1633,Jc=1971,Qc=1984,el=1984,tl=1985,nl=1986,rl=1987,ol=2003,sl=2004,il=2022,al=4454,cl=4455,ll=4550,ul=5999,fl=6999,dl=7e3,hl=7374,pl=7375,ml=7376,gl=7516,yl=7517,bl=9e3,wl=9001,xl=9002,vl=9005,El=9007,Sl=9008,Al=9009,Tl=9021,Rl=9022,_l=9041,Bl=9321,kl=9467,Ul=9734,Ll=9735,Cl=9802,Il=1e4,Nl=10001,Ml=10002,Ol=10003,Pl=10004,Hl=10005,Dl=10006,ql=10007,Fl=10009,$l=10012,Vl=10013,Gl=10015,Kl=10019,Wl=10020,jl=10021,zl=10030,Zl=10044,Yl=10050,Xl=10054,Jl=10063,Ql=10096,eu=10101,tu=10102,nu=10154,ru=10164,ou=10166,su=10312,iu=10317,au=10377,cu=11111,lu=13194,uu=15128,fu=17375,du=21e3,Gs=22242,Ks=23194,hu=23195,pu=24133,mu=24242,Er=27235,gu=3e4,yu=30001,bu=30002,wu=30003,xu=30004,vu=30005,Eu=30007,Su=30008,Au=30009,Tu=30015,Ru=30017,_u=30018,Bu=30019,ku=30020,Uu=30023,Lu=30024,Cu=30030,Iu=30040,Nu=30041,Mu=30063,Ou=30078,Pu=30166,Hu=30267,Du=30311,qu=30312,Fu=30313,$u=30315,Vu=30388,Gu=30402,Ku=30403,Wu=30617,ju=30618,zu=30818,Zu=30819,Yu=31234,Xu=31388,Ju=31890,Qu=31922,ef=31923,tf=31924,nf=31925,rf=31987,of=31989,sf=31990,af=32267,cf=34128,lf=34237,uf=34550,ff=35128,df=37515,hf=37516,pf=38172,mf=38173,gf=38383,yf=39e3,bf=39001,wf=39002,xf=39003,vf=39004,Ef=39089,Sf=39092,Af=39701;var Tf={};z(Tf,{getHex64:()=>Sr,getInt:()=>Ws,getSubscriptionId:()=>Rf,matchEventId:()=>_f,matchEventKind:()=>kf,matchEventPubkey:()=>Bf});function Sr(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,o=e.slice(r).indexOf('"')+r+1;return e.slice(o,o+64)}function Ws(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,o=e.slice(r),s=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,s),10)}function Rf(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,o=e.slice(r+1,80).indexOf('"');if(o===-1)return null;let s=r+1+o;return e.slice(r+1,s)}function _f(e,t){return t===Sr(e,"id")}function Bf(e,t){return t===Sr(e,"pubkey")}function kf(e,t){return t===Ws(e,"kind")}var Uf={};z(Uf,{makeAuthEvent:()=>Lf});function Lf(e,t){return{kind:Gs,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var Cf;try{Cf=WebSocket}catch{}var If=256,bp=If*2,wp=new TextEncoder;var Nf;try{Nf=WebSocket}catch{}var Mf={};z(Mf,{BECH32_REGEX:()=>js,Bech32MaxSize:()=>Ar,NostrTypeGuard:()=>Of,decode:()=>en,decodeNostrURI:()=>Hf,encodeBytes:()=>nn,naddrEncode:()=>Gf,neventEncode:()=>Vf,noteEncode:()=>Ff,nprofileEncode:()=>$f,npubEncode:()=>qf,nsecEncode:()=>Df});var Of={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},Ar=5e3,js=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function Pf(e){let t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function Hf(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),en(e)}catch{return{type:"invalid",data:null}}}function en(e){let{prefix:t,words:n}=Ie.decode(e,Ar),r=new Uint8Array(Ie.fromWords(n));switch(t){case"nprofile":{let o=ar(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:P(o[0][0]),relays:o[1]?o[1].map(s=>Be.decode(s)):[]}}}case"nevent":{let o=ar(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:P(o[0][0]),relays:o[1]?o[1].map(s=>Be.decode(s)):[],author:o[2]?.[0]?P(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(P(o[3][0]),16):void 0}}}case"naddr":{let o=ar(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Be.decode(o[0][0]),pubkey:P(o[2][0]),kind:parseInt(P(o[3][0]),16),relays:o[1]?o[1].map(s=>Be.decode(s)):[]}}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:P(r)};default:throw new Error(`unknown prefix ${t}`)}}function ar(e){let t={},n=e;for(;n.length>0;){if(n.length<2)throw new Error("not enough data to read TLV");let r=n[0],o=n[1],s=n.slice(2,2+o);if(n=n.slice(2+o),s.length<o)throw new Error(`not enough data to read on TLV ${r}`);t[r]=t[r]||[],t[r].push(s)}return t}function Df(e){return nn("nsec",e)}function qf(e){return nn("npub",$(e))}function Ff(e){return nn("note",$(e))}function tn(e,t){let n=Ie.toWords(t);return Ie.encode(e,n,Ar)}function nn(e,t){return tn(e,t)}function $f(e){let t=Tr({0:[$(e.pubkey)],1:(e.relays||[]).map(n=>he.encode(n))});return tn("nprofile",t)}function Vf(e){let t;e.kind!==void 0&&(t=Pf(e.kind));let n=Tr({0:[$(e.id)],1:(e.relays||[]).map(r=>he.encode(r)),2:e.author?[$(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return tn("nevent",n)}function Gf(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=Tr({0:[he.encode(e.identifier)],1:(e.relays||[]).map(r=>he.encode(r)),2:[$(e.pubkey)],3:[new Uint8Array(t)]});return tn("naddr",n)}function Tr(e){let t=[];return Object.entries(e).reverse().forEach(([n,r])=>{r.forEach(o=>{let s=new Uint8Array(o.length+2);s.set([parseInt(n)],0),s.set([o.length],1),s.set(o,2),t.push(s)})}),X(...t)}var Kf={};z(Kf,{decrypt:()=>Wf,encrypt:()=>zs});function zs(e,t,n){let r=e instanceof Uint8Array?e:$(e),o=gt.getSharedSecret(r,$("02"+t)),s=Zs(o),i=Uint8Array.from(ge(16)),a=he.encode(n),c=nr(s,i).encrypt(a),l=be.encode(new Uint8Array(c)),u=be.encode(new Uint8Array(i.buffer));return`${l}?iv=${u}`}function Wf(e,t,n){let r=e instanceof Uint8Array?e:$(e),[o,s]=n.split("?iv="),i=gt.getSharedSecret(r,$("02"+t)),a=Zs(i),c=be.decode(s),l=be.decode(o),u=nr(a,c).decrypt(l);return Be.decode(u)}function Zs(e){return e.slice(1,33)}var jf={};z(jf,{NIP05_REGEX:()=>Rr,isNip05:()=>zf,isValid:()=>Xf,queryProfile:()=>Ys,searchDomain:()=>Yf,useFetchImplementation:()=>Zf});var Rr=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,zf=e=>Rr.test(e||""),rn;try{rn=fetch}catch{}function Zf(e){rn=e}async function Yf(e,t=""){try{let n=`https://${e}/.well-known/nostr.json?name=${t}`,r=await rn(n,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function Ys(e){let t=e.match(Rr);if(!t)return null;let[,n="_",r]=t;try{let o=`https://${r}/.well-known/nostr.json?name=${n}`,s=await rn(o,{redirect:"manual"});if(s.status!==200)throw Error("Wrong response code");let i=await s.json(),a=i.names[n];return a?{pubkey:a,relays:i.relays?.[a]}:null}catch{return null}}async function Xf(e,t){let n=await Ys(t);return n?n.pubkey===e:!1}var Jf={};z(Jf,{parse:()=>Qf});function Qf(e){let t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]},n,r;for(let o=e.tags.length-1;o>=0;o--){let s=e.tags[o];if(s[0]==="e"&&s[1]&&le(s[1])){let[i,a,c,l,u]=s,f={id:a,relays:c?[c]:[],author:u&&le(u)?u:void 0};if(l==="root"){t.root=f;continue}if(l==="reply"){t.reply=f;continue}if(l==="mention"){t.mentions.push(f);continue}n?r=f:n=f,t.mentions.push(f);continue}if(s[0]==="q"&&s[1]&&le(s[1])){let[i,a,c]=s;t.quotes.push({id:a,relays:c?[c]:[]})}if(s[0]==="p"&&s[1]&&le(s[1])){t.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return t.root||(t.root=r||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach(o=>{if(!o)return;let s=t.mentions.indexOf(o);if(s!==-1&&t.mentions.splice(s,1),o.author){let i=t.profiles.find(a=>a.pubkey===o.author);i&&i.relays&&(o.relays||(o.relays=[]),i.relays.forEach(a=>{o.relays?.indexOf(a)===-1&&o.relays.push(a)}),i.relays=o.relays)}}),t.mentions.forEach(o=>{if(o.author){let s=t.profiles.find(i=>i.pubkey===o.author);s&&s.relays&&(o.relays||(o.relays=[]),s.relays.forEach(i=>{o.relays.indexOf(i)===-1&&o.relays.push(i)}),s.relays=o.relays)}}),t}var ed={};z(ed,{fetchRelayInformation:()=>nd,useFetchImplementation:()=>td});var Xs;try{Xs=fetch}catch{}function td(e){Xs=e}async function nd(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var rd={};z(rd,{getPow:()=>od,minePow:()=>id});function od(e){let t=0;for(let n=0;n<64;n+=8){let r=parseInt(e.substring(n,n+8),16);if(r===0)t+=32;else{t+=Math.clz32(r);break}}return t}function sd(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===0)t+=8;else{t+=Math.clz32(r)-24;break}}return t}function id(e,t){let n=0,r=e,o=["nonce",n.toString(),t.toString()];for(r.tags.push(o);;){let s=Math.floor(new Date().getTime()/1e3);s!==r.created_at&&(n=0,r.created_at=s),o[1]=(++n).toString();let i=ee(he.encode(JSON.stringify([0,r.pubkey,r.created_at,r.kind,r.tags,r.content])));if(sd(i)>=t){r.id=P(i);break}}return r}var ad={};z(ad,{unwrapEvent:()=>bd,unwrapManyEvents:()=>wd,wrapEvent:()=>ui,wrapManyEvents:()=>yd});var cd={};z(cd,{createRumor:()=>ii,createSeal:()=>ai,createWrap:()=>ci,unwrapEvent:()=>Nr,unwrapManyEvents:()=>li,wrapEvent:()=>Jt,wrapManyEvents:()=>md});var ld={};z(ld,{decrypt:()=>Ir,encrypt:()=>Cr,getConversationKey:()=>Ur,v2:()=>hd});var _r=1,Br=4294967295,kr=65536;function Ur(e,t){let n=gt.getSharedSecret(e,$("02"+t)).subarray(1,33);return Rs(ee,n,he.encode("nip44-v2"))}function Js(e,t){let n=_s(ee,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Lr(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;let t=2**(Math.floor(Math.log2(e-1))+1),n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function ud(e){if(!Number.isSafeInteger(e)||e<_r||e>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function fd(e){if(!Number.isSafeInteger(e)||e<kr||e>Br)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function Qs(e){let t=he.encode(e),n=t.length;if(n<_r||n>Br)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=kr?X(new Uint8Array([0,0]),fd(n)):ud(n),o=new Uint8Array(Lr(n)-n);return X(r,t,o)}function ei(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(0),r,o;if(n===0){if(r=t.getUint32(2),r<kr)throw new Error("invalid padding");o=6}else r=n,o=2;let s=e.subarray(o,o+r);if(r<_r||r>Br||s.length!==r||e.length!==o+Lr(r))throw new Error("invalid padding");return Be.decode(s)}function ti(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=X(n,t);return ve(ee,e,r)}function dd(e){if(typeof e!="string")throw new Error("payload must be a valid string");let t=e.length;if(t<132)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let n;try{n=be.decode(e)}catch(s){throw new Error("invalid base64: "+s.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Cr(e,t,n=ge(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:s}=Js(t,n),i=Qs(e),a=zt(r,o,i),c=ti(s,a,n);return be.encode(X(new Uint8Array([2]),n,a,c))}function Ir(e,t){let{nonce:n,ciphertext:r,mac:o}=dd(e),{chacha_key:s,chacha_nonce:i,hmac_key:a}=Js(t,n),c=ti(a,r,n);if(!wt(c,o))throw new Error("invalid MAC");let l=zt(s,i,r);return ei(l)}var hd={utils:{getConversationKey:Ur,calcPaddedLen:Lr,pad:Qs,unpad:ei},encrypt:Cr,decrypt:Ir},pd=2880*60,ni=()=>Math.round(Date.now()/1e3),ri=()=>Math.round(ni()-Math.random()*pd),oi=(e,t)=>Ur(e,t),si=(e,t,n)=>Cr(JSON.stringify(e),oi(t,n)),Bs=(e,t)=>JSON.parse(Ir(e.content,oi(t,e.pubkey)));function ii(e,t){let n={created_at:ni(),content:"",tags:[],...e,pubkey:mr(t)};return n.id=Yt(n),n}function ai(e,t,n){return pe({kind:Os,content:si(e,t,n),created_at:ri(),tags:[]},t)}function ci(e,t){let n=pr();return pe({kind:Vs,content:si(e,n,t),created_at:ri(),tags:[["p",t]]},n)}function Jt(e,t,n){let r=ii(e,t),o=ai(r,t,n);return ci(o,n)}function md(e,t,n){if(!n||n.length===0)throw new Error("At least one recipient is required.");let r=mr(t),o=[Jt(e,t,r)];return n.forEach(s=>{o.push(Jt(e,t,s))}),o}function Nr(e,t){let n=Bs(e,t);return Bs(n,t)}function li(e,t){let n=[];return e.forEach(r=>{n.push(Nr(r,t))}),n.sort((r,o)=>r.created_at-o.created_at),n}function gd(e,t,n,r){let o={created_at:Math.ceil(Date.now()/1e3),kind:Ps,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach(({publicKey:i,relayUrl:a})=>{o.tags.push(a?["p",i,a]:["p",i])}),r&&o.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&o.tags.push(["subject",n]),o}function ui(e,t,n,r,o){let s=gd(t,n,r,o);return Jt(s,e,t.publicKey)}function yd(e,t,n,r,o){if(!t||t.length===0)throw new Error("At least one recipient is required.");return[{publicKey:mr(e)},...t].map(i=>ui(e,i,n,r,o))}var bd=Nr,wd=li,xd={};z(xd,{finishRepostEvent:()=>vd,getRepostedEvent:()=>Ed,getRepostedEventPointer:()=>fi});function vd(e,t,n,r){let o,s=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===Ms?o=wr:(o=vr,s.push(["k",String(t.kind)])),pe({kind:o,tags:s,content:e.content===""||t.tags?.find(i=>i[0]==="-")?"":JSON.stringify(t),created_at:e.created_at},r)}function fi(e){if(![wr,vr].includes(e.kind))return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){let o=e.tags[r];o.length>=2&&(o[0]==="e"&&t===void 0?t=o:o[0]==="p"&&n===void 0&&(n=o))}if(t!==void 0)return{id:t[1],relays:[t[2],n?.[2]].filter(r=>typeof r=="string"),author:n?.[1]}}function Ed(e,{skipVerification:t}={}){let n=fi(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!gr(r)))return r}var Sd={};z(Sd,{NOSTR_URI_REGEX:()=>Mr,parse:()=>Td,test:()=>Ad});var Mr=new RegExp(`nostr:(${js.source})`);function Ad(e){return typeof e=="string"&&new RegExp(`^${Mr.source}$`).test(e)}function Td(e){let t=e.match(new RegExp(`^${Mr.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:en(t[1])}}var Rd={};z(Rd,{parse:()=>Bd});function ks(e){if(e)return/^\d+$/.test(e)?parseInt(e,10):e}function di(e,t){let n=e.indexOf(":"),r=e.indexOf(":",n+1);if(n===-1||r===-1)return;let o=parseInt(e.slice(0,n),10);if(Number.isNaN(o))return;let s=e.slice(n+1,r);if(le(s))return{kind:o,pubkey:s,identifier:e.slice(r+1),relays:t?[t]:[]}}function Us(e){switch(e[0]){case"E":case"e":return!e[1]||!le(e[1])?void 0:{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&le(e[3])?e[3]:void 0};case"A":case"a":return e[1]?di(e[1],e[2]):void 0;case"I":case"i":return e[1]?{value:e[1],hint:e[2]}:void 0}}function _d(e){if(e[1]){if(e[1].includes(":"))return di(e[1],e[2]);if(le(e[1]))return{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&le(e[3])?e[3]:void 0}}}function Ls(e){return e.findLast(t=>t.tagName==="A"||t.tagName==="a")?.pointer||e.findLast(t=>t.tagName==="I"||t.tagName==="i")?.pointer||e.findLast(t=>t.tagName==="E"||t.tagName==="e")?.pointer}function cr(e,t){if(!e||!("id"in e)||!e.author)return;let n=t.find(r=>r.pubkey===e.author);!n||!n.relays||(e.relays||(e.relays=[]),n.relays.forEach(r=>{e.relays.indexOf(r)===-1&&e.relays.push(r)}),n.relays=e.relays)}function Bd(e){let t={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},n=[],r=[];for(let o of e.tags){if((o[0]==="E"||o[0]==="A"||o[0]==="I")&&o[1]){let s=Us(o);s&&n.push({tagName:o[0],pointer:s});continue}if((o[0]==="e"||o[0]==="a"||o[0]==="i")&&o[1]){let s=Us(o);s&&r.push({tagName:o[0],pointer:s});continue}if(o[0]==="K"){t.rootKind=ks(o[1]);continue}if(o[0]==="k"){t.replyKind=ks(o[1]);continue}if(o[0]==="q"){let s=_d(o);s&&t.quotes.push(s);continue}(o[0]==="P"||o[0]==="p")&&o[1]&&le(o[1])&&t.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]})}return t.root=Ls(n),t.reply=Ls(r),cr(t.root,t.profiles),cr(t.reply,t.profiles),t.quotes.forEach(o=>cr(o,t.profiles)),t}var kd={};z(kd,{finishReactionEvent:()=>Ud,getReactedEventPointer:()=>Ld});function Ud(e,t,n){let r=t.tags.filter(o=>o.length>=2&&(o[0]==="e"||o[0]==="p"));return pe({...e,kind:xr,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function Ld(e){if(e.kind!==xr)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){let o=e.tags[r];o.length>=2&&(o[0]==="e"&&t===void 0?t=o:o[0]==="p"&&n===void 0&&(n=o))}if(!(t===void 0||n===void 0))return{id:t[1],relays:[t[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Cd={};z(Cd,{parse:()=>Nd});var lr=/\W/m,Cs=/[^\w\/] |[^\w\/]$|$|,| /m,Id=42;function*Nd(e){let t=[];if(typeof e!="string"){for(let s=0;s<e.tags.length;s++){let i=e.tags[s];i[0]==="emoji"&&i.length>=3&&t.push({type:"emoji",shortcode:i[1],url:i[2]})}e=e.content}let n=e.length,r=0,o=0;e:for(;o<n;){let s=e.indexOf(":",o),i=e.indexOf("#",o);if(s===-1&&i===-1)break e;if(s===-1||i>=0&&i<s){if(i===0||e[i-1].match(lr)){let a=e.slice(i+1,i+Id).match(lr),c=a?i+1+a.index:n;yield{type:"text",text:e.slice(r,i)},yield{type:"hashtag",value:e.slice(i+1,c)},o=c,r=o;continue e}o=i+1;continue e}if(e.slice(s-5,s)==="nostr"){let a=e.slice(s+60).match(lr),c=a?s+60+a.index:n;try{let l,{data:u,type:f}=en(e.slice(s+1,c));switch(f){case"npub":l={pubkey:u};break;case"note":l={id:u};break;case"nsec":o=c+1;continue;default:l=u}r!==s-5&&(yield{type:"text",text:e.slice(r,s-5)}),yield{type:"reference",pointer:l},o=c,r=o;continue e}catch{o=s+1;continue e}}else if(e.slice(s-5,s)==="https"||e.slice(s-4,s)==="http"){let a=e.slice(s+4).match(Cs),c=a?s+4+a.index:n,l=e[s-1]==="s"?5:4;try{let u=new URL(e.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid url");if(r!==s-l&&(yield{type:"text",text:e.slice(r,s-l)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(u.pathname)){yield{type:"image",url:u.toString()},o=c,r=o;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(u.pathname)){yield{type:"video",url:u.toString()},o=c,r=o;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(u.pathname)){yield{type:"audio",url:u.toString()},o=c,r=o;continue e}yield{type:"url",url:u.toString()},o=c,r=o;continue e}catch{o=c+1;continue e}}else if(e.slice(s-3,s)==="wss"||e.slice(s-2,s)==="ws"){let a=e.slice(s+4).match(Cs),c=a?s+4+a.index:n,l=e[s-1]==="s"?3:2;try{let u=new URL(e.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid ws url");r!==s-l&&(yield{type:"text",text:e.slice(r,s-l)}),yield{type:"relay",url:u.toString()},o=c,r=o;continue e}catch{o=c+1;continue e}}else{for(let a=0;a<t.length;a++){let c=t[a];if(e[s+c.shortcode.length+1]===":"&&e.slice(s+1,s+c.shortcode.length+1)===c.shortcode){r!==s&&(yield{type:"text",text:e.slice(r,s)}),yield c,o=s+c.shortcode.length+2,r=o;continue e}}o=s+1;continue e}}r!==n&&(yield{type:"text",text:e.slice(r)})}var Md={};z(Md,{channelCreateEvent:()=>Od,channelHideMessageEvent:()=>Dd,channelMessageEvent:()=>Hd,channelMetadataEvent:()=>Pd,channelMuteUserEvent:()=>qd});var Od=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return pe({kind:Hs,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Pd=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return pe({kind:Ds,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Hd=(e,t)=>{let n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),pe({kind:qs,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},Dd=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return pe({kind:Fs,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},qd=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return pe({kind:$s,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},Fd={};z(Fd,{EMOJI_SHORTCODE_REGEX:()=>hi,matchAll:()=>$d,regex:()=>Or,replaceAll:()=>Vd});var hi=/:(\w+):/,Or=()=>new RegExp(`\\B${hi.source}\\B`,"g");function*$d(e){let t=e.matchAll(Or());for(let n of t)try{let[r,o]=n;yield{shortcode:r,name:o,start:n.index,end:n.index+r.length}}catch{}}function Vd(e,t){return e.replaceAll(Or(),(n,r)=>t({shortcode:n,name:r}))}var Gd={};z(Gd,{useFetchImplementation:()=>Kd,validateGithub:()=>Wd});var Pr;try{Pr=fetch}catch{}function Kd(e){Pr=e}async function Wd(e,t,n){try{return await(await Pr(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var jd={};z(jd,{makeNwcRequestEvent:()=>Zd,parseConnectionString:()=>zd});function zd(e){let{host:t,pathname:n,searchParams:r}=new URL(e),o=n||t,s=r.getAll("relay"),i=r.get("secret");if(!o||s.length===0||!i)throw new Error("invalid connection string");return{pubkey:o,relay:s[0],relays:s,secret:i}}async function Zd(e,t,n){let o=zs(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:Ks,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e]]};return pe(s,t)}var Yd={};z(Yd,{normalizeIdentifier:()=>Xd});function Xd(e){return e=e.trim().toLowerCase(),e=e.normalize("NFKC"),Array.from(e).map(t=>/\p{Letter}/u.test(t)||/\p{Number}/u.test(t)?t:"-").join("")}var Jd={};z(Jd,{getSatoshisAmountFromBolt11:()=>oh,getZapEndpoint:()=>eh,makeZapReceipt:()=>rh,makeZapRequest:()=>th,useFetchImplementation:()=>Qd,validateZapRequest:()=>nh});var Hr;try{Hr=fetch}catch{}function Qd(e){Hr=e}async function eh(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(r){let[i,a]=r.split("@");t=new URL(`/.well-known/lnurlp/${i}`,`https://${a}`).toString()}else if(n){let{words:i}=Ie.decode(n,1e3),a=Ie.fromWords(i);t=Be.decode(a)}else return null;let s=await(await Hr(t)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function th(e){let t={kind:9734,created_at:Math.round(Date.now()/1e3),content:e.comment||"",tags:[["p","pubkey"in e?e.pubkey:e.event.pubkey],["amount",e.amount.toString()],["relays",...e.relays]]};if("event"in e){if(t.tags.push(["e",e.event.id]),yr(e.event.kind)){let n=["a",`${e.event.kind}:${e.event.pubkey}:`];t.tags.push(n)}else if(br(e.event.kind)){let n=e.event.tags.find(([o,s])=>o==="d"&&s);if(!n)throw new Error("d tag not found or is empty");let r=["a",`${e.event.kind}:${e.event.pubkey}:${n[1]}`];t.tags.push(r)}t.tags.push(["k",e.event.kind.toString()])}return t}function nh(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!hr(t))return"Zap request is not a valid Nostr event.";if(!gr(t))return"Invalid signature on zap request.";let n=t.tags.find(([s,i])=>s==="p"&&i);if(!n)return"Zap request doesn't have a 'p' tag.";if(!le(n[1]))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find(([s,i])=>s==="e"&&i);return r&&!le(r[1])?"Zap request 'e' tag is not valid hex.":t.tags.find(([s,i])=>s==="relays"&&i)?null:"Zap request doesn't have a 'relays' tag."}function rh({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let o=JSON.parse(e),s=o.tags.filter(([a])=>a==="e"||a==="p"||a==="a"),i={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",o.pubkey],["bolt11",n],["description",e]]};return t&&i.tags.push(["preimage",t]),i}function oh(e){if(e.length<50)return 0;e=e.substring(0,50);let t=e.lastIndexOf("1");if(t===-1)return 0;let n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;let r=n.substring(4);if(r.length<1)return 0;let o=r[r.length-1],s=o.charCodeAt(0)-48,i=s>=0&&s<=9,a=r.length-1;if(i&&a++,a<1)return 0;let c=parseInt(r.substring(0,a));switch(o){case"m":return c*1e5;case"u":return c*100;case"n":return c/10;case"p":return c/1e4;default:return c*1e8}}var sh={};z(sh,{Negentropy:()=>mi,NegentropyStorageVector:()=>ch,NegentropySync:()=>lh});var ur=97,tt=32,pi=16,Ve={Skip:0,Fingerprint:1,IdList:2},_e=class{_raw;length;constructor(e){typeof e=="number"?(this._raw=new Uint8Array(e),this.length=0):e instanceof Uint8Array?(this._raw=new Uint8Array(e),this.length=e.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(e){if(e instanceof _e&&(e=e.unwrap()),typeof e.length!="number")throw Error("bad length");let t=e.length+this.length;if(this.capacity<t){let n=this._raw,r=Math.max(this.capacity*2,t);this._raw=new Uint8Array(r),this._raw.set(n)}this._raw.set(e,this.length),this.length+=e.length}shift(){let e=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,e}shiftN(e=1){let t=this._raw.subarray(0,e);return this._raw=this._raw.subarray(e),this.length-=e,t}};function Zt(e){let t=0;for(;;){if(e.length===0)throw Error("parse ends prematurely");let n=e.shift();if(t=t<<7|n&127,(n&128)===0)break}return t}function Re(e){if(e===0)return new _e(new Uint8Array([0]));let t=[];for(;e!==0;)t.push(e&127),e>>>=7;t.reverse();for(let n=0;n<t.length-1;n++)t[n]|=128;return new _e(new Uint8Array(t))}function ih(e){return Xt(e,1)[0]}function Xt(e,t){if(e.length<t)throw Error("parse ends prematurely");return e.shiftN(t)}var ah=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(tt)}add(e){let t=0,n=0,r=new DataView(this.buf.buffer),o=new DataView(e.buffer);for(let s=0;s<8;s++){let i=s*4,a=r.getUint32(i,!0),c=o.getUint32(i,!0),l=a;l+=t,l+=c,l>4294967295&&(n=1),r.setUint32(i,l&4294967295,!0),t=n,n=0}}negate(){let e=new DataView(this.buf.buffer);for(let n=0;n<8;n++){let r=n*4;e.setUint32(r,~e.getUint32(r,!0))}let t=new Uint8Array(tt);t[0]=1,this.add(t)}getFingerprint(e){let t=new _e;return t.extend(this.buf),t.extend(Re(e)),ee(t.unwrap()).subarray(0,pi)}},ch=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(e,t){if(this.sealed)throw Error("already sealed");let n=$(t);if(n.byteLength!==tt)throw Error("bad id size for added item");this.items.push({timestamp:e,id:n})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(fr);for(let e=1;e<this.items.length;e++)if(fr(this.items[e-1],this.items[e])===0)throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(e){if(this._checkSealed(),e>=this.items.length)throw Error("out of range");return this.items[e]}iterate(e,t,n){this._checkSealed(),this._checkBounds(e,t);for(let r=e;r<t&&n(this.items[r],r);++r);}findLowerBound(e,t,n){return this._checkSealed(),this._checkBounds(e,t),this._binarySearch(this.items,e,t,r=>fr(r,n)<0)}fingerprint(e,t){let n=new ah;return n.setToZero(),this.iterate(e,t,r=>(n.add(r.id),!0)),n.getFingerprint(t-e)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(e,t){if(e>t||t>this.items.length)throw Error("bad range")}_binarySearch(e,t,n,r){let o=n-t;for(;o>0;){let s=t,i=Math.floor(o/2);s+=i,r(e[s])?(t=++s,o-=i+1):o=i}return t}},mi=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(e,t=6e4){if(t<4096)throw Error("frameSizeLimit too small");this.storage=e,this.frameSizeLimit=t,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(e,t){return{timestamp:e,id:t||new Uint8Array(0)}}initiate(){let e=new _e;return e.extend(new Uint8Array([ur])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),e),P(e.unwrap())}reconcile(e,t,n){let r=new _e($(e));this.lastTimestampIn=this.lastTimestampOut=0;let o=new _e;o.extend(new Uint8Array([ur]));let s=ih(r);if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(s!==ur)throw Error("unsupported negentropy protocol version requested: "+(s-96));let i=this.storage.size(),a=this._bound(0),c=0,l=!1;for(;r.length!==0;){let u=new _e,f=()=>{l&&(l=!1,u.extend(this.encodeBound(a)),u.extend(Re(Ve.Skip)))},h=this.decodeBound(r),d=Zt(r),m=c,g=this.storage.findLowerBound(c,i,h);if(d===Ve.Skip)l=!0;else if(d===Ve.Fingerprint){let p=Xt(r,pi),y=this.storage.fingerprint(m,g);gi(p,y)!==0?(f(),this.splitRange(m,g,h,u)):l=!0}else if(d===Ve.IdList){let p=Zt(r),y={};for(let E=0;E<p;E++){let A=Xt(r,tt);y[P(A)]=A}if(l=!0,this.storage.iterate(m,g,E=>{let A=E.id,I=P(A);return y[I]?delete y[P(A)]:t?.(I),!0}),n)for(let E of Object.values(y))n(P(E))}else throw Error("unexpected mode");if(this.exceededFrameSizeLimit(o.length+u.length)){let p=this.storage.fingerprint(g,i);o.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),o.extend(Re(Ve.Fingerprint)),o.extend(p);break}else o.extend(u);c=g,a=h}return o.length===1?null:P(o.unwrap())}splitRange(e,t,n,r){let o=t-e,s=16;if(o<s*2)r.extend(this.encodeBound(n)),r.extend(Re(Ve.IdList)),r.extend(Re(o)),this.storage.iterate(e,t,i=>(r.extend(i.id),!0));else{let i=Math.floor(o/s),a=o%s,c=e;for(let l=0;l<s;l++){let u=i+(l<a?1:0),f=this.storage.fingerprint(c,c+u);c+=u;let h;if(c===t)h=n;else{let d,m;this.storage.iterate(c-1,c+1,(g,p)=>(p===c-1?d=g:m=g,!0)),h=this.getMinimalBound(d,m)}r.extend(this.encodeBound(h)),r.extend(Re(Ve.Fingerprint)),r.extend(f)}}}exceededFrameSizeLimit(e){return e>this.frameSizeLimit-200}decodeTimestampIn(e){let t=Zt(e);return t=t===0?Number.MAX_VALUE:t-1,this.lastTimestampIn===Number.MAX_VALUE||t===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(t+=this.lastTimestampIn,this.lastTimestampIn=t,t)}decodeBound(e){let t=this.decodeTimestampIn(e),n=Zt(e);if(n>tt)throw Error("bound key too long");let r=Xt(e,n);return{timestamp:t,id:r}}encodeTimestampOut(e){if(e===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,Re(0);let t=e;return e-=this.lastTimestampOut,this.lastTimestampOut=t,Re(e+1)}encodeBound(e){let t=new _e;return t.extend(this.encodeTimestampOut(e.timestamp)),t.extend(Re(e.id.length)),t.extend(e.id),t}getMinimalBound(e,t){if(t.timestamp!==e.timestamp)return this._bound(t.timestamp);{let n=0,r=t.id,o=e.id;for(let s=0;s<tt&&r[s]===o[s];s++)n++;return this._bound(t.timestamp,t.id.subarray(0,n+1))}}};function gi(e,t){for(let n=0;n<e.byteLength;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return e.byteLength>t.byteLength?1:e.byteLength<t.byteLength?-1:0}function fr(e,t){return e.timestamp===t.timestamp?gi(e.id,t.id):e.timestamp-t.timestamp}var lh=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(e,t,n,r={}){this.relay=e,this.storage=t,this.neg=new mi(t),this.onhave=r.onhave,this.onneed=r.onneed,this.filter=n,this.subscription=this.relay.prepareSubscription([{}],{label:r.label||"negentropy"}),this.subscription.oncustom=o=>{switch(o[0]){case"NEG-MSG":{o.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${o}`);try{let s=this.neg.reconcile(o[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":{let s=o[2];console.warn("negentropy error:",s),r.onclose?.(s);break}case"NEG-ERR":r.onclose?.()}}}async start(){let e=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${e}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},uh={};z(uh,{getToken:()=>fh,hashPayload:()=>Dr,unpackEventFromToken:()=>bi,validateEvent:()=>Ai,validateEventKind:()=>xi,validateEventMethodTag:()=>Ei,validateEventPayloadTag:()=>Si,validateEventTimestamp:()=>wi,validateEventUrlTag:()=>vi,validateToken:()=>dh});var yi="Nostr ";async function fh(e,t,n,r=!1,o){let s={kind:Er,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};o&&s.tags.push(["payload",Dr(o)]);let i=await n(s);return(r?yi:"")+be.encode(he.encode(JSON.stringify(i)))}async function dh(e,t,n){let r=await bi(e).catch(s=>{throw s});return await Ai(r,t,n).catch(s=>{throw s})}async function bi(e){if(!e)throw new Error("Missing token");e=e.replace(yi,"");let t=Be.decode(be.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function wi(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function xi(e){return e.kind===Er}function vi(e,t){let n=e.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===t:!1}function Ei(e,t){let n=e.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===t.toLowerCase():!1}function Dr(e){let t=ee(he.encode(JSON.stringify(e)));return P(t)}function Si(e,t){let n=e.tags.find(o=>o[0]==="payload");if(!n)return!1;let r=Dr(t);return n.length>0&&n[1]===r}async function Ai(e,t,n,r){if(!gr(e))throw new Error("Invalid nostr event, signature invalid");if(!xi(e))throw new Error("Invalid nostr event, kind invalid");if(!wi(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!vi(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!Ei(e,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!Si(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}var on=23478;async function Ti(e,t){let n=ot(e),r=await mo(n,t),o={kind:on,created_at:Math.floor(Date.now()/1e3),tags:[[ct,lt(n)]],content:r};return pe(o,pr())}var sn={stalePacketMs:1e3,receiptStaleMs:3e3,pathRttBadMs:1500,pathDeliveryBad:.8,pathBanMs:3e4,pathMinSamples:5,rateBanMs:3e4,rateBanMaxMs:3e5,blockedBanMs:6e5,connectBackoffMs:2e3,connectBackoffMaxMs:3e5,publishTimeoutMs:4e3,bucketRate:8,bucketBurst:8,bucketMinRate:1,bucketMaxRate:20,bucketIncreaseEveryMs:1e4,maxEventPlaintext:49152,dupRelays:2,statsEveryMs:3e4,eventMaxAgeMs:3e4};var Ri=(e,t)=>e===void 0?t:e+.3*(t-e),an=class{constructor(t){this.t=t;this.paths=new Map;this.lastReceipt=new Map}sent(t,n,r,o){this.state(t,n,o).outstanding.push({seq:r,at:o})}receipt(t,n,r){this.lastReceipt.set(t,r);let o=this.state(t,n.path,r),s=o.outstanding.filter(c=>c.seq<=n.lastSeq);o.outstanding=o.outstanding.filter(c=>c.seq>n.lastSeq);let i=o.prevRecv===void 0?Math.min(n.recv,s.length):n.recv-o.prevRecv;o.prevRecv=n.recv;let a=s.find(c=>c.seq===n.lastSeq);a&&(o.rttMs=Ri(o.rttMs,Math.max(0,r-a.at-n.holdMs))),s.length>0&&this.account(o,s.length,Math.max(0,i),r),this.sweepFlow(t,r)}sweep(t){for(let n of this.paths.keys())this.sweepFlow(n,t)}receiptFresh(t,n){let r=this.lastReceipt.get(t);return r!==void 0&&n-r<this.t.receiptStaleMs}view(t,n,r){let o=this.paths.get(t)?.get(n);return o?(this.expire(o,r),{delivery:o.delivery,rttMs:o.rttMs,banned:r<o.bannedUntil,samples:o.samples}):{delivery:void 0,rttMs:void 0,banned:!1,samples:0}}entries(t){let n=[];for(let[r,o]of this.paths)for(let s of o.keys())n.push({flow:r,path:s,view:this.view(r,s,t)});return n}forget(t){this.paths.delete(t),this.lastReceipt.delete(t)}sweepFlow(t,n){if(!this.receiptFresh(t,n))return;let r=this.t.pathRttBadMs*2;for(let o of this.paths.get(t)?.values()??[]){let s=o.outstanding.filter(i=>n-i.at>=r);s.length!==0&&(o.outstanding=o.outstanding.filter(i=>n-i.at<r),this.account(o,s.length,0,n))}}account(t,n,r,o){t.delivery=Ri(t.delivery,Math.min(1,r/n)),t.samples+=n;let s=(t.delivery??1)<this.t.pathDeliveryBad||(t.rttMs??0)>this.t.pathRttBadMs;t.samples>=this.t.pathMinSamples&&s&&o>=t.bannedUntil&&(t.bannedUntil=o+this.t.pathBanMs)}expire(t,n){t.bannedUntil===0||n<t.bannedUntil||Object.assign(t,{delivery:void 0,rttMs:void 0,samples:0,bannedUntil:0,prevRecv:t.prevRecv})}state(t,n,r){let o=this.paths.get(t);o||this.paths.set(t,o=new Map);let s=o.get(n);return s||o.set(n,s={outstanding:[],prevRecv:void 0,delivery:void 0,rttMs:void 0,samples:0,bannedUntil:0}),this.expire(s,r),s}};var cn=class{constructor(){this.flows=new Map}accept(t,n,r,o){let s=this.flow(t),i=s.paths.get(r)??{recv:0,lastSeq:n,at:o};if(i.recv+=1,(i.recv===1||n>=i.lastSeq)&&(i.lastSeq=n,i.at=o),s.paths.set(r,i),n<=s.maxSeq-2048||s.seen.has(n))return!1;if(s.seen.add(n),n>s.maxSeq){s.maxSeq=n;for(let a of s.seen)a<=n-2048&&s.seen.delete(a)}return!0}receiptsFor(t,n){let r=this.flows.get(t);return r?[...r.paths.entries()].sort(([o],[s])=>o-s).map(([o,s])=>({path:o,recv:s.recv,lastSeq:s.lastSeq,holdMs:Math.min(65535,n-s.at)})):[]}forget(t){this.flows.delete(t)}flow(t){let n=this.flows.get(t);return n||this.flows.set(t,n={seen:new Set,maxSeq:-1,paths:new Map}),n}};var _i=e=>e.estRttMs+e.waitMs;function Bi(e,t){let n=e.filter(i=>i.usable);if(n.length===0)return{indices:[],waitMs:null};let r=n.filter(i=>!i.pathBanned),o=(r.length>0?r:n).slice().sort((i,a)=>_i(i)-_i(a));if(t.dup){let i=o.filter(a=>a.waitMs===0).sort((a,c)=>a.estRttMs-c.estRttMs).slice(0,t.dupCount);return i.length>0?{indices:i.map(a=>a.index),waitMs:0}:{indices:[],waitMs:Math.min(...o.map(a=>a.waitMs))}}let s=o[0];return s.waitMs===0?{indices:[s.index],waitMs:0}:{indices:[],waitMs:s.waitMs}}function ki(e,t,n,r){return e.map((o,s)=>{let i=t.view(n,s,r),a=i.rttMs??2*(o.health.okRttMs??150)+400;return{index:s,usable:o.health.usable(r),pathBanned:i.banned,waitMs:o.health.bucket.waitMs(r),estRttMs:a}})}var ln=class{constructor(t){this.opts=t;this.stale=0;this.queues=new Map}push(t,n,r){let o=this.queues.get(t)??[];o.push({bytes:n,at:r}),this.queues.set(t,o)}dropStale(t,n){let r=this.queues.get(t);for(;r&&r.length>0&&n-r[0].at>this.opts.staleMs;)r.shift(),this.stale+=1;r?.length===0&&this.queues.delete(t)}take(t,n,r){this.dropStale(t,n);let o=this.queues.get(t);if(!o)return[];let s=[],i=0;for(;o.length>0;){let a=2+o[0].bytes.length;if(s.length>0&&i+a>r)break;s.push(o.shift().bytes),i+=a}return o.length===0&&this.queues.delete(t),s}size(t){return this.queues.get(t)?.length??0}delete(t){this.queues.delete(t)}clear(){this.queues.clear()}};function Li(e){try{return new URL(e).host}catch{return e}}var hh=e=>`\u2026${e.split(":").slice(-3).join(":")}`,Ui=e=>e===void 0?"-":`${Math.round(e)}ms`;function ph(e,t){let n=e.map(o=>{let s=o.counters,i=o.banReason?` ban=${JSON.stringify(o.banReason)}`:"";return`stats relay=${Li(o.url)} state=${o.state} pub=${s.published} ok=${s.ok} rej=${s.rejected} notice=${s.notices} timeout=${s.timeouts} recv=${s.received} rate=${Math.round(o.rate)}/s okRtt=${Ui(o.okRttMs)}${i}`}),r=t.map(o=>{let s=o.flow.split(">").map(hh).join(">"),i=o.view.delivery===void 0?"-":o.view.delivery.toFixed(2);return`stats path=${s} relay=${o.host} deliv=${i} rtt=${Ui(o.view.rttMs)} samples=${o.view.samples}${o.view.banned?" banned":""}`});return[...n,...r]}function Ci(e,t,n){let r=setInterval(()=>{let o=Date.now(),s=e.paths.entries(o).map(i=>({flow:i.flow,host:Li(e.links[i.path]?.url??"?"),view:i.view}));for(let i of ph(e.links.map(a=>a.health.snapshot(o)),s))t(i)},n);return r.unref?.(),()=>clearInterval(r)}var mh=512,gh=250,vt=(e,t)=>`${xe(e)}>${xe(t)}`;function Ii(e){let t={...sn,...e.tunables},{links:n}=e,r={published:0,seqs:0,dropped:0,delivered:0,duplicates:0},o=new ln({staleMs:t.stalePacketMs}),s=new an(t),i=new cn,a=new Map,c=new Map,l=!1,u=(p,y,E)=>{y.timer||l||(y.timer=setTimeout(()=>{y.timer=null,f(p,y)},E))},f=(p,y)=>{let E=Date.now();if(o.dropStale(p,E),o.size(p)===0)return;let A=Bi(ki(n,s,p,E),{dup:!s.receiptFresh(p,E),dupCount:t.dupRelays});if(A.indices.length===0){n.length===0?o.delete(p):u(p,y,A.waitMs??gh);return}let I=o.take(p,E,t.maxEventPlaintext-mh),q=y.seq;y.seq=y.seq+1>>>0;let O=i.receiptsFor(vt(y.dst,y.src),E);for(let V of A.indices){n[V].health.bucket.take(E),s.sent(p,V,q,E),r.published+=1;let H=yo({src18:ot(y.src),seq:q,path:V,receipts:O,packets:I});Ti(y.dst,H).then(L=>n[V].publish(L))}r.seqs+=1,o.size(p)>0&&u(p,y,0)},h=async(p,y)=>{let E=y.tags.find(H=>H[0]===ct)?.[1],A=E?c.get(E):void 0;if(!A)return;let I=await go(A.addr18,y.content),q=I&&bo(I),O=q&&io(q.src18);if(!q||!O||c.get(E)!==A)return;let V=Date.now();for(let H of q.receipts)s.receipt(vt(A.addr,O),H,V);if(!i.accept(vt(O,A.addr),q.seq,q.path,V)){r.duplicates+=1;return}r.delivered+=q.packets.length;for(let H of q.packets)A.onPacket(O,H)},d=()=>{let p=l||c.size===0?null:{kinds:[on],[`#${ct}`]:[...c.keys()],since:Math.floor(Date.now()/1e3)};n.forEach((y,E)=>y.subscribe(p,A=>{h(E,A)}))},m=p=>{let y=xe(p);for(let[E,A]of a)xe(A.src)===y&&(A.timer&&clearTimeout(A.timer),a.delete(E),o.delete(E),s.forget(E),i.forget(vt(A.dst,A.src)))},g=e.log?Ci({links:n,paths:s},e.log,t.statsEveryMs):void 0;return{send(p,y,E){if(l)return;if(!so(y)){r.dropped+=1;return}let A=vt(p,y),I=a.get(A);I||a.set(A,I={src:p,dst:y,seq:0,timer:null}),o.push(A,E.slice(),Date.now()),u(A,I,0)},listen(p,y){let E=ot(p),A=lt(E),I={addr:p,addr18:E,onPacket:y};return c.set(A,I),d(),()=>{c.get(A)===I&&(c.delete(A),m(p),d())}},stats:()=>({...r,stale:o.stale}),close(){l=!0,g?.();for(let p of a.values())p.timer&&clearTimeout(p.timer);a.clear(),o.clear(),c.clear(),d()}}}import{renameSync as yh,rmSync as bh,writeFileSync as wh}from"fs";var xh=0;function Et(e,t){let n=`${e}.${process.pid}.${++xh}.tmp`;try{wh(n,t,"utf-8"),yh(n,e)}catch(r){throw bh(n,{force:!0}),r}}function qr(e,t){Et(e,String(t))}function Fr(e,t){Et(e,String(t))}var Zm=new TextDecoder("utf-8"),Ym=new TextEncoder;function vh(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.protocol==="http:"?t.protocol="ws:":t.protocol==="https:"&&(t.protocol="wss:"),t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}var Eh=22242;function Sh(e,t){if(e.ids&&e.ids.indexOf(t.id)===-1||e.kinds&&e.kinds.indexOf(t.kind)===-1||e.authors&&e.authors.indexOf(t.pubkey)===-1)return!1;for(let n in e)if(n[0]==="#"){let r=n.slice(1),o=e[`#${r}`];if(o&&!t.tags.find(([s,i])=>s===n.slice(1)&&o.indexOf(i)!==-1))return!1}return!(e.since&&t.created_at<e.since||e.until&&t.created_at>e.until)}function Ah(e,t){for(let n=0;n<e.length;n++)if(Sh(e[n],t))return!0;return!1}function Th(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,o=e.slice(r).indexOf('"')+r+1;return e.slice(o,o+64)}function Rh(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,o=e.slice(r+1,80).indexOf('"');if(o===-1)return null;let s=r+1+o;return e.slice(r+1,s)}function _h(e,t){return{kind:Eh,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var $r=class extends Error{constructor(e,t){super(`Tried to send message '${e} on a closed connection to ${t}.`),this.name="SendingOnClosedConnection"}},Vr=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);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(e,t){this.url=vh(e),this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation||WebSocket,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,t.idleTimeout&&(this.idleTimeout=t.idleTimeout)}static async connect(e,t){let n=new Vr(e,t);return await n.connect(t),n}closeAllSubscriptions(e){for(let[t,n]of this.openSubs)n.close(e);this.openSubs.clear();for(let[t,n]of this.openEventPublishes)n.reject(new Error(e));this.openEventPublishes.clear();for(let[t,n]of this.openCountRequests)n.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}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(){let e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose=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(e))}async connect(e){let t;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{e?.timeout&&(t=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.reconnectAttempts===0&&(this.skipReconnection=!0),this.handleHardClose("relay connection timed out")},e.timeout)),e?.abort&&(e.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(o){clearTimeout(t),r(o);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(t),this._connected=!0;let o=this.reconnectAttempts>0;this.reconnectAttempts=0;for(let s of this.openSubs.values()){if(s.eosed=!1,o)for(let i=0;i<s.filters.length;i++)s.lastEmitted&&(s.filters[i].since=s.lastEmitted+1);s.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(t),r("connection failed"),this.connectionPromise=void 0,this.reconnectAttempts===0&&(this.skipReconnection=!0),this.handleHardClose("relay connection failed")},this.ws.onclose=o=>{clearTimeout(t),r(o.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,t)=>{if(!this.connectionPromise)return t(new Error(`no connection to ${this.url}, can't ping`));try{let n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),n.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){t(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(t=>setTimeout(()=>t(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(e){if(!this.connectionPromise)throw new $r(e,this.url);this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){let t=this.challenge;if(!t)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let o=await e(_h(this.url,t)),s=setTimeout(()=>{let i=this.openEventPublishes.get(o.id);i&&(i.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))},this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:s}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(o){console.warn("subscribe auth function failed:",o)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++;let t=new Promise((n,r)=>{let o=setTimeout(()=>{let s=this.openEventPublishes.get(e.id);s&&(s.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:n,reject:r,timeout:o})});try{await this.send('["EVENT",'+JSON.stringify(e)+"]")}catch(n){let r=this.openEventPublishes.get(e.id);r&&(r.reject(n),this.openEventPublishes.delete(e.id))}return this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now(),this.scheduleIdleClose()),t}async count(e,t){return(await this.countWithHLL(e,t)).count}async countWithHLL(e,t){this.serial++;let n=t?.id||"count:"+this.serial,r=new Promise((o,s)=>{this.openCountRequests.set(n,{resolve:o,reject:s})});try{await this.send('["COUNT","'+n+'",'+JSON.stringify(e).substring(1))}catch(o){let s=this.openCountRequests.get(n);s&&(s.reject(o),this.openCountRequests.delete(n))}return r}subscribe(e,t){t.label!=="<forced-ping>"&&(this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++);let n=this.prepareSubscription(e,t);return n.fire(),t.abort&&(t.abort.onabort=()=>n.close(String(t.abort.reason||"<aborted>"))),n}prepareSubscription(e,t){this.serial++;let n=t.id||(t.label?t.label+":":"sub:")+this.serial,r=new Bh(this,n,e,t);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=null,this.ws.readyState!==this._WebSocket.CLOSING&&this.ws.readyState!==this._WebSocket.CLOSED&&this.ws.close())}_onmessage(e){let t=e.data;if(!t)return;let n=Rh(t);if(n){let r=this.openSubs.get(n);if(!r)return;let o=Th(t,"id"),s=r.alreadyHaveEvent?.(o);if(r.receivedEvent?.(this,o),s)return}try{let r=JSON.parse(t);switch(r[0]){case"EVENT":{let o=this.openSubs.get(r[1]),s=r[2];Ah(o.filters,s)&&this.verifyEvent(s,this.url)?o.onevent(s):o.oninvalidevent?.(s),(!o.lastEmitted||o.lastEmitted<s.created_at)&&(o.lastEmitted=s.created_at);return}case"COUNT":{let o=r[1],s=r[2],i=this.openCountRequests.get(o);i&&(i.resolve(s),this.openCountRequests.delete(o));return}case"EOSE":{let o=this.openSubs.get(r[1]);if(!o)return;o.receivedEose();return}case"OK":{let o=r[1],s=r[2],i=r[3],a=this.openEventPublishes.get(o);a&&(clearTimeout(a.timeout),s?a.resolve(i):a.reject(new Error(i)),this.openEventPublishes.delete(o));return}case"CLOSED":{let o=r[1],s=this.openSubs.get(o);if(!s){let i=this.openCountRequests.get(o);i&&(i.reject(new Error(r[2])),this.openCountRequests.delete(o));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(o=>{if(!(o instanceof $r))throw o});return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{let[o,s,i]=JSON.parse(t);console.warn(`[nostr] relay ${this.url} error processing message:`,r,i)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},Bh=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,t,n,r){if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=n,this.id=t,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||e.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}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(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(t){if(!(t instanceof $r))throw t}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?.(e)}};var un=class{constructor(t,n){this.t=t;this.current=t.bucketRate,this.tokens=t.bucketBurst,this.refilledAt=n,this.changedAt=n}get rate(){return this.current}waitMs(t){return this.advance(t),this.tokens>=1?0:Math.ceil((1-this.tokens)/this.current*1e3)}take(t){return this.waitMs(t)>0?!1:(this.tokens-=1,!0)}penalize(t){this.advance(t),this.current=Math.max(this.t.bucketMinRate,this.current/2),this.tokens=Math.min(this.tokens,0),this.changedAt=t}advance(t){for(;t-this.changedAt>=this.t.bucketIncreaseEveryMs&&this.current<this.t.bucketMaxRate;)this.refill(this.changedAt+this.t.bucketIncreaseEveryMs),this.current=Math.min(this.t.bucketMaxRate,this.current+1),this.changedAt+=this.t.bucketIncreaseEveryMs;this.current>=this.t.bucketMaxRate&&(this.changedAt=Math.max(this.changedAt,t-this.t.bucketIncreaseEveryMs)),this.refill(t)}refill(t){t<=this.refilledAt||(this.tokens=Math.min(this.t.bucketBurst,this.tokens+(t-this.refilledAt)/1e3*this.current),this.refilledAt=t)}};var kh=/^(blocked|restricted|pow|auth-required|invalid):/i,Uh=/rate|too many|slow down/i,Lh=.3;function Ch(e){return/^duplicate:/i.test(e)?"duplicate":kh.test(e)?"blocked":"rate"}var Ih=e=>Uh.test(e),fn=class{constructor(t,n,r){this.url=t;this.t=n;this.counters={published:0,ok:0,rejected:0,notices:0,timeouts:0,received:0};this.connected=!1;this.connectFailures=0;this.bannedUntil=0;this.rateStrikes=0;this.bucket=new un(n,r)}onConnected(){this.connected=!0,this.connectFailures=0}onDisconnected(){this.connected=!1}onConnectFailed(){this.connected=!1;let t=Math.min(this.t.connectBackoffMaxMs,this.t.connectBackoffMs*2**this.connectFailures);return this.connectFailures+=1,t}onPublish(){this.counters.published+=1}onOk(t){this.counters.ok+=1,this.rateStrikes=0,this.okRttMs=this.okRttMs===void 0?t:this.okRttMs+Lh*(t-this.okRttMs)}onRejected(t,n){let r=Ch(t);if(r==="duplicate")return this.onOk(this.okRttMs??0);this.counters.rejected+=1,r==="blocked"?this.ban(n,this.t.blockedBanMs,t):this.rateBan(n,t)}onNotice(t,n){Ih(t)&&(this.counters.notices+=1,this.rateBan(n,t))}onTimeout(t){this.counters.timeouts+=1,this.rateBan(t,"publish timed out")}onReceived(){this.counters.received+=1}usable(t){return this.connected&&t>=this.bannedUntil}snapshot(t){this.bucket.waitMs(t);let n=t<this.bannedUntil,r=n?"banned":this.connected?"connected":this.connectFailures>0?"backoff":"connecting",o={url:this.url,state:r,rate:this.bucket.rate,okRttMs:this.okRttMs,counters:{...this.counters}};return n&&this.banReason&&(o.banReason=this.banReason),o}rateBan(t,n){this.bucket.penalize(t),this.ban(t,Math.min(this.t.rateBanMaxMs,this.t.rateBanMs*2**this.rateStrikes),n),this.rateStrikes+=1}ban(t,n,r){this.bannedUntil=Math.max(this.bannedUntil,t+n),this.banReason=r}};var Nh=5e3;function Ni(e,t){let n=new fn(e,t,Date.now()),r=h=>Date.now()-h.created_at*1e3<=t.eventMaxAgeMs,o=null,s=null,i=null,a,c=!1,l=()=>{if(!o?.connected||!i)return;let{filter:h,onEvent:d}=i,m=s;s=o.subscribe([h],{onevent:g=>{n.onReceived(),d(g)},eoseTimeout:6e4}),m?.close()},u=h=>{c||(clearTimeout(a),a=setTimeout(f,h))},f=()=>{if(c)return;let h=new Vr(e,{verifyEvent:r});h.publishTimeout=t.publishTimeoutMs,h.onnotice=d=>n.onNotice(d,Date.now()),h.onclose=()=>{o===h&&(o=null,s=null,n.onDisconnected(),u(n.onConnectFailed()))},o=h,h.connect({timeout:Nh}).then(()=>{if(c||o!==h)return h.close();n.onConnected(),l()},()=>{o===h&&(o=null,u(n.onConnectFailed()))})};return f(),{url:e,health:n,connected:()=>!!o?.connected,publish(h){let d=o;if(!d?.connected)return;n.onPublish();let m=Date.now();d.publish(h).then(()=>n.onOk(Date.now()-m),g=>{let p=g instanceof Error?g.message:String(g);p==="publish timed out"?n.onTimeout(Date.now()):d.connected&&n.onRejected(p,Date.now())})},subscribe(h,d){i=h?{filter:h,onEvent:d}:null,i?l():(s?.close(),s=null)},close(){c=!0,clearTimeout(a),s?.close(),o?.close(),o=null}}}var nt=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Me=new Uint32Array(80),Kr=class extends Pe{A=nt[0]|0;B=nt[1]|0;C=nt[2]|0;D=nt[3]|0;E=nt[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:t,B:n,C:r,D:o,E:s}=this;return[t,n,r,o,s]}set(t,n,r,o,s){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0}process(t,n){for(let c=0;c<16;c++,n+=4)Me[c]=t.getUint32(n,!1);for(let c=16;c<80;c++)Me[c]=it(Me[c-3]^Me[c-8]^Me[c-14]^Me[c-16],1);let{A:r,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=We(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=kt(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let f=it(r,5)+l+a+u+Me[c]|0;a=i,i=s,s=it(o,30),o=r,r=f}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(r,o,s,i,a)}roundClean(){ce(Me)}destroy(){this.set(0,0,0,0,0),ce(this.buffer)}},Mi=at(()=>new Kr),Mh=Math.pow(2,32),Oh=Array.from({length:64},(e,t)=>Math.floor(Mh*Math.abs(Math.sin(t+1)))),dn=nt.slice(0,4),Gr=new Uint32Array(16),Wr=class extends Pe{A=dn[0]|0;B=dn[1]|0;C=dn[2]|0;D=dn[3]|0;constructor(){super(64,16,8,!0)}get(){let{A:t,B:n,C:r,D:o}=this;return[t,n,r,o]}set(t,n,r,o){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0}process(t,n){for(let a=0;a<16;a++,n+=4)Gr[a]=t.getUint32(n,!0);let{A:r,B:o,C:s,D:i}=this;for(let a=0;a<64;a++){let c,l,u;a<16?(c=We(o,s,i),l=a,u=[7,12,17,22]):a<32?(c=We(i,o,s),l=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=o^s^i,l=(3*a+5)%16,u=[4,11,16,23]):(c=s^(o|~i),l=7*a%16,u=[6,10,15,21]),c=c+r+Oh[a]+Gr[l],r=i,i=s,s=o,o=o+it(c,u[a%4])}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,this.set(r,o,s,i)}roundClean(){ce(Gr)}destroy(){this.set(0,0,0,0),ce(this.buffer)}},Oi=at(()=>new Wr);var we={request:0,indication:16,success:256,error:272},Ge={binding:1,allocate:3,refresh:4,send:6,data:7,createPermission:8,channelBind:9},J={username:6,messageIntegrity:8,errorCode:9,channelNumber:12,lifetime:13,xorPeerAddress:18,data:19,realm:20,nonce:21,xorRelayedAddress:22,requestedTransport:25,xorMappedAddress:32,fingerprint:32808},Hi=24;function rt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ph(e,t){return e&15|(e&112)<<1|(e&3968)<<2|t}function Hh(e){return{method:e&15|(e&224)>>1|(e&15872)>>2,cls:e&272}}var Di=e=>Math.ceil(e/4)*4;function Dh(e){return e.length>=20&&(e[0]&192)===0&&rt(e).getUint32(4)===554869826}function zr(e){if(!Dh(e))return null;let t=rt(e),n=20+t.getUint16(2);if(n>e.length)return null;let r=[];for(let o=20;o+4<=n;o+=4+Di(t.getUint16(o+2))){let s=t.getUint16(o+2);if(o+4+s>n)return null;r.push({type:t.getUint16(o),value:e.subarray(o+4,o+4+s)})}return{...Hh(t.getUint16(0)),transactionId:e.subarray(8,20),attributes:r}}function ke(e,t){return e.attributes.find(n=>n.type===t)?.value}function jr(e,t){let n=new Uint8Array(20),r=rt(n);return r.setUint16(0,Ph(e.method,e.cls)),r.setUint16(2,t),r.setUint32(4,554869826),n.set(e.transactionId,8),n}function St(e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function Pi(e,t){let n=new Uint8Array(4+Di(t.length));return rt(n).setUint16(0,e),rt(n).setUint16(2,t.length),n.set(t,4),n}function At(e,t={}){let n=St(e.attributes.map(s=>Pi(s.type,s.value)));if(!t.integrity)return St([jr(e,n.length),n]);let r=t.integrity(St([jr(e,n.length+Hi),n])),o=St([n,Pi(J.messageIntegrity,r)]);return St([jr(e,o.length),o])}function qi(e){let t=zr(e),n=t&&ke(t,J.messageIntegrity);if(!n)return null;let r=n.byteOffset-e.byteOffset-4,o=e.slice(0,r);return rt(o).setUint16(2,r-20+Hi),{input:o,mac:n}}var Fi="nosturn",hn=e=>new TextEncoder().encode(e);function qh(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function $i(e){let t=Oi(hn(`${e.username}:${Fi}:${e.password}`)),n=hn(globalThis.crypto.randomUUID().replace(/-/g,"")),r=o=>ve(Mi,t,o);return{sign:r,verify(o,s){let i=ke(s,J.username),a=qi(o);return!i||!a||new TextDecoder().decode(i)!==e.username?!1:qh(r(a.input),a.mac)},challenge(o){let s=new Uint8Array([0,0,4,1,...hn("Unauthorized")]);return At({method:o.method,cls:we.error,transactionId:o.transactionId,attributes:[{type:J.errorCode,value:s},{type:J.realm,value:hn(Fi)},{type:J.nonce,value:n}]})}}}import{createSocket as $h}from"node:dgram";var Fh=new Uint8Array([33,18,164,66]);function Gi(e){let t=new Uint8Array(16);return t.set(Fh,0),t.set(e,4),t}function Tt(e,t){let n=new Uint8Array(4+e.address.length),r=new DataView(n.buffer);r.setUint8(1,e.family===6?2:1),r.setUint16(2,e.port^8466);let o=Gi(t);return e.address.forEach((s,i)=>{n[4+i]=s^o[i]}),n}function Zr(e,t){if(e.length<8)return null;let n=e[1]===2?6:e[1]===1?4:null,r=n===6?16:4;if(n===null||e.length<4+r)return null;let o=(e[2]<<8|e[3])^8466,s=Gi(t),i=Uint8Array.from(e.subarray(4,4+r),(a,c)=>a^s[c]);return{family:n,address:i,port:o}}function Yr(e){return e.length>=4&&(e[0]&192)===64}function Ki(e){if(!Yr(e))return null;let t=e[0]<<8|e[1],n=e[2]<<8|e[3];return 4+n>e.length?null:{channel:t,data:e.subarray(4,4+n)}}function Wi(e,t){let n=new Uint8Array(4+Math.ceil(t.length/4)*4);return n[0]=e>>8,n[1]=e&255,n[2]=t.length>>8,n[3]=t.length&255,n.set(t,4),n}var pn=e=>`${e.address}:${e.port}`,mn=class{constructor(){this.byClient=new Map}get(t){return this.byClient.get(pn(t))}create(t,n,r,o){let s={client:t,relay:n,expiresAt:Date.now()+r,channelToPeer:new Map,peerToChannel:new Map,release:o};return this.byClient.set(pn(t),s),s}refresh(t,n){n<=0?this.remove(t):t.expiresAt=Date.now()+n}bind(t,n,r){let o=t.channelToPeer.get(n);o&&t.peerToChannel.delete(xe(o)),t.channelToPeer.set(n,r),t.peerToChannel.set(xe(r),n)}remove(t){this.byClient.get(pn(t.client))===t&&(this.byClient.delete(pn(t.client)),t.release())}expire(t=Date.now()){for(let n of[...this.byClient.values()])n.expiresAt<=t&&this.remove(n)}clear(){for(let t of[...this.byClient.values()])this.remove(t)}};var Vh=600,ji=e=>Uint8Array.of(e>>>24,e>>>16&255,e>>>8&255,e&255);async function zi(e){let t=$h("udp4"),n=new mn,r=e.lifetimeSec??Vh,o=(f,h)=>{t.send(h,f.port,f.address)},s=(f,h,d,m,g=!0)=>{let p={method:h.method,cls:d,transactionId:h.transactionId,attributes:m};o(f,At(p,g?{integrity:e.auth.sign}:{}))},i=(f,h,d)=>{let m=f.peerToChannel.get(xe(h));if(m!==void 0)return o(f.client,Wi(m,d));let g=globalThis.crypto.getRandomValues(new Uint8Array(12));o(f.client,At({method:Ge.data,cls:we.indication,transactionId:g,attributes:[{type:J.xorPeerAddress,value:Tt(h,g)},{type:J.data,value:d}]}))},a=(f,h)=>{let m=n.get(f)??(()=>{let p=oo(),y={},E=n.create(f,p,r*1e3,()=>y.stop?.());return y.stop=e.bridge.listen(p,(A,I)=>i(E,A,I)),E})(),g=wn(f.address,f.port);s(f,h,we.success,[{type:J.xorRelayedAddress,value:Tt(m.relay,h.transactionId)},...g?[{type:J.xorMappedAddress,value:Tt(g,h.transactionId)}]:[],{type:J.lifetime,value:ji(r)}])},c=(f,h)=>{if(h.method===Ge.allocate)return a(f,h);let d=n.get(f);if(!d)return s(f,h,we.error,[{type:J.errorCode,value:Uint8Array.of(0,0,4,37)}]);if(h.method===Ge.refresh){let m=ke(h,J.lifetime),g=m?new DataView(m.buffer,m.byteOffset,4).getUint32(0):r;return n.refresh(d,Math.min(g,r)*1e3),s(f,h,we.success,[{type:J.lifetime,value:ji(Math.min(g,r))}])}if(h.method===Ge.channelBind){let m=ke(h,J.channelNumber),g=ke(h,J.xorPeerAddress),p=g&&Zr(g,h.transactionId);m&&p&&n.bind(d,m[0]<<8|m[1],p)}s(f,h,we.success,[])},l=(f,h,d)=>{if(d.method===Ge.send&&d.cls===we.indication){let m=n.get(f),g=ke(d,J.xorPeerAddress),p=g&&Zr(g,d.transactionId),y=ke(d,J.data);m&&p&&y&&e.bridge.send(m.relay,p,y);return}if(d.cls===we.request){if(d.method===Ge.binding){let m=wn(f.address,f.port);return s(f,d,we.success,m?[{type:J.xorMappedAddress,value:Tt(m,d.transactionId)}]:[],!1)}if(!e.auth.verify(h,d))return o(f,e.auth.challenge(d));c(f,d)}};t.on("message",(f,h)=>{let d=new Uint8Array(f.buffer,f.byteOffset,f.byteLength),m={address:h.address,port:h.port};if(Yr(d)){let p=Ki(d),y=n.get(m),E=p&&y?.channelToPeer.get(p.channel);y&&E&&p&&e.bridge.send(y.relay,E,p.data);return}let g=zr(d);g&&l(m,d,g)});let u=setInterval(()=>n.expire(),3e4);return u.unref(),await new Promise(f=>t.bind(0,e.host??"127.0.0.1",f)),{port:t.address().port,close:()=>new Promise(f=>{clearInterval(u),n.clear(),t.close(()=>f())})}}var Gh="nosturn";async function Zi(e){let t={...sn,...e.tunables},n=e.relays.map(s=>Ni(s,t)),r=Ii({links:n,tunables:t,log:e.log}),o=await zi({bridge:r,auth:$i({username:Gh,password:e.serverId}),log:e.log});return e.portFile&&Fr(e.portFile,o.port),e.pidFile&&qr(e.pidFile,process.pid),e.write?.(`${JSON.stringify({service:"nosturn",port:o.port,pid:process.pid})}
|
|
3
3
|
`),{port:o.port,close:async()=>{await o.close(),r.close();for(let s of n)s.close()}}}function gn(e){process.stderr.write(`[nosturn] ${e}
|
|
4
4
|
`)}async function Kh(){let e=eo(),t=await Zi({...e,write:r=>process.stdout.write(r),log:gn});gn(`listening udp 127.0.0.1:${t.port} relays=${e.relays.length}`);let n=()=>{t.close().finally(()=>process.exit(0))};process.on("SIGTERM",n),process.on("SIGINT",n),process.stdin.resume(),process.stdin.on("end",()=>process.exit(1)),process.on("uncaughtException",r=>{gn(`uncaught: ${r.stack??String(r)}`),process.exit(1)})}Kh().catch(e=>{gn(`boot failed: ${String(e)}`),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "planx",
|
|
3
|
-
"version": "20.53.
|
|
3
|
+
"version": "20.53.2",
|
|
4
4
|
"author": "Nozomu Miyamoto",
|
|
5
5
|
"description": "planx — Angular DI ベースの machina ターミナルマルチプレクサ / ピアセッション管理 CLI",
|
|
6
6
|
"type": "module",
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"ws": "8.18.3"
|
|
49
49
|
},
|
|
50
50
|
"optionalDependencies": {
|
|
51
|
-
"@
|
|
52
|
-
"@
|
|
53
|
-
"@
|
|
54
|
-
"@
|
|
55
|
-
"@
|
|
51
|
+
"@10p.io/tunnel-darwin-arm64": "20.53.2",
|
|
52
|
+
"@10p.io/tunnel-darwin-x64": "20.53.2",
|
|
53
|
+
"@10p.io/tunnel-linux-x64-gnu": "20.53.2",
|
|
54
|
+
"@10p.io/tunnel-linux-arm64-gnu": "20.53.2",
|
|
55
|
+
"@10p.io/tunnel-linux-x64-musl": "20.53.2"
|
|
56
56
|
},
|
|
57
57
|
"publishConfig": {
|
|
58
58
|
"access": "public"
|
package/planx-networkd.main.mjs
CHANGED
|
@@ -49,7 +49,7 @@ Domains=~${j}
|
|
|
49
49
|
</plist>
|
|
50
50
|
`,ue=`[Unit]
|
|
51
51
|
Description=planx ROOT network daemon (TUN + smoltcp via NAPI, exposed over unix-socket HTTP)
|
|
52
|
-
Documentation=https://github.com/nontangent/x_x_machina/tree/develop/packages/@
|
|
52
|
+
Documentation=https://github.com/nontangent/x_x_machina/tree/develop/packages/@10p.io/network
|
|
53
53
|
After=network.target
|
|
54
54
|
|
|
55
55
|
[Service]
|
|
@@ -72,7 +72,7 @@ StandardError=append:/var/log/planx-networkd.err.log
|
|
|
72
72
|
|
|
73
73
|
[Install]
|
|
74
74
|
WantedBy=multi-user.target
|
|
75
|
-
`});import{writeFileSync as Pr,mkdirSync as Rr,unlinkSync as Nr}from"node:fs";import{execFileSync as Lr}from"node:child_process";function Be(e){if(e.getuid&&e.getuid()!==0)throw new Error("must run as root (try: sudo planx network install)")}var Ir,x,He=B(()=>{Ir=typeof process.getuid=="function"?process.getuid.bind(process):void 0,x={writeFile:(e,t)=>Pr(e,t),mkdir:e=>Rr(e,{recursive:!0}),exec:(e,t)=>Lr(e,t,{stdio:"inherit"}),log:e=>console.log(e),platform:process.platform,getuid:Ir,rm:e=>{try{Nr(e)}catch{}}}});import{dirname as K}from"node:path";function z(e,t=x){t.mkdir(K(C)),t.writeFile(C,se(e.nodePath,e.bundlePath)),t.exec("chmod",["755",C]),t.log(`[planx-networkd install] installed launcher: ${C} -> ${e.bundlePath}`)}function de(e=x){e.mkdir(K(A)),e.writeFile(A,le);try{e.exec("launchctl",["bootout",`system/${$e}`])}catch{}e.exec("launchctl",["bootstrap","system",A]),e.log(`[planx-networkd install] installed launchd unit: ${A}`)}function fe(e=x){e.mkdir(K(P)),e.writeFile(P,ue),e.exec("systemctl",["daemon-reload"]),e.exec("systemctl",["enable","--now","planx-networkd"]),e.log(`[planx-networkd install] installed systemd unit: ${P}`)}function pe(e=x){e.mkdir(K(R)),e.writeFile(R,ae),e.log(`[planx-networkd install] installed macOS resolver hook: ${R}`)}function he(e=x){e.mkdir(K(N)),e.writeFile(N,ce),e.exec("systemctl",["reload-or-restart","systemd-resolved"]),e.log(`[planx-networkd install] installed Linux resolved zone config: ${N}`)}function me(e=x){try{e.exec("launchctl",["bootout",`system/${$e}`])}catch{}e.rm?.(A),e.log(`[planx-networkd uninstall] removed launchd unit: ${A}`)}function ge(e=x){try{e.exec("systemctl",["disable","--now","planx-networkd"])}catch{}e.rm?.(P);try{e.exec("systemctl",["daemon-reload"])}catch{}e.log(`[planx-networkd uninstall] removed systemd unit: ${P}`)}function G(e=x){e.rm?.(C),e.log(`[planx-networkd uninstall] removed launcher: ${C}`)}function ye(e=x){e.rm?.(R),e.log(`[planx-networkd uninstall] removed macOS resolver hook: ${R}`)}function xe(e=x){e.rm?.(N);try{e.exec("systemctl",["reload-or-restart","systemd-resolved"])}catch{}e.log(`[planx-networkd uninstall] removed Linux resolved zone config: ${N}`)}var Me=B(()=>{Ue();He()});var kt={};Ot(kt,{LAUNCHD_DEST:()=>A,LAUNCHD_PLIST:()=>le,LINUX_RESOLVED_CONTENT:()=>ce,LINUX_RESOLVED_DEST:()=>N,MACOS_RESOLVER_CONTENT:()=>ae,MACOS_RESOLVER_DEST:()=>R,NETWORKD_BIN_DEST:()=>C,RESOLVER_DNS_PORT:()=>ie,SYSTEMD_DEST:()=>P,SYSTEMD_UNIT:()=>ue,buildNetworkdWrapper:()=>se,installLaunchd:()=>de,installLinuxResolved:()=>he,installMacosResolver:()=>pe,installNetworkdBin:()=>z,installSystemd:()=>fe,runInstall:()=>$r,runUninstall:()=>Ur,uninstallLaunchd:()=>me,uninstallLinuxResolved:()=>xe,uninstallMacosResolver:()=>ye,uninstallNetworkdBin:()=>G,uninstallSystemd:()=>ge});async function $r(e=x,t){if(Be(e),e.platform==="darwin"){t&&z(t,e),de(e),pe(e);return}if(e.platform==="linux"){t&&z(t,e),fe(e),he(e);return}if(e.platform==="win32"){e.log("[planx-networkd install] Windows: use NSSM or sc.exe to register `planx-networkd` as a service.");return}throw new Error(`unsupported platform: ${e.platform}`)}async function Ur(e=x){if(Be(e),e.platform==="darwin"){me(e),G(e),ye(e);return}if(e.platform==="linux"){ge(e),G(e),xe(e);return}if(e.platform==="win32"){e.log("[planx-networkd uninstall] Windows: remove the `planx-networkd` service via NSSM or sc.exe delete.");return}throw new Error(`unsupported platform: ${e.platform}`)}var vt=B(()=>{Ue();Me();He();Me()});import{createServer as Hr}from"node:http";import{existsSync as Mr,unlinkSync as Ct,chmodSync as Fr}from"node:fs";import{createRequire as Dt}from"node:module";import{readFileSync as Pt}from"node:fs";function Rt(){try{let e=Pt("/usr/bin/ldd","utf8");return/musl/i.test(e)?"musl":"gnu"}catch{return"gnu"}}function Nt(e=process.platform,t=process.arch){if(e==="darwin")return`@planx.machina.at/tunnel-darwin-${t}`;if(e==="linux")return`@planx.machina.at/tunnel-linux-${t}-${Rt()}`;if(e==="win32")return`@planx.machina.at/tunnel-win32-${t}-msvc`;throw new Error(`[planx-networkd] unsupported platform: ${e}/${t}`)}function Ve(e){let t=()=>{throw new Error(`[planx-networkd] native binding unavailable: ${e}`)};return{setupVnet:t,addSelfAddress:t,addPeerAddress:t,removePeerAddress:t,injectTcpData:t,injectTcpClose:t,injectUdpSend:t,setExitCapture:t,injectUdpDatagram:t,onEvent:t,offEvent:t}}function Lt(){let e=Nt();try{let r=Dt(import.meta.url)(e);return!r||typeof r.setupVnet!="function"?Ve(`subpackage ${e} loaded but missing exports`):r}catch(t){return Ve(`${e} not installed (${t.message})`)}}var Se=null;function b(){return Se||(Se=Lt()),Se}var Wr=new Proxy({},{get(e,t){return b()[t]}});var It=new Date(Date.now()-process.uptime()*1e3).toISOString();function $t(){let e=b();if(typeof e.version!="function")return"unknown";try{return e.version()}catch{return"unavailable"}}function je(){return{version:"20.53.1",nativeVersion:$t(),uptime:Math.floor(process.uptime()),pid:process.pid,platform:process.platform,arch:process.arch,nodeVersion:process.version,startedAt:It}}var H=null;function U(){return H}function be(e,t){if(e.enabled&&!e.socksPort)throw new Error("exit capture \u3092 on \u306B\u3059\u308B\u306B\u306F socksPort (front door \u306E port) \u304C\u8981\u308B");if(!e.enabled&&e.socksPort&&H!==null&&e.socksPort!==H)return{bypass:[],failed:[`front door ${H} \u304C capture \u3057\u3066\u3044\u308B\u306E\u3067 ${e.socksPort} \u304B\u3089\u306E off \u306F\u7121\u8996\u3057\u305F`]};let r=t.setExitCapture({enabled:e.enabled,bypass:e.enabled?e.bypass:[],ipv6:e.enabled&&e.ipv6===!0});return H=e.enabled?e.socksPort??null:null,r}var Ut={"/health":()=>je(),"/exit/capture/status":()=>({socksPort:U()})};function Y(e,t,r){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(r))}function Ke(e,t){let r=(e.url??"/").split("?")[0],n=Ut[r];if(!n)return Y(t,404,{error:`not found: ${r}`});if(e.method!=="GET")return Y(t,405,{error:`method not allowed: ${e.method}`});try{Y(t,200,n())}catch(s){Y(t,500,{error:s instanceof Error?s.message:String(s)})}}var Bt="/var/run/planx-networkd.sock",Ht="\\\\.\\pipe\\planx-networkd";function ze(e=process.platform){return e==="win32"?Ht:Bt}import*as ct from"node:net";function L(e){let t=e.split(":");if(t.length!==8||t.some(r=>!/^[0-9a-fA-F]{1,4}$/.test(r)))throw new Error(`[planx-networkd] invalid hip string (expected 8 full groups): "${e}"`);return t.map(r=>r.toLowerCase().padStart(4,"0")).join(":")}function we(e){let t=new Uint8Array(16);return L(e).split(":").forEach((r,n)=>{let s=parseInt(r,16);t[n*2]=s>>8,t[n*2+1]=s&255}),t}function Ge(e){if(e.length!==16)throw new Error(`[planx-networkd] invalid hip bytes (expected 16, got ${e.length})`);let t=[];for(let r=0;r<16;r+=2)t.push(((e[r]<<8|e[r+1])>>>0).toString(16).padStart(4,"0"));return t.join(":")}import{Buffer as rt}from"node:buffer";var Te,Xe=!!globalThis.__webrtcProxyDebug||typeof process<"u"&&!!(!((Te=process.env)===null||Te===void 0)&&Te.PLANX_PROXY_DEBUG);var M;(function(e){e[e.Success=0]="Success",e[e.GeneralFailure=1]="GeneralFailure",e[e.ConnectionNotAllowed=2]="ConnectionNotAllowed",e[e.NetworkUnreachable=3]="NetworkUnreachable",e[e.HostUnreachable=4]="HostUnreachable",e[e.ConnectionRefused=5]="ConnectionRefused",e[e.TtlExpired=6]="TtlExpired",e[e.CommandNotSupported=7]="CommandNotSupported",e[e.AddressTypeNotSupported=8]="AddressTypeNotSupported"})(M||(M={}));var k=1,I=3,v=4;var Xt={[k]:4,[v]:16},$=class{constructor(){this.buf=Buffer.alloc(0),this.methodDone=!1,this.replyDone=!1}push(t){this.buf=this.buf.length===0?t:Buffer.concat([this.buf,t])}takeMethodReply(){if(this.methodDone||this.buf.length<2)return null;if(this.buf[0]!==5)throw new Error(`[socks] method reply unsupported version: ${this.buf[0]}`);let t=this.buf[1];return this.buf=this.buf.subarray(2),this.methodDone=!0,{method:t}}takeConnectReply(){if(!this.methodDone||this.replyDone||this.buf.length<4)return null;if(this.buf[0]!==5)throw new Error(`[socks] connect reply unsupported version: ${this.buf[0]}`);let t=this.buf[3],r=t===I?this.buf.length<5?null:this.buf[4]+1:Xt[t];if(r===void 0)throw new Error(`[socks] connect reply unsupported ATYP: ${t}`);if(r===null)return null;let n=4+r+2;if(this.buf.length<n)return null;let s=this.buf[1],u=this.buf[n-2]<<8|this.buf[n-1];return this.buf=this.buf.subarray(n),this.replyDone=!0,{reply:s,atyp:t,bndPort:u}}drainRest(){let t=this.buf;return this.buf=Buffer.alloc(0),t}};var D=e=>new Error(`socks address: ${e}`);function F(e,t){if(!Number.isInteger(t)||t<0||t>65535)throw D(`port out of range: ${t}`);let r=[t>>8,t&255];if(e.kind==="ipv4"){if(e.addr.length!==4)throw D("ipv4 must be 4 bytes");return Uint8Array.from([k,...e.addr,...r])}if(e.kind==="ipv6"){if(e.addr.length!==16)throw D("ipv6 must be 16 bytes");return Uint8Array.from([v,...e.addr,...r])}let n=new TextEncoder().encode(e.name);if(n.length===0||n.length>255)throw D(`domain length ${n.length} is not in 1..255`);return Uint8Array.from([I,n.length,...n,...r])}function qt(e){if(e.length===0)throw D("empty");let t=e[0];if(t===k)return{address:{kind:"ipv4",addr:e.slice(1,5)},end:5};if(t===v)return{address:{kind:"ipv6",addr:e.slice(1,17)},end:17};if(t===I){if(e.length<2)throw D("domain length missing");let r=2+e[1];return{address:{kind:"domain",name:new TextDecoder().decode(e.slice(2,r))},end:r}}throw D(`unknown atyp 0x${t.toString(16)}`)}function ke(e){let{address:t,end:r}=qt(e);if(e.length<r+2)throw D(`truncated (${e.length} < ${r+2})`);return{address:t,port:e[r]<<8|e[r+1],length:r+2}}function ve(e){return Buffer.from([5,1,0,...e])}var Ce=e=>new Error(`socks udp: ${e}`),Jt=Uint8Array.of(k,0,0,0,0,0,0);function Ae(e,t){let r=new Uint8Array(3+e.length+t.length);return r.set(e,3),r.set(t,3+e.length),r}function Oe(e){if(e.length<3)throw Ce(`too short (${e.length})`);if(e[0]!==0||e[1]!==0)throw Ce("reserved bytes must be 0");let t;try{t=ke(e.subarray(3))}catch(r){throw Ce(r instanceof Error?r.message:String(r))}return{frag:e[2],target:t,data:e.subarray(3+t.length)}}function De(e=Jt){return Buffer.from([5,3,0,...e])}function V(){return Buffer.from([5,1,0])}function Pe(e,t){if(e.length!==16)throw new Error(`[socks] connect request addr must be 16 bytes, got ${e.length}`);let r=Buffer.alloc(22);return r.set([5,1,0,v],0),r.set(e,4),r.writeUInt16BE(t&65535,20),r}var q=new TextEncoder,Re=new TextDecoder;var as=q.encode(`0\r
|
|
75
|
+
`});import{writeFileSync as Pr,mkdirSync as Rr,unlinkSync as Nr}from"node:fs";import{execFileSync as Lr}from"node:child_process";function Be(e){if(e.getuid&&e.getuid()!==0)throw new Error("must run as root (try: sudo planx network install)")}var Ir,x,He=B(()=>{Ir=typeof process.getuid=="function"?process.getuid.bind(process):void 0,x={writeFile:(e,t)=>Pr(e,t),mkdir:e=>Rr(e,{recursive:!0}),exec:(e,t)=>Lr(e,t,{stdio:"inherit"}),log:e=>console.log(e),platform:process.platform,getuid:Ir,rm:e=>{try{Nr(e)}catch{}}}});import{dirname as K}from"node:path";function z(e,t=x){t.mkdir(K(C)),t.writeFile(C,se(e.nodePath,e.bundlePath)),t.exec("chmod",["755",C]),t.log(`[planx-networkd install] installed launcher: ${C} -> ${e.bundlePath}`)}function de(e=x){e.mkdir(K(A)),e.writeFile(A,le);try{e.exec("launchctl",["bootout",`system/${$e}`])}catch{}e.exec("launchctl",["bootstrap","system",A]),e.log(`[planx-networkd install] installed launchd unit: ${A}`)}function fe(e=x){e.mkdir(K(P)),e.writeFile(P,ue),e.exec("systemctl",["daemon-reload"]),e.exec("systemctl",["enable","--now","planx-networkd"]),e.log(`[planx-networkd install] installed systemd unit: ${P}`)}function pe(e=x){e.mkdir(K(R)),e.writeFile(R,ae),e.log(`[planx-networkd install] installed macOS resolver hook: ${R}`)}function he(e=x){e.mkdir(K(N)),e.writeFile(N,ce),e.exec("systemctl",["reload-or-restart","systemd-resolved"]),e.log(`[planx-networkd install] installed Linux resolved zone config: ${N}`)}function me(e=x){try{e.exec("launchctl",["bootout",`system/${$e}`])}catch{}e.rm?.(A),e.log(`[planx-networkd uninstall] removed launchd unit: ${A}`)}function ge(e=x){try{e.exec("systemctl",["disable","--now","planx-networkd"])}catch{}e.rm?.(P);try{e.exec("systemctl",["daemon-reload"])}catch{}e.log(`[planx-networkd uninstall] removed systemd unit: ${P}`)}function G(e=x){e.rm?.(C),e.log(`[planx-networkd uninstall] removed launcher: ${C}`)}function ye(e=x){e.rm?.(R),e.log(`[planx-networkd uninstall] removed macOS resolver hook: ${R}`)}function xe(e=x){e.rm?.(N);try{e.exec("systemctl",["reload-or-restart","systemd-resolved"])}catch{}e.log(`[planx-networkd uninstall] removed Linux resolved zone config: ${N}`)}var Me=B(()=>{Ue();He()});var kt={};Ot(kt,{LAUNCHD_DEST:()=>A,LAUNCHD_PLIST:()=>le,LINUX_RESOLVED_CONTENT:()=>ce,LINUX_RESOLVED_DEST:()=>N,MACOS_RESOLVER_CONTENT:()=>ae,MACOS_RESOLVER_DEST:()=>R,NETWORKD_BIN_DEST:()=>C,RESOLVER_DNS_PORT:()=>ie,SYSTEMD_DEST:()=>P,SYSTEMD_UNIT:()=>ue,buildNetworkdWrapper:()=>se,installLaunchd:()=>de,installLinuxResolved:()=>he,installMacosResolver:()=>pe,installNetworkdBin:()=>z,installSystemd:()=>fe,runInstall:()=>$r,runUninstall:()=>Ur,uninstallLaunchd:()=>me,uninstallLinuxResolved:()=>xe,uninstallMacosResolver:()=>ye,uninstallNetworkdBin:()=>G,uninstallSystemd:()=>ge});async function $r(e=x,t){if(Be(e),e.platform==="darwin"){t&&z(t,e),de(e),pe(e);return}if(e.platform==="linux"){t&&z(t,e),fe(e),he(e);return}if(e.platform==="win32"){e.log("[planx-networkd install] Windows: use NSSM or sc.exe to register `planx-networkd` as a service.");return}throw new Error(`unsupported platform: ${e.platform}`)}async function Ur(e=x){if(Be(e),e.platform==="darwin"){me(e),G(e),ye(e);return}if(e.platform==="linux"){ge(e),G(e),xe(e);return}if(e.platform==="win32"){e.log("[planx-networkd uninstall] Windows: remove the `planx-networkd` service via NSSM or sc.exe delete.");return}throw new Error(`unsupported platform: ${e.platform}`)}var vt=B(()=>{Ue();Me();He();Me()});import{createServer as Hr}from"node:http";import{existsSync as Mr,unlinkSync as Ct,chmodSync as Fr}from"node:fs";import{createRequire as Dt}from"node:module";import{readFileSync as Pt}from"node:fs";function Rt(){try{let e=Pt("/usr/bin/ldd","utf8");return/musl/i.test(e)?"musl":"gnu"}catch{return"gnu"}}function Nt(e=process.platform,t=process.arch){if(e==="darwin")return`@10p.io/tunnel-darwin-${t}`;if(e==="linux")return`@10p.io/tunnel-linux-${t}-${Rt()}`;if(e==="win32")return`@10p.io/tunnel-win32-${t}-msvc`;throw new Error(`[planx-networkd] unsupported platform: ${e}/${t}`)}function Ve(e){let t=()=>{throw new Error(`[planx-networkd] native binding unavailable: ${e}`)};return{setupVnet:t,addSelfAddress:t,addPeerAddress:t,removePeerAddress:t,injectTcpData:t,injectTcpClose:t,injectUdpSend:t,setExitCapture:t,injectUdpDatagram:t,onEvent:t,offEvent:t}}function Lt(){let e=Nt();try{let r=Dt(import.meta.url)(e);return!r||typeof r.setupVnet!="function"?Ve(`subpackage ${e} loaded but missing exports`):r}catch(t){return Ve(`${e} not installed (${t.message})`)}}var Se=null;function b(){return Se||(Se=Lt()),Se}var Wr=new Proxy({},{get(e,t){return b()[t]}});var It=new Date(Date.now()-process.uptime()*1e3).toISOString();function $t(){let e=b();if(typeof e.version!="function")return"unknown";try{return e.version()}catch{return"unavailable"}}function je(){return{version:"20.53.2",nativeVersion:$t(),uptime:Math.floor(process.uptime()),pid:process.pid,platform:process.platform,arch:process.arch,nodeVersion:process.version,startedAt:It}}var H=null;function U(){return H}function be(e,t){if(e.enabled&&!e.socksPort)throw new Error("exit capture \u3092 on \u306B\u3059\u308B\u306B\u306F socksPort (front door \u306E port) \u304C\u8981\u308B");if(!e.enabled&&e.socksPort&&H!==null&&e.socksPort!==H)return{bypass:[],failed:[`front door ${H} \u304C capture \u3057\u3066\u3044\u308B\u306E\u3067 ${e.socksPort} \u304B\u3089\u306E off \u306F\u7121\u8996\u3057\u305F`]};let r=t.setExitCapture({enabled:e.enabled,bypass:e.enabled?e.bypass:[],ipv6:e.enabled&&e.ipv6===!0});return H=e.enabled?e.socksPort??null:null,r}var Ut={"/health":()=>je(),"/exit/capture/status":()=>({socksPort:U()})};function Y(e,t,r){e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(r))}function Ke(e,t){let r=(e.url??"/").split("?")[0],n=Ut[r];if(!n)return Y(t,404,{error:`not found: ${r}`});if(e.method!=="GET")return Y(t,405,{error:`method not allowed: ${e.method}`});try{Y(t,200,n())}catch(s){Y(t,500,{error:s instanceof Error?s.message:String(s)})}}var Bt="/var/run/planx-networkd.sock",Ht="\\\\.\\pipe\\planx-networkd";function ze(e=process.platform){return e==="win32"?Ht:Bt}import*as ct from"node:net";function L(e){let t=e.split(":");if(t.length!==8||t.some(r=>!/^[0-9a-fA-F]{1,4}$/.test(r)))throw new Error(`[planx-networkd] invalid hip string (expected 8 full groups): "${e}"`);return t.map(r=>r.toLowerCase().padStart(4,"0")).join(":")}function we(e){let t=new Uint8Array(16);return L(e).split(":").forEach((r,n)=>{let s=parseInt(r,16);t[n*2]=s>>8,t[n*2+1]=s&255}),t}function Ge(e){if(e.length!==16)throw new Error(`[planx-networkd] invalid hip bytes (expected 16, got ${e.length})`);let t=[];for(let r=0;r<16;r+=2)t.push(((e[r]<<8|e[r+1])>>>0).toString(16).padStart(4,"0"));return t.join(":")}import{Buffer as rt}from"node:buffer";var Te,Xe=!!globalThis.__webrtcProxyDebug||typeof process<"u"&&!!(!((Te=process.env)===null||Te===void 0)&&Te.PLANX_PROXY_DEBUG);var M;(function(e){e[e.Success=0]="Success",e[e.GeneralFailure=1]="GeneralFailure",e[e.ConnectionNotAllowed=2]="ConnectionNotAllowed",e[e.NetworkUnreachable=3]="NetworkUnreachable",e[e.HostUnreachable=4]="HostUnreachable",e[e.ConnectionRefused=5]="ConnectionRefused",e[e.TtlExpired=6]="TtlExpired",e[e.CommandNotSupported=7]="CommandNotSupported",e[e.AddressTypeNotSupported=8]="AddressTypeNotSupported"})(M||(M={}));var k=1,I=3,v=4;var Xt={[k]:4,[v]:16},$=class{constructor(){this.buf=Buffer.alloc(0),this.methodDone=!1,this.replyDone=!1}push(t){this.buf=this.buf.length===0?t:Buffer.concat([this.buf,t])}takeMethodReply(){if(this.methodDone||this.buf.length<2)return null;if(this.buf[0]!==5)throw new Error(`[socks] method reply unsupported version: ${this.buf[0]}`);let t=this.buf[1];return this.buf=this.buf.subarray(2),this.methodDone=!0,{method:t}}takeConnectReply(){if(!this.methodDone||this.replyDone||this.buf.length<4)return null;if(this.buf[0]!==5)throw new Error(`[socks] connect reply unsupported version: ${this.buf[0]}`);let t=this.buf[3],r=t===I?this.buf.length<5?null:this.buf[4]+1:Xt[t];if(r===void 0)throw new Error(`[socks] connect reply unsupported ATYP: ${t}`);if(r===null)return null;let n=4+r+2;if(this.buf.length<n)return null;let s=this.buf[1],u=this.buf[n-2]<<8|this.buf[n-1];return this.buf=this.buf.subarray(n),this.replyDone=!0,{reply:s,atyp:t,bndPort:u}}drainRest(){let t=this.buf;return this.buf=Buffer.alloc(0),t}};var D=e=>new Error(`socks address: ${e}`);function F(e,t){if(!Number.isInteger(t)||t<0||t>65535)throw D(`port out of range: ${t}`);let r=[t>>8,t&255];if(e.kind==="ipv4"){if(e.addr.length!==4)throw D("ipv4 must be 4 bytes");return Uint8Array.from([k,...e.addr,...r])}if(e.kind==="ipv6"){if(e.addr.length!==16)throw D("ipv6 must be 16 bytes");return Uint8Array.from([v,...e.addr,...r])}let n=new TextEncoder().encode(e.name);if(n.length===0||n.length>255)throw D(`domain length ${n.length} is not in 1..255`);return Uint8Array.from([I,n.length,...n,...r])}function qt(e){if(e.length===0)throw D("empty");let t=e[0];if(t===k)return{address:{kind:"ipv4",addr:e.slice(1,5)},end:5};if(t===v)return{address:{kind:"ipv6",addr:e.slice(1,17)},end:17};if(t===I){if(e.length<2)throw D("domain length missing");let r=2+e[1];return{address:{kind:"domain",name:new TextDecoder().decode(e.slice(2,r))},end:r}}throw D(`unknown atyp 0x${t.toString(16)}`)}function ke(e){let{address:t,end:r}=qt(e);if(e.length<r+2)throw D(`truncated (${e.length} < ${r+2})`);return{address:t,port:e[r]<<8|e[r+1],length:r+2}}function ve(e){return Buffer.from([5,1,0,...e])}var Ce=e=>new Error(`socks udp: ${e}`),Jt=Uint8Array.of(k,0,0,0,0,0,0);function Ae(e,t){let r=new Uint8Array(3+e.length+t.length);return r.set(e,3),r.set(t,3+e.length),r}function Oe(e){if(e.length<3)throw Ce(`too short (${e.length})`);if(e[0]!==0||e[1]!==0)throw Ce("reserved bytes must be 0");let t;try{t=ke(e.subarray(3))}catch(r){throw Ce(r instanceof Error?r.message:String(r))}return{frag:e[2],target:t,data:e.subarray(3+t.length)}}function De(e=Jt){return Buffer.from([5,3,0,...e])}function V(){return Buffer.from([5,1,0])}function Pe(e,t){if(e.length!==16)throw new Error(`[socks] connect request addr must be 16 bytes, got ${e.length}`);let r=Buffer.alloc(22);return r.set([5,1,0,v],0),r.set(e,4),r.writeUInt16BE(t&65535,20),r}var q=new TextEncoder,Re=new TextDecoder;var as=q.encode(`0\r
|
|
76
76
|
\r
|
|
77
77
|
`);var ms=Buffer.from(`\r
|
|
78
78
|
\r
|
package/presentation.main.mjs
CHANGED