planx 20.86.1 → 20.88.0

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/blob.main.mjs CHANGED
@@ -1,4 +1,4 @@
1
- globalThis.__PLANX_SERVICE_VERSION__="20.86.1";
1
+ globalThis.__PLANX_SERVICE_VERSION__="20.88.0";
2
2
  import { createRequire } from 'module';
3
3
  const require = createRequire(import.meta.url);
4
4
 
@@ -44,7 +44,7 @@ SELECT hash FROM object
44
44
  WHERE hash NOT IN (SELECT h FROM reach) AND created_at < ?`,Is=`
45
45
  SELECT name, hash, accessed_at FROM alias ORDER BY accessed_at ASC LIMIT ?`,ks=`
46
46
  SELECT name, hash, accessed_at FROM alias WHERE accessed_at < ? ORDER BY accessed_at ASC`;var qt=class{constructor(e){this.db=e}link(e,r){this.run("INSERT OR IGNORE INTO edge (parent, child) VALUES (?, ?)",[e,r])}childrenOf(e){return je(this.db,"SELECT child FROM edge WHERE parent = ?",[e])}dropEdgesOf(e){this.run("DELETE FROM edge WHERE parent = ? OR child = ?",[e,e])}pin(e,r="",n=0){this.run("INSERT OR REPLACE INTO pin (hash, reason, created) VALUES (?, ?, ?)",[e,r,n])}unpin(e){this.run("DELETE FROM pin WHERE hash = ?",[e])}setAlias(e,r,n=0){this.run("INSERT OR REPLACE INTO alias (name, hash, accessed_at) VALUES (?, ?, ?)",[e,r,n])}resolveAlias(e){let r=le(this.db,"SELECT hash FROM alias WHERE name = ?",[e]);return r==null?null:String(r)}touchAlias(e,r){this.run("UPDATE alias SET accessed_at = ? WHERE name = ?",[r,e])}dropAlias(e){this.run("DELETE FROM alias WHERE name = ?",[e])}oldestAliases(e){return this.selectAliasRows(Is,[e])}expiredAliases(e){return this.selectAliasRows(ks,[e])}aliasCount(){return Number(le(this.db,"SELECT COUNT(*) FROM alias")??0)}selectAliasRows(e,r){return this.db.prepare(e).all(...r).map(n=>({name:String(n.name),hash:String(n.hash),accessedAt:Number(n.accessed_at)}))}run(e,r){this.db.prepare(e).run(...r)}};var Ru="ledger.db",Ns="INSERT INTO object (hash, size, accessed_at, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO UPDATE SET size = excluded.size, accessed_at = excluded.accessed_at",Su=256,jt=class t extends qt{constructor(r){super(ws(vu(r,Ru)));this.dir=r;this.batchDepth=0;this.pending=new Map;this.seq=Number(le(this.db,"SELECT COALESCE(MAX(accessed_at), 0) FROM object")??0)}static async create(r){return new t(r)}note(r,n,o=0){this.pending.delete(r),this.seq+=1,this.run(Ns,[r,n,this.seq,o])}markAccessed(r,n){this.pending.set(r,n),this.pending.size>=Su&&this.flush()}flush(){if(this.pending.size===0)return;let r=[...this.pending];this.pending.clear();let n=this.batchDepth===0;n&&this.db.exec("BEGIN");try{for(let[o,s]of r)this.seq+=1,this.run(Ns,[o,s,this.seq,0]);n&&this.db.exec("COMMIT")}catch(o){throw n&&this.db.exec("ROLLBACK"),o}}async batch(r){this.batchDepth===0&&this.db.exec("BEGIN"),this.batchDepth+=1;try{let n=await r();return this.batchDepth-=1,this.batchDepth===0&&this.db.exec("COMMIT"),n}catch(n){throw this.batchDepth-=1,this.batchDepth===0&&this.db.exec("ROLLBACK"),n}}inTransaction(){return this.batchDepth>0}reachable(){return this.flush(),new Set(je(this.db,Ps))}oldestEvictable(r){this.flush();let n=le(this.db,_s,[r]);return n==null?null:String(n)}purgeNonContentAddressed(){return xs(this.db)}collectable(r){return this.flush(),je(this.db,Cs,[r])}forget(r){this.run("DELETE FROM object WHERE hash = ?",[r])}has(r){return this.flush(),le(this.db,"SELECT 1 FROM object WHERE hash = ?",[r])!==void 0}sizeOf(r){return this.flush(),Number(le(this.db,"SELECT size FROM object WHERE hash = ?",[r])??0)}totalBytes(){return this.flush(),Number(le(this.db,"SELECT COALESCE(SUM(size), 0) FROM object")??0)}size(){return this.flush(),Number(le(this.db,"SELECT COUNT(*) FROM object")??0)}async rebuildFromDisk(){await Os(this.db,this.dir,()=>this.seq+=1)}close(){try{this.flush()}catch{}try{this.db.close()}catch{}}};import{rm as Us}from"node:fs/promises";import{join as Ms}from"node:path";async function Ds(t,e){let r=new Set(t.purgeNonContentAddressed());for(let n of await Ls(e))r.add(n),await Us(Ms(e,n),{force:!0});for(let n of r)n.includes("/")||await Us(Ms(e,n.slice(0,2),n),{force:!0});r.size>0&&console.error(`[planx-blob] purged ${r.size} legacy (non content-addressed) objects`)}import{readdir as Au,rm as Bu,stat as Tu}from"node:fs/promises";import{join as Lu}from"node:path";var Hs=3600*1e3;async function $s(t,e){let r;try{r=await Au(t,{recursive:!0})}catch{return[]}let n=Date.now()-e,o=[];for(let s of r){if(!s.endsWith(".wip"))continue;let i=Lu(t,s);try{let a=await Tu(i);if(!a.isFile()||a.mtimeMs>=n)continue;await Bu(i,{force:!0}),o.push(i)}catch{continue}}return o}var Ft=class{constructor(e){this.options=e;this.ledger=null;this.ready=null;this.closed=!1}async ensureReady(){if(this.closed)throw new Error("blob store is closed");let e=this.ready??=this.openLedger();try{return await e}catch(r){throw this.ready===e&&(this.ready=null),r}}async openLedger(){let e=await jt.create(this.options.dir);this.ledger=e,await $s(this.options.dir,this.options.wipGraceMs??Hs);let r=e.size()===0;return r&&await e.rebuildFromDisk(),await Ds(e,this.options.dir),r||await Ht(e,n=>this.pathOf(n),this.options.gcGraceMs),e}async totalBytes(){return(await this.ensureReady()).totalBytes()}close(){this.closed=!0;let e=this.ready;if(!e)return void this.ledger?.close();e.then(r=>r.close()).catch(()=>{})}pathOf(e){return Ou(this.options.dir,ls(e))}};var Gt=class extends Ft{async read(e){if(!xe(e))return null;let r=await this.ensureReady();try{let n=await Cu(this.pathOf(e));return r.markAccessed(e,n.length),n}catch{return null}}async has(e){if(!xe(e))return!1;let r=await this.ensureReady();try{let n=await qs(this.pathOf(e));return r.markAccessed(e,n.size),!0}catch{return r.forget(e),!1}}async write(e,r){if(!xe(e))throw new Error(`invalid blob key: ${e}`);let n=await this.ensureReady(),o=this.pathOf(e),s=await us(o);if(s&&(!Buffer.isBuffer(r)||s.size===r.length)){n.markAccessed(e,s.size),Buffer.isBuffer(r)||await r.cancel();return}s&&console.warn(`[planx-blob] size-divergent rewrite, replacing ${e} (${s.size} -> ${r.length})`),await _u(Uu(o),{recursive:!0});let i=`${o}.${crypto.randomUUID()}.wip`;Buffer.isBuffer(r)?await Nu(i,r):await Du(Mu.fromWeb(r),Pu(i)),await Iu(i,o),n.note(e,(await qs(o)).size,Date.now())}async discard(e){if(!xe(e))return;(await this.ensureReady()).forget(e),await ku(this.pathOf(e),{force:!0})}async batch(e){return(await this.ensureReady()).batch(e)}async setAlias(e,r,n=Date.now()){(await this.ensureReady()).setAlias(e,r,n)}async resolveAlias(e){return(await this.ensureReady()).resolveAlias(e)}async touchAlias(e,r){(await this.ensureReady()).touchAlias(e,r)}async dropAlias(e){(await this.ensureReady()).dropAlias(e)}async oldestAliases(e){return(await this.ensureReady()).oldestAliases(e)}async expiredAliases(e){return(await this.ensureReady()).expiredAliases(e)}async aliasCount(){return(await this.ensureReady()).aliasCount()}async reachable(){return(await this.ensureReady()).reachable()}async dropTree(e,r){return fs(await this.ensureReady(),n=>this.pathOf(n),e,r)}async treeSizeEstimate(e){return hs(await this.ensureReady(),e)}async pin(e,r=""){(await this.ensureReady()).pin(e,r,Date.now())}async unpin(e){(await this.ensureReady()).unpin(e)}async link(e,r){(await this.ensureReady()).link(e,r)}async childrenOf(e){return(await this.ensureReady()).childrenOf(e)}async gc(e=Xr){return Ht(await this.ensureReady(),r=>this.pathOf(r),e)}};var rt=class{constructor(e={}){this.options=e;this.localHit=0;this.relayHit=0;this.miss=0;this.put=0;this.replicaFailures=0;this.lastReplicaFailure=null;this.retainRuns=0;this.expiredAliases=0;this.evictedAliases=0;this.evictedBytes=0;this.samples=[]}recordLocalHit(e){this.localHit+=1,this.addSample(e)}recordRelayHit(e){this.relayHit+=1,this.addSample(e)}recordMiss(e){this.miss+=1,this.addSample(e)}recordPut(e){this.put+=1,this.addSample(e)}recordReplicaFailure(e,r){this.lastReplicaFailure={peer:e,reason:r},this.replicaFailures+=1}recordRetain(e){this.retainRuns+=1,this.expiredAliases+=e.expiredAliases,this.evictedAliases+=e.evictedAliases,this.evictedBytes+=e.freedBytes}sampleCount(){return this.samples.length}snapshot(){let e=this.localHit+this.relayHit+this.miss,r=[...this.samples].sort((n,o)=>n-o);return{retainRuns:this.retainRuns,expiredAliases:this.expiredAliases,evictedAliases:this.evictedAliases,evictedBytes:this.evictedBytes,localHit:this.localHit,relayHit:this.relayHit,miss:this.miss,put:this.put,hitRate:e===0?0:(this.localHit+this.relayHit)/e,replicaFailures:this.replicaFailures,lastReplicaFailure:this.lastReplicaFailure,getLatencyMs:{p50:js(r,.5),p99:js(r,.99)}}}addSample(e){let r=this.options.maxSamples??1024;this.samples.push(e),this.samples.length>r&&this.samples.shift()}};function js(t,e){if(t.length===0)return 0;let r=Math.min(t.length-1,Math.ceil(e*t.length)-1);return t[Math.max(0,r)]}var Yr={maxBytes:10737418240,highWaterRatio:.9,lowWaterRatio:.8,aliasTtlMs:12096e5,retainIntervalMs:6e5,wipGraceMs:36e5,evictBatch:64};function xt(t){return{high:Math.floor(t.maxBytes*t.highWaterRatio),low:Math.floor(t.maxBytes*t.lowWaterRatio)}}var Hu=1024*1024,Wt=class{constructor(e,r,n,o={}){this.store=e;this.policy=r;this.metrics=n;this.options=o;this.inFlight=null;this.lastRetainAt=null;this.lastRetain=null}retain(){return this.inFlight??=this.run().finally(()=>{this.inFlight=null}),this.inFlight}async afterPut(){let{high:e}=xt(this.policy);return await this.store.totalBytes()<=e?null:this.retain()}async status(){return{status:this.inFlight?"retaining":"ok",totalBytes:await this.store.totalBytes(),maxBytes:this.policy.maxBytes,highWaterBytes:xt(this.policy).high,aliases:await this.store.aliasCount(),lastRetainAt:this.lastRetainAt,lastRetain:this.lastRetain}}async run(){let e=this.now(),r=await this.expire(e),{evicted:n,freed:o}=await this.evictToLowWater(),s=await this.store.totalBytes()>xt(this.policy).high,i=r.count+n>0||s?(await this.store.gc()).length:0,a={expiredAliases:r.count,evictedAliases:n,freedBytes:r.freed+o,collected:i,tookMs:this.now()-e};return this.lastRetainAt=this.now(),this.lastRetain=a,this.metrics.recordRetain(a),this.report(a),a}async expire(e){let r=await this.store.expiredAliases(e-this.policy.aliasTtlMs);for(let s of r)await this.store.dropAlias(s.name);if(r.length===0)return{count:0,freed:0};let n=await this.store.reachable(),o=0;for(let s of r)o+=await this.store.dropTree(s.hash,n);return{count:r.length,freed:o}}async evictToLowWater(){let{high:e,low:r}=xt(this.policy),n=0,o=0,s=await this.store.totalBytes();for(;s>e;){let i=await this.selectVictims(s,r);if(i.length===0)break;for(let c of i)await this.store.dropAlias(c.name);let a=await this.store.reachable();for(let c of i)o+=await this.store.dropTree(c.hash,a),n+=1;s=await this.store.totalBytes()}return{evicted:n,freed:o}}async selectVictims(e,r){let n=await this.store.oldestAliases(this.policy.evictBatch),o=[],s=e;for(let i of n)if(o.push(i),s-=await this.store.treeSizeEstimate(i.hash),s<=r)break;return o}report(e){if(e.expiredAliases+e.evictedAliases===0&&e.tookMs<=1e3)return;let n=`${(e.freedBytes/Hu).toFixed(1)} MB freed`;this.log(`[planx-blob] retain: expired=${e.expiredAliases} evicted=${e.evictedAliases} aliases, ${n}, collected=${e.collected}, took=${e.tookMs} ms`)}log(e){(this.options.log??console.error)(e)}now(){return(this.options.now??(()=>Date.now()))()}};function Fs(t,e){let r=setInterval(()=>{t.retain().catch(n=>{t.log(`[planx-blob] retain failed: ${String(n)}`)})},e);return r.unref?.(),()=>clearInterval(r)}function Gs(t){let e=[];for(let r of t){let n=Buffer.from(r.hash,"utf-8"),o=Buffer.alloc(2+n.length+4);o.writeUInt16BE(n.length,0),n.copy(o,2),o.writeUInt32BE(r.data.length,2+n.length),e.push(o,r.data)}return Buffer.concat(e)}function Ws(t){let e=[],r=0;for(;r<t.length;){if(r+2>t.length)return null;let n=t.readUInt16BE(r),o=r+2+n+4;if(o>t.length)return null;let s=t.subarray(r+2,r+2+n).toString("utf-8"),i=t.readUInt32BE(r+2+n);if(o+i>t.length)return null;e.push({hash:s,data:Buffer.from(t.subarray(o,o+i))}),r=o+i}return e}var $u=new Set([404,405]);async function zs(t,e,r){try{let n=await fetch(`${e.baseUrl}/blob/objects/batch`,{method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/octet-stream"},body:new Uint8Array(Gs(r)),signal:AbortSignal.timeout(t.timeoutMs??3e3)});return await n.body?.cancel().catch(()=>{}),n.ok?{ok:!0}:{ok:!1,unsupported:$u.has(n.status),reason:`status ${n.status}`}}catch(n){let o=n instanceof Error?n:new Error(String(n));return{ok:!1,unsupported:!1,reason:`error ${o.name}: ${o.message}`}}}var zt=class{constructor(e){this.options=e}async get(e,r,n={}){let o=await this.request(e,r,"GET",void 0,n);return o instanceof Error?null:!o.ok||!o.body?(await o.body?.cancel().catch(()=>{}),null):o.body}async head(e,r,n={}){let o=await this.request(e,r,"HEAD",void 0,n);return o instanceof Error?!1:(await o.body?.cancel().catch(()=>{}),o.ok)}async put(e,r,n,o={}){let s=await this.request(e,r,"PUT",n,o);return s instanceof Error?{ok:!1,reason:`error ${s.name}: ${s.message}`}:(await s.body?.cancel().catch(()=>{}),s.ok?{ok:!0}:{ok:!1,reason:`status ${s.status}`})}putBatch(e,r){return zs(this.options,e,r)}async have(e,r){try{let n=await fetch(`${e.baseUrl}/blob/have`,{method:"POST",headers:{authorization:`Bearer ${this.options.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.options.timeoutMs??3e3)});if(!n.ok)return null;let o=await n.json();return Array.isArray(o.missing)?o.missing:null}catch{return null}}async getAlias(e,r){let n=await this.aliasRequest(e,r,"GET");return n?.ok?(await n.text()).trim()||null:(await n?.body?.cancel(),null)}async putAlias(e,r,n){let o=await this.aliasRequest(e,r,"PUT",n);return await o?.body?.cancel(),o?.ok??!1}async aliasRequest(e,r,n,o){try{return await fetch(`${e.baseUrl}/blob/aliases/${encodeURIComponent(r)}`,{method:n,headers:{authorization:`Bearer ${this.options.token}`},body:o,signal:AbortSignal.timeout(this.options.timeoutMs??3e3)})}catch{return null}}async request(e,r,n,o,s={}){let i=AbortSignal.timeout(this.options.timeoutMs??3e3),a=s.signal?qu([i,s.signal]):i;try{return await fetch(`${e.baseUrl}/blob/objects/${r}?noRelay=1&raw=1`,{method:n,headers:{authorization:`Bearer ${this.options.token}`},body:o?new Uint8Array(o):void 0,signal:a})}catch(c){return c instanceof Error?c:new Error(String(c))}}};function qu(t){let e=AbortSignal.any;if(typeof e=="function")return e(t);let r=new AbortController;for(let n of t){if(n.aborted){r.abort(n.reason);break}n.addEventListener("abort",()=>r.abort(n.reason),{once:!0})}return r.signal}import{createWriteStream as Xs,createReadStream as Ku}from"node:fs";import{rm as Xu,stat as Zu}from"node:fs/promises";import{tmpdir as Yu}from"node:os";import{join as Ju}from"node:path";import{Readable as Zs}from"node:stream";import{pipeline as Ys}from"node:stream/promises";var Vs=ju();function ju(){let t=new Uint32Array(256),e=2654435769;for(let r=0;r<256;r+=1)e^=e<<13,e>>>=0,e^=e>>>17,e^=e<<5,e>>>=0,t[r]=e;return t}var Fu=16*1024,Gu=64*1024,Wu=256*1024;function Ks(t,e={}){let r=e.minSize??Fu,n=e.avgSize??Gu,o=e.maxSize??Wu,s=Vu(n),i=[],a=0;for(;a<t.length;){let c=zu(t,a,r,o,s);i.push(t.subarray(a,c)),a=c}return i}function zu(t,e,r,n,o){let s=Math.min(e+n,t.length);if(s-e<=r)return s;let i=0;for(let a=e+r;a<s;a+=1)if(i=(i<<1>>>0)+Vs[t[a]],i>>>=0,(i&o)===0)return a+1;return s}function Vu(t){return 2**Math.max(1,Math.round(Math.log2(Math.max(2,t))))-1>>>0}var Qu=8*1024*1024;async function Vt(t){let e=Ju(Yu(),`planx-blob-spool-${crypto.randomUUID()}`);Buffer.isBuffer(t)?await Ys(Zs.from(t),Xs(e)):await Ys(Zs.fromWeb(t),Xs(e));let r=await Zu(e);return{path:e,size:r.size,discard:()=>Xu(e,{force:!0})}}async function*Js(t){let e=Buffer.alloc(0);for await(let r of Ku(t,{highWaterMark:Qu})){let n=r;e=e.length===0?n:Buffer.concat([e,n]);let o=Ks(e);for(let s of o.slice(0,-1))yield s;e=o.length>0?Buffer.from(o[o.length-1]):Buffer.alloc(0)}e.length>0&&(yield e)}var ef=64,tf=256,rf=1024,Jr=`
47
- `,Qs=" ";function nf(t){let e=t.map(r=>`${r.hash}${Qs}${r.subtreeBytes}`).join(Jr);return Buffer.from(`v2${Jr}${e}`,"utf-8")}function Kt(t){let e=t.toString("utf-8").split(Jr);if(e[0]!=="v2")throw new Error(`unsupported manifest version: ${e[0]}`);return e.slice(1).filter(r=>r.length>0).map(r=>{let[n,o]=r.split(Qs);return{hash:n,subtreeBytes:Number(o)}})}async function ei(t,e={}){let r=[],n=t.map(s=>({hash:s.hash,subtreeBytes:s.size})),o=n.reduce((s,i)=>s+i.subtreeBytes,0);if(n.length===1)return{rootHash:n[0].hash,totalBytes:o,objects:r};for(;;){let s=of(n,e),i=[];for(let a of s){let c=nf(a),l=await bt(1,c);r.push({hash:l,type:1,payload:c}),i.push({hash:l,subtreeBytes:a.reduce((u,f)=>u+f.subtreeBytes,0)})}if(i.length===1)return{rootHash:i[0].hash,totalBytes:o,objects:r};n=i}}function of(t,e){let r=e.minEntries??ef,n=e.avgEntries??tf,o=e.maxEntries??rf;if(t.length<=o)return[t];let s=(1<<Math.round(Math.log2(Math.max(2,n))))-1,i=[],a=0;for(;a<t.length;){let c=Math.min(a+o,t.length);for(let l=a+r;l<c;l+=1)if((sf(t[l].hash)&s)===0){c=l+1;break}i.push(t.slice(a,c)),a=c}return i}function sf(t){return parseInt(t.slice(-8),16)>>>0}async function ti(t,e){return t.batch(async()=>{let r=[];for await(let o of Js(e)){let s=await bt(0,o);await t.write(s,o),r.push({hash:s,size:o.length})}let n=await ei(r);for(let o of n.objects){await t.write(o.hash,o.payload);for(let s of Kt(o.payload))await t.link(o.hash,s.hash)}return n.rootHash})}function af(t,e){return yt(t,1,e)}async function Fe(t,e){if(!await af(t,e))return null;try{return Kt(e)}catch{throw console.error(`[planx-blob] malformed manifest, rejecting ${t}`),new Error(`malformed manifest: ${t}`)}}async function ri(t,e){let r=await e(t);if(!r)return null;let n=await Fe(t,r);return n?n.reduce((o,s)=>o+s.subtreeBytes,0):r.length}async function*en(t,e){let r=await e(t);if(!r)throw new Error(`missing object: ${t}`);let n=await Fe(t,r);if(!n){yield r;return}for(let o of n)yield*en(o.hash,e)}async function ni(t,e,r){let n;try{n=await Fe(e,r)}catch{return}if(!n)return;let o=n;await t.batch(async()=>{for(let s of o)await t.link(e,s.hash)})}async function oi(t,e){let r=[t];for(;r.length>0;){let n=[];for(let s of r)await e.has(s)||n.push(s);if(n.length>0&&!await e.fetchMissing(n))return!1;let o=[];for(let s of r){let i=await e.read(s);if(!i)return!1;try{o.push(...(await Fe(s,i)??[]).map(a=>a.hash))}catch{return!1}}r=o}return!0}async function Ge(t,e){return(await Promise.all(t.map(async n=>({peer:n,score:await cf(n.id,e)})))).sort((n,o)=>n.score<o.score?1:n.score>o.score?-1:0).map(n=>n.peer)}async function cf(t,e){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${t}:${e}`));return Buffer.from(r).toString("hex")}function si(t,e){let r=new Map;for(let o of e.keys())r.set(o,[]);let n=[];for(let o of t){let s=[...e.entries()].filter(([,i])=>i.has(o));if(s.length===0){n.push(o);continue}s.sort(([i],[a])=>(r.get(i)?.length??0)-(r.get(a)?.length??0)),r.get(s[0][0])?.push(o)}return{queues:r,unclaimed:n}}var ii=8;async function ai(t,e){if(e.length===0)return!0;let r=await lf(t,e),{queues:n,unclaimed:o}=si(e,r),s={ownedBy:r,queues:n,started:new Set,done:new Set,tried:new Map,retry:[],busy:new Map,inFlight:0,wake:[]},i=Array.from({length:ii},()=>t.peers).flat();await Promise.all(i.map(a=>uf(t,s,a)));for(let a of[...o,...e.filter(c=>!s.done.has(c))])if(!s.done.has(a)){if(!await t.fallback(a))return!1;s.done.add(a)}return!0}async function lf(t,e){let r=new Map;return await Promise.all(t.peers.map(async n=>{let o=await t.have(n,e);if(o===null)return;let s=new Set(o);r.set(n.id,new Set(e.filter(i=>!s.has(i))))})),r}async function uf(t,e,r){for(;;){let n=hf(e,r.id);if(n===null){if(e.inFlight===0)return;await new Promise(o=>e.wake.push(o));continue}e.started.add(n),li(e,n).add(r.id),!e.done.has(n)&&await ff(t,e,r,n)}}async function ff(t,e,r,n){let o=!1;e.inFlight+=1,e.busy.set(r.id,(e.busy.get(r.id)??0)+1);try{o=await t.fetchFrom(r,n)}finally{e.inFlight-=1,e.busy.set(r.id,(e.busy.get(r.id)??1)-1),o?e.done.add(n):df(e,n)&&e.retry.push(n);for(let s of e.wake.splice(0))s()}}function hf(t,e){let r=t.queues.get(e)??[];for(;r.length>0;){let o=r.shift();if(!t.started.has(o))return o}let n=t.retry.findIndex(o=>!t.done.has(o)&&ci(t,o,e));if(n>=0)return t.retry.splice(n,1)[0];for(let[o,s]of t.queues){if(o===e||(t.busy.get(o)??0)<ii)continue;let i=s.findIndex(a=>!t.started.has(a)&&t.ownedBy.get(e)?.has(a));if(i>=0)return s.splice(i,1)[0]}return null}function ci(t,e,r){return(t.ownedBy.get(r)?.has(e)??!1)&&!li(t,e).has(r)}function df(t,e){return[...t.ownedBy.keys()].some(r=>ci(t,e,r))}function li(t,e){let r=t.tried.get(e);return r||t.tried.set(e,r=new Set),r}async function tn(t,e=()=>{}){return t.length===0?null:new Promise(r=>{let n=t.length,o=!1,s=()=>{n-=1,n===0&&!o&&(o=!0,r(null))};for(let i of t)i.then(a=>{if(a===null)return s();if(o)return e(a);o=!0,r(a)},s)})}async function ui(t,e,r){let{client:n,hash:o}=r,s=new Map,i=u=>{let f=new AbortController;return s.set(u.id,f),f.signal},a=u=>f=>f?{peer:u,stream:f}:null,c=[...t.slice(0,e).map(u=>n.get(u,o,{signal:i(u)}).then(a(u)).catch(()=>null)),...t.slice(e).map(u=>{let f=i(u);return n.head(u,o,{signal:f}).then(d=>d?n.get(u,o,{signal:f}):null).then(a(u)).catch(()=>null)})],l=await tn(c,u=>{u.stream.cancel().catch(()=>{})});for(let[u,f]of s)u!==l?.peer.id&&f.abort();return l?.stream??null}function fi(t,e){return async r=>{let n=await hi(t,r);return n||(e?(t.onRemote(),pi(t,r)):null)}}async function hi(t,e){let r=await t.store.read(e);return r?await t.accepts(e,r)?r:(console.warn(`[planx-blob] local chunk failed verification, discarding ${e}`),await t.store.discard(e),null):null}function di(t,e){return{has:r=>t.store.has(r),read:r=>hi(t,r),fetchMissing:async r=>e?(t.onRemote(),ai({peers:await t.livePeers(),have:(n,o)=>t.client.have(n,o),fetchFrom:(n,o)=>pf(t,n,o),fallback:async n=>await pi(t,n)!==null},r)):!1}}async function pi(t,e){let r=await Ge(await t.livePeers(),e),n=await ui(r,t.replication,{client:t.client,hash:e});return n?mi(t,e,n):null}async function pf(t,e,r){let n=await t.client.get(e,r);return n?await mi(t,r,n)!==null:!1}async function mi(t,e,r){let n;try{n=Buffer.from(await new Response(r).arrayBuffer())}catch{return null}return await t.accepts(e,n)?(await t.store.write(e,n),await ni(t.store,e,n),n):null}function gi(t=e=>console.error(e)){let e=new Set;return(r,n)=>{let o=`${r.id} ${n}`;e.has(o)||(e.size>=64&&e.clear(),e.add(o),t(`[planx-blob] replica put failed peer=${r.id} reason=${n}`))}}var mf=8*1024*1024;async function wi(t,e){let r=await t.livePeers(),n=new Map,o=new Set,s=[e];for(;s.length>0;){let i=s.pop();if(o.has(i))continue;o.add(i);let a=await t.store.read(i);if(a){for(let c of(await Ge(r,i)).slice(0,t.replication)){let l=n.get(c.id)??{peer:c,pending:[],bytes:0,legacy:!1,failed:!1};n.set(c.id,l),l.pending.push({hash:i,data:a}),l.bytes+=a.length,l.bytes>=mf&&await bi(t,l)}s.push(...await gf(i,a))}}await Promise.all([...n.values()].map(i=>bi(t,i)))}async function gf(t,e){try{return(await Fe(t,e)??[]).map(r=>r.hash).reverse()}catch{return[]}}async function bi(t,e){let r=e.pending;if(e.pending=[],e.bytes=0,!(r.length===0||e.failed)){if(!e.legacy){let n=await t.client.putBatch(e.peer,r);if(n.ok)return;if(!n.unsupported)return yi(t,e,n.reason);e.legacy=!0}for(let n of r){let o=await t.client.put(e.peer,n.hash,n.data).catch(s=>({ok:!1,reason:`error ${String(s)}`}));if(!o.ok)return yi(t,e,o.reason)}}}function yi(t,e,r){e.failed=!0,t.onFailure(e.peer,r)}function xi(t){return new ReadableStream({async pull(e){try{let r=await t.next();if(r.done)return e.close();e.enqueue(new Uint8Array(r.value))}catch(r){e.error(r)}},cancel:()=>{t.return(void 0)}})}async function Ei(t,e,r){let n=await Ge(await t.livePeers(),e);await Promise.all(n.slice(0,t.replication).map(o=>t.client.putAlias(o,e,r)))}async function vi(t,e){if(_e(e))return null;let r=await Ge(await t.livePeers(),e);return tn(r.map(async n=>{let o=await t.client.getAlias(n,e);return o&&_e(o)?o:null}))}var bf=2,Xt=class{constructor(e,r,n,o={}){this.store=e;this.peers=r;this.client=n;this.options=o;this.reportReplicaFailure=gi();this.metrics=o.metrics??new rt}async get(e,r){let n=this.now(),o=await this.rootOf(e,r.relay),s={value:!1},i={store:this.store,client:this.client,replication:this.replication(),livePeers:()=>this.peers.livePeers(),accepts:(l,u)=>this.accepts(l,u),onRemote:()=>{s.value=!0}},a=fi(i,r.relay),c;try{c=await ri(o,a)}catch{c=null}return c===null||!await this.store.batch(()=>oi(o,di(i,r.relay)))?(this.metrics.recordMiss(this.now()-n),null):(s.value?this.metrics.recordRelayHit(this.now()-n):this.metrics.recordLocalHit(this.now()-n),{size:c,stream:xi(en(o,a))})}async rootOf(e,r){let n=await this.store.resolveAlias(e);if(n)return await this.store.touchAlias(e,this.now()),n;if(!r)return e;let o=await vi(await this.aliasDeps(),e);return o?(await this.store.setAlias(e,o),o):e}async aliasDeps(){return{client:this.client,livePeers:()=>this.peers.livePeers(),replication:this.replication()}}now(){return(this.options.now??(()=>Date.now()))()}async accepts(e,r){return await yt(e,0,r)||await yt(e,1,r)?!0:(console.error(`[planx-blob] hash mismatch, rejecting ${e}`),!1)}async put(e){let r=this.now(),n=await Vt(e),o;try{o=await ti(this.store,n.path),wi(this.replicationDeps(),o).catch(()=>{})}finally{await n.discard()}return this.metrics.recordPut(this.now()-r),await this.options.retention?.afterPut(),o}async bind(e,r){await this.store.setAlias(e,r,this.now()),this.aliasDeps().then(n=>Ei(n,e,r)).catch(()=>{})}replicationDeps(){return{store:this.store,client:this.client,livePeers:()=>this.peers.livePeers(),replication:this.replication(),onFailure:(e,r)=>{this.metrics.recordReplicaFailure(e.id,r),this.reportReplicaFailure(e,r)}}}replication(){return this.options.replication??bf}};var Ri=Symbol();var Si=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData();var yf=1e4,Zt=t=>"headers"in t,Ti=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(Zt(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?wf(t,{all:r,dot:n}):{}};async function wf(t,e){if(!Zt(t)&&t.bodyCache.formData)return Ai(await t.bodyCache.formData,e);let r=Zt(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=Si(n,r.get("Content-Type")||"");Zt(t)||(t.bodyCache.formData=o);let s=await o;return s?Ai(s,e):{}}function Ai(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?xf(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Ef(r,o,s,n),delete r[o])}),r}var xf=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Ef=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",34);s.length>33&&Bi(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=yf&&Bi(),o[i]=Object.create(null)),o=o[i])})},Bi=()=>{throw new Error("Nesting limit exceeded")};var nn=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Li=t=>{let{groups:e,path:r}=vf(t),n=nn(r);return Rf(n,e)},vf=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},Rf=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},Yt={},Oi=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return Yt[n]||(r[2]?Yt[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Yt[n]=[t,r[1],!0]),Yt[n]}return null},Pi=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},Sf=t=>Pi(t,decodeURI),on=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return Sf(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var _i=t=>{let e=on(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ce=(t,e,...r)=>(r.length&&(e=Ce(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Jt=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},Qt=t=>t.indexOf("%")!==-1?Pi(t,Af):t,rn=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),Qt(t)),Ci=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let a=t.indexOf("?",8);if(a===-1)return;for(t.startsWith(e,a+1)||(a=t.indexOf(`&${e}`,a+1));a!==-1;){let c=t.charCodeAt(a+e.length+1);if(c===61){let l=a+e.length+2,u=t.indexOf("&",l);return rn(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=t.indexOf(`&${e}`,a+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let a=t.indexOf("&",i+1),c=t.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=t.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=rn(l)),i=a,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,a===-1?void 0:a),o&&(u=rn(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Ii=Ci,ki=(t,e)=>Ci(t,e,!0),Af=decodeURIComponent;var Ni=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&Qt(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=Qt(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Ii(this.url,t)}queries(t){return ki(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ti(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>{o==="json"&&(s=JSON.stringify(s));let i=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:i?{"Content-Type":i}:void 0})[t]()});return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("formData")}addValidatedData(t,e){(this.#t??={})[t]=e}valid(t){return this.#t?.[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ri](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ui={Stringify:1,BeforeStream:2,Stream:3},Bf=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var sn=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>sn(c,e,!1,n,o))).then(()=>o[0]));return r?Bf(await i,s):i};var Tf="text/plain; charset=UTF-8",an=(t,e)=>({"Content-Type":t,...e}),Et=(t,e)=>new Response(t,e),cn=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#f;#h;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#h=e.path,this.#f=e.matchResult)}get req(){return this.#e??=new Ni(this.#t,this.#h,this.#f),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=Et(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=Et(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#o=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#o=Et(this.#o.body,this.#o));let n=this.#o?this.#o.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,i]of new Headers(e.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}}}let o=typeof e=="number"?e:e?.status??this.#s;return Et(t,{status:o,headers:n??r})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,an(Tf,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,an("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,an("text/html; charset=UTF-8",r));return typeof t=="object"?sn(t,Ui.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>Et(),this.#l(this))};var ln=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(f){if(f instanceof Error&&e)n.error=f,c=await e(f,n),l=!0;else throw f}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Mi=["get","post","put","delete","options","patch","query"],er="Can not add a route since the matcher is already built.",tr=class extends Error{};var Di="__COMPOSED_HANDLER";var Lf=t=>t.text("404 Not Found",404),Hi=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},$i=class qi{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Mi,"all"].forEach(o=>{this[o]=(s,...i)=>{let a=o.toUpperCase();return typeof s=="string"?this.#t=s:this.#s(a,this.#t,s),i.forEach(c=>{this.#s(a,this.#t,c)}),this}}),this.on=(o,s,...i)=>{for(let a of[s].flat()){this.#t=a;for(let c of[o].flat()){let l=c.toUpperCase();for(let u of i)this.#s(l,this.#t,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#t=o:(this.#t="*",s.unshift(o)),s.forEach(i=>{this.#s("ALL",this.#t,i)}),this);let{strict:r,...n}=e;Object.assign(this,n),this.getPath=r??!0?e.getPath??on:_i}#e(){let e=new qi({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Lf;errorHandler=Hi;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Hi?s=o.handler:(s=async(i,a)=>(await ln([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Di]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=Ce(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=Ce(this._basePath,e),l=c==="/"?0:c.length;return u=>{let f=new URL(u.url);return f.pathname=this.getPath(u).slice(l)||"/",new Request(f,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s("ALL",Ce(e,"*"),a),this}#s(e,r,n,o){r=Ce(this._basePath,r);let s={basePath:o!==void 0?Ce(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new cn(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=ln(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,a)}})()}fetch=(e,...r)=>this.#o(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Ce("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var Q=()=>Object.create(null);var rr=[];function un(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r.ALL,a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],rr];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var hn="[^/]+";var dn="(?:|/.*)",Ie=Symbol(),ji=new Set(".\\+*[^]$()");function Of(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===".*"||t==="(?:|/.*)"?e==="(?:|/.*)"?-1:1:e===".*"||e==="(?:|/.*)"?-1:t==="[^/]+"?1:e==="[^/]+"?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Fi=class fn{#t;#e;#r=Q();insert(e,r,n,o,s){let i=this;for(let a=0,c=e.length;a<c;a++){let l=e[a],u=l.length===1?l==="*"?a===c-1?["","",".*"]:["","",hn]:null:l==="/*"?["","",dn]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(u){let d=u[1],h=u[2]||"[^/]+";if(d&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&ji.has(h)))throw Ie;if(f=i.#r[h],!f){if(h!==".*"&&h!=="(?:|/.*)"){for(let p in i.#r)if((h.length>1||p.length>1)&&p!==".*"&&p!=="(?:|/.*)")throw Ie}f=i.#r[h]=new fn}d!==""&&(f.#e??=o.varIndex++,n.push([d,f.#e]))}else if(f=i.#r[l],!f){for(let d in i.#r)if(d.length>1&&d!==".*"&&d!=="(?:|/.*)")throw Ie;f=i.#r[l]=new fn}i=f}if(i.#t!==void 0)throw Ie;i.#t=s?-1:r}buildRegExpStr(){let e=Object.keys(this.#r).sort(Of).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:ji.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}};var pn=class{#t={varIndex:0};#e=new Fi;#r=0;paths=Q();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var Gi=Q();function Wi(t){return Gi[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?dn:e==="*"?".*":`/:${hn}`)}$`)}function nr(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(Wi(r).test(e))return[...t[r]]}var or=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:Q()},this.#e={ALL:Q()},this.#r={ALL:new pn}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===Ie?new tr(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(er);if(!n[t]){this.#r[t]=new pn;for(let a of[n,o]){a[t]=Q();for(let c in a.ALL)a[t][c]=[...a.ALL[c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t==="ALL"?Object.keys(n):[t];if(/\*$/.test(e)){let a=Wi(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=nr(n[c],e)||nr(n.ALL,e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,e]);return}let i=Jt(e)||[e];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=nr(n[c],a)||nr(n.ALL,a)||[]),o[c][a].push([r,a])}match=un;buildAllMatchers(){let t=Q();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,Gi=Q(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=Q(),s=[],[i,a,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let f=l[u],d=n.paths[u];if(!d){o[u]=[f.map(([h])=>[h,Q()]),rr];continue}s[d[0]]=f.map(([h,p])=>[h,n.paths[p][1].reduceRight((b,[m],w)=>(b[m]=c[d[1][w][1]],b),Q())])}return[i,a.map(l=>s[l]),o]}};var zi=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(er);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof tr)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var mn=Q(),Pf=0,Vi=class Ki{#t=[];#e=Q();#r=[];#s;#n=mn;insert(e,r,n){let o=this,s=Li(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Oi(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(u),d=f?u[0]:u||c,h=o.#e[d]||=new Ki;u&&!h.#s&&(h.#s=u,o.#r.push(h)),o=h,f&&i.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...i],score:++Pf}})}#o(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c.ALL;if(l){l.params=Q(),e.push(l);for(let u=0,f=l.possibleKeys.length;u<f;u++){let d=l.possibleKeys[u];l.params[d]=s?.[d]&&!u?s[d]:o[d]??s?.[d]}}}}search(e,r){let n=[];this.#n=mn;let o=[this],s=nn(r),i=[],a=s.length,c=null;for(let l=0;l<a;l++){let u=s[l],f=l===a-1,d=[];for(let p=0,b=o.length;p<b;p++){let m=o[p],w=m.#e[u];w&&(w.#n=m.#n,f?(w.#e["*"]&&this.#o(n,w.#e["*"],e,m.#n),this.#o(n,w,e,m.#n)):d.push(w));for(let v of m.#r){let P=v.#s,I=m.#n===mn?{}:{...m.#n};if(typeof P=="string"){(P==="*"||u.startsWith(P.slice(0,-1)))&&(this.#o(n,v,e,m.#n),P==="*"&&(v.#n=I,d.push(v)));continue}let[,Z,D]=P;if(!(!u&&D===!0)){if(D!==!0){if(!c){c=[];let _=r[0]==="/"?1:0;for(let N=0;N<a;N++)c[N]=_,_+=s[N].length+1}let V=r.slice(c[l]),j=D.exec(V);if(j){I[Z]=j[0],this.#o(n,v,e,m.#n,I),j[0].length===V.length&&v.#e["*"]&&this.#o(n,v.#e["*"],e,m.#n,I);for(let _ in v.#e){v.#n=I;let N=j[0].match(/\//g)?.length??0;(i[N]||=[]).push(v);break}continue}}(D===!0||D.test(u))&&(I[Z]=u,f?(this.#o(n,v,e,I,m.#n),v.#e["*"]&&this.#o(n,v.#e["*"],e,I,m.#n)):(v.#n=I,d.push(v)))}}}let h=i.shift();o=h?d.concat(h):d}return n[1]&&n.sort((l,u)=>l.score-u.score),[n.map(({handler:l,params:u})=>[l,u])]}};var gn=class{name="TrieRouter";#t=new Vi;add(t,e,r){for(let n of Jt(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var ne=class extends $i{constructor(t={}){super(t),this.router=t.router??new zi({routers:[new or,new gn]})}};import{isIP as _f}from"node:net";var Cf="x-planx-l7-peer",Xi=new Set(["127.0.0.1","localhost","::1","[::1]"]);function Zi(t){let e=t.trim().toLowerCase();return e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.replace(/:\d+$/,"")}function If(t){return!!t&&Xi.has(Zi(t))}function kf(t){return t?_f(Zi(t).replace(/^\[|\]$/g,""))!==0:!1}function Nf(t){if(!t)return!1;try{let e=new URL(t);return(e.protocol==="http:"||e.protocol==="https:")&&Xi.has(e.hostname.toLowerCase())}catch{return!1}}function Uf(t){return t.host&&!If(t.host)&&!kf(t.host)?"bad-host":t.origin&&!Nf(t.origin)&&!t.l7Peer?"bad-origin":"allow"}function Yi(){return async(t,e)=>{let r=Uf({host:t.req.header("host"),origin:t.req.header("origin"),l7Peer:t.req.header(Cf)});if(r!=="allow")return new Response(JSON.stringify({error:"Forbidden",reason:r}),{status:403,headers:{"content-type":"application/json"}});await e()}}var Mf=8e3,Qi=Symbol("nx-cache-get-deadline");function Df(t,e){return e>0?new Promise((r,n)=>{let o=setTimeout(()=>r(Qi),e);t.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})}):t}function Ji(t){return t?`hit size=${t.size}`:"miss"}function Hf(t){return t instanceof Error?t.message:String(t)}function bn(t){let e=new ne,r=t.now??(()=>Date.now()),n=t.getDeadlineMs??Mf,o=(s,i,a)=>{s.then(c=>{c?.stream.cancel().catch(()=>{}),t.log?.(`nx get ${i} relay settled after deadline -> ${Ji(c)} (${r()-a}ms)`)},c=>t.log?.(`nx get ${i} relay failed after deadline: ${Hf(c)}`))};return e.get("/blob/nx/v1/cache/:hash",async s=>{let i=s.req.param("hash"),a=r();t.log?.(`nx get ${i} start`);let c=t.blob.get(i,{relay:!0}),l=await Df(c,n);return l===Qi?(t.log?.(`nx get ${i} -> miss deadline=${n}ms (${r()-a}ms, relay continues)`),o(c,i,a),t.respond(s,null)):(t.log?.(`nx get ${i} -> ${Ji(l)} (${r()-a}ms)`),t.respond(s,l))}),e.put("/blob/nx/v1/cache/:hash",async s=>{let i=s.req.param("hash"),a=r(),c=await t.blob.put(s.req.raw.body??Buffer.alloc(0));return await t.blob.bind(i,c),t.log?.(`nx put ${i} -> root=${c} (${r()-a}ms)`),s.body(null,200)}),e}function ea(t){return async(e,r)=>{if(e.req.header("authorization")!==`Bearer ${t}`)return e.body(null,401);await r()}}function nt(t,e){return e?t.body(e.stream,200,{"content-type":"application/octet-stream","content-length":String(e.size)}):t.body(null,404)}function ta(t){let e=new ne;return e.on("HEAD","/blob/objects/:hash",async r=>{let n=await t.get(r.req.param("hash"),{relay:!1});return n?(await n.stream.cancel(),r.body(null,200)):r.body(null,404)}),e.get("/blob/objects/:hash",async r=>{if(r.req.query("raw")==="1"){let o=await t.store.read(r.req.param("hash"));return o?r.body(new Uint8Array(o),200,{"content-type":"application/octet-stream","content-length":String(o.length)}):r.body(null,404)}let n=r.req.query("noRelay")!=="1";return nt(r,await t.get(r.req.param("hash"),{relay:n}))}),e.post("/blob/objects/batch",async r=>{let n=Ws(Buffer.from(await r.req.arrayBuffer()));return!n||n.some(o=>!xe(o.hash))?r.body(null,400):(await t.store.batch(async()=>{for(let o of n)await t.store.write(o.hash,o.data)}),r.json({stored:n.length}))}),e.put("/blob/objects/:hash",async r=>(await t.store.write(r.req.param("hash"),r.req.raw.body??Buffer.alloc(0)),r.body(null,200))),e}function ra(t){let e=new ne;return e.get("/blob/metrics",async r=>{let n=t.metrics.snapshot();return r.json({...n,totalBytes:await t.store.totalBytes()})}),e}var $f=4096;function oa(t){let e=new ne;return e.post("/blob/have",async r=>{let n=await na(r);if(!n)return r.body(null,400);let o=[];return await t.store.batch(async()=>{for(let s of n)await t.store.has(s)||o.push(s)}),r.json({missing:o})}),e.post("/blob/batch",async r=>{let n=await na(r);if(!n)return r.body(null,400);let o={},s=[];for(let i of n){let a=await t.store.read(i);a?o[i]=a.toString("base64"):s.push(i)}return r.json({blobs:o,missing:s})}),e}async function na(t){try{let e=await t.req.json();return!Array.isArray(e)||e.length>$f?null:e.filter(r=>typeof r=="string")}catch{return null}}function sa(t){let e=new ne;return e.get("/blob/aliases/:name",async r=>{let n=await t.store.resolveAlias(r.req.param("name"));return n?r.text(n,200):r.body(null,404)}),e.put("/blob/aliases/:name",async r=>{let n=(await r.req.text()).trim();return _e(n)?(await t.store.setAlias(r.req.param("name"),n),r.body(null,200)):r.body(null,400)}),e}function ia(t){let e=new ne;return e.get("/blob/names/:name",async r=>nt(r,await t.get(r.req.param("name"),{relay:!0}))),e.put("/blob/names/:name",async r=>{let n=await t.put(r.req.raw.body??Buffer.alloc(0));return await t.bind(r.req.param("name"),n),r.body(null,200)}),e}function vt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function he(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function U(t,e,r=""){let n=vt(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function We(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");he(t.outputLen),he(t.blockLen)}function ot(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ca(t,e){U(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Se(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function me(t,e){return t<<32-e|t>>>e}var la=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",qf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function M(t){if(U(t),la)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=qf[t[r]];return e}var Re={_0:48,_9:57,A:65,F:70,a:97,f:102};function aa(t){if(t>=Re._0&&t<=Re._9)return t-Re._0;if(t>=Re.A&&t<=Re.F)return t-(Re.A-10);if(t>=Re.a&&t<=Re.f)return t-(Re.a-10)}function q(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(la)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=aa(t.charCodeAt(s)),a=aa(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Y(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];U(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function ua(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function ge(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var fa=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function ha(t,e,r){return t&e^~t&r}function da(t,e,r){return t&e^t&r^e&r}var ir=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=sr(this.buffer)}update(e){ot(this),U(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=sr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ot(this),ca(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Se(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)r[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=sr(e),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:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ae=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var jf=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]),ke=new Uint32Array(64),yn=class extends ir{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)ke[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let d=ke[f-15],h=ke[f-2],p=me(d,7)^me(d,18)^d>>>3,b=me(h,17)^me(h,19)^h>>>10;ke[f]=b+ke[f-7]+p+ke[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=me(a,6)^me(a,11)^me(a,25),h=u+d+ha(a,c,l)+jf[f]+ke[f]|0,b=(me(n,2)^me(n,13)^me(n,22))+da(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+b|0}n=n+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(n,o,s,i,a,c,l,u)}roundClean(){Se(ke)}destroy(){this.set(0,0,0,0,0,0,0,0),Se(this.buffer)}},wn=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=ua(()=>new wn,fa(1));var En=BigInt(0),xn=BigInt(1);function Rt(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function pa(t){if(typeof t=="bigint"){if(!ar(t))throw new Error("positive bigint expected, got "+t)}else he(t);return t}function St(t){let e=pa(t).toString(16);return e.length&1?"0"+e:e}function ma(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?En:BigInt("0x"+t)}function Ne(t){return ma(M(t))}function vn(t){return ma(M(Ff(U(t)).reverse()))}function cr(t,e){he(e),t=pa(t);let r=q(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Rn(t,e){return cr(t,e).reverse()}function Ff(t){return Uint8Array.from(t)}function ga(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var ar=t=>typeof t=="bigint"&&En<=t;function Gf(t,e,r){return ar(t)&&ar(e)&&ar(r)&&e<=t&&t<r}function ba(t,e,r,n){if(!Gf(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Sn(t){let e;for(e=0;t>En;t>>=xn,e+=1);return e}var At=t=>(xn<<BigInt(t))-xn;function ya(t,e,r){if(he(t,"hashLen"),he(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),l=n(t),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...m)=>r(l,Y(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,w=[];for(;m<e;){c=d();let v=c.slice();w.push(v),m+=c.length}return Y(...w)};return(m,w)=>{f(),h(m);let v;for(;!(v=w(p()));)h();return f(),v}}function Bt(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,a){let c=t[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])=>n(a,c,i));o(e,!1),o(r,!0)}function An(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}var ce=BigInt(0),ae=BigInt(1),ze=BigInt(2),Ea=BigInt(3),va=BigInt(4),Ra=BigInt(5),Wf=BigInt(7),Sa=BigInt(8),zf=BigInt(9),Aa=BigInt(16);function be(t,e){let r=t%e;return r>=ce?r:e+r}function fe(t,e,r){let n=t;for(;e-- >ce;)n*=n,n%=r;return n}function wa(t,e){if(t===ce)throw new Error("invert: expected non-zero number");if(e<=ce)throw new Error("invert: expected positive modulus, got "+e);let r=be(t,e),n=e,o=ce,s=ae,i=ae,a=ce;for(;r!==ce;){let l=n/r,u=n%r,f=o-i*l,d=s-a*l;n=r,r=u,o=i,s=a,i=f,a=d}if(n!==ae)throw new Error("invert: does not exist");return be(o,e)}function Tn(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Ba(t,e){let r=(t.ORDER+ae)/va,n=t.pow(e,r);return Tn(t,n,e),n}function Vf(t,e){let r=(t.ORDER-Ra)/Sa,n=t.mul(e,ze),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,ze),o),a=t.mul(s,t.sub(i,t.ONE));return Tn(t,a,e),a}function Kf(t){let e=st(t),r=Ta(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Wf)/Aa;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let b=a.eql(a.sqr(u),c),m=a.cmov(l,u,b);return Tn(a,m,c),m}}function Ta(t){if(t<Ea)throw new Error("sqrt is not defined for small field");let e=t-ae,r=0;for(;e%ze===ce;)e/=ze,r++;let n=ze,o=st(t);for(;xa(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Ba;let s=o.pow(n,e),i=(e+ae)/ze;return function(c,l){if(c.is0(l))return l;if(xa(c,l)!==1)throw new Error("Cannot find square root");let u=r,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,b=c.sqr(d);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===u)throw new Error("Cannot find square root");let m=ae<<BigInt(u-p-1),w=c.pow(f,m);u=p,f=c.sqr(w),d=c.mul(d,f),h=c.mul(h,w)}return h}}function Xf(t){return t%va===Ea?Ba:t%Sa===Ra?Vf:t%Aa===zf?Kf(t):Ta(t)}var Zf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ln(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Zf.reduce((n,o)=>(n[o]="function",n),e);return Bt(t,r),t}function Yf(t,e,r){if(r<ce)throw new Error("invalid exponent, negatives unsupported");if(r===ce)return t.ONE;if(r===ae)return e;let n=t.ONE,o=e;for(;r>ce;)r&ae&&(n=t.mul(n,o)),o=t.sqr(o),r>>=ae;return n}function lr(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function xa(t,e){let r=(t.ORDER-ae)/ze,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Jf(t,e){e!==void 0&&he(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Bn=class{ORDER;BITS;BYTES;isLE;ZERO=ce;ONE=ae;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ce)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=Jf(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return be(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ce<=e&&e<this.ORDER}is0(e){return e===ce}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return be(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return be(e*e,this.ORDER)}add(e,r){return be(e+r,this.ORDER)}sub(e,r){return be(e-r,this.ORDER)}mul(e,r){return be(e*r,this.ORDER)}pow(e,r){return Yf(this,e,r)}div(e,r){return be(e*wa(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return wa(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Xf(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Rn(e,this.BYTES):cr(e,this.BYTES)}fromBytes(e,r=!1){U(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?vn(e):Ne(e);if(a&&(c=be(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return lr(this,e)}cmov(e,r,n){return n?r:e}};function st(t,e={}){return new Bn(t,e)}function La(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function On(t){let e=La(t);return e+Math.ceil(e/2)}function ur(t,e,r=!1){U(t);let n=t.length,o=La(e),s=On(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?vn(t):Ne(t),a=be(i,e-ae)+ae;return r?Rn(a,o):cr(a,o)}var it=BigInt(0),Ve=BigInt(1);function Tt(t,e){let r=e.negate();return t?r:e}function In(t,e){let r=lr(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Ca(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pn(t,e){Ca(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=At(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Oa(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Ve);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var _n=new WeakMap,Ia=new WeakMap;function Cn(t){return Ia.get(t)||1}function Pa(t){if(t!==it)throw new Error("invalid wNAF")}var fr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>it;)r&Ve&&(n=n.add(o)),o=o.double(),r>>=Ve;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Pn(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;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(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Pn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=Oa(n,a,i);n=c,u?s=s.add(Tt(d,r[h])):o=o.add(Tt(f,r[l]))}return Pa(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Pn(e,this.bits);for(let i=0;i<s.windows&&n!==it;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Oa(n,i,s);if(n=a,!l){let f=r[c];o=o.add(u?f.negate():f)}}return Pa(n),o}getPrecomputes(e,r,n){let o=_n.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),_n.set(r,o))),o}cached(e,r,n){let o=Cn(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Cn(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Ca(r,this.bits),Ia.set(e,r),_n.delete(e)}hasCache(e){return Cn(e)!==1}};function ka(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>it||n>it;)r&Ve&&(s=s.add(o)),n&Ve&&(i=i.add(o)),o=o.double(),r>>=Ve,n>>=Ve;return{p1:s,p2:i}}function _a(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ln(e),e}else return st(t,{isLE:r})}function Na(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>it))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_a(e.p,r.Fp,n),s=_a(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function hr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var dr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(We(e),U(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Se(o)}update(e){return ot(this),this.iHash.update(e),this}digestInto(e){ot(this),U(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ue=(t,e,r)=>new dr(t,e).update(r).digest();Ue.create=(t,e)=>new dr(t,e);var Ua=(t,e)=>(t+(t>=0?e:-e)/Ma)/e;function Qf(t,e,r){let[[n,o],[s,i]]=e,a=Ua(i*t,r),c=Ua(-o*t,r),l=t-a*n-c*s,u=-a*o-c*i,f=l<Be,d=u<Be;f&&(l=-l),d&&(u=-u);let h=At(Math.ceil(Sn(r)/2))+at;if(l<Be||l>=h||u<Be||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Nn(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function kn(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Rt(r.lowS,"lowS"),Rt(r.prehash,"prehash"),r.format!==void 0&&Nn(r.format),r}var Un=class extends Error{constructor(e=""){super(e)}},Me={Err:Un,_tlv:{encode:(t,e)=>{let{Err:r}=Me;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=St(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?St(o.length/2|128):"";return St(t)+s+o+e},decode(t,e){let{Err:r}=Me,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Me;if(t<Be)throw new e("integer: negative integers are not allowed");let r=St(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Me;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ne(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Me,o=U(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=Me,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},Be=BigInt(0),at=BigInt(1),Ma=BigInt(2),pr=BigInt(3),eh=BigInt(4);function Da(t,e={}){let r=Na("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Bt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=$a(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(C,x,y){let{x:g,y:R}=x.toAffine(),A=n.toBytes(g);if(Rt(y,"isCompressed"),y){u();let B=!n.isOdd(R);return Y(Ha(B),A)}else return Y(Uint8Array.of(4),A,n.toBytes(R))}function d(C){U(C,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,g=C.length,R=C[0],A=C.subarray(1);if(g===x&&(R===2||R===3)){let B=n.fromBytes(A);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let E=b(B),S;try{S=n.sqrt(E)}catch(F){let $=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+$)}u();let T=n.isOdd(S);return(R&1)===1!==T&&(S=n.neg(S)),{x:B,y:S}}else if(g===y&&R===4){let B=n.BYTES,E=n.fromBytes(A.subarray(0,B)),S=n.fromBytes(A.subarray(B,B*2));if(!m(E,S))throw new Error("bad point: is not on curve");return{x:E,y:S}}else throw new Error(`bad point: got length ${g}, expected compressed=${x} or uncompressed=${y}`)}let h=e.toBytes||f,p=e.fromBytes||d;function b(C){let x=n.sqr(C),y=n.mul(x,C);return n.add(n.add(y,n.mul(C,s.a)),s.b)}function m(C,x){let y=n.sqr(x),g=b(C);return n.eql(y,g)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,pr),eh),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,v)))throw new Error("bad curve params: a or b");function P(C,x,y=!1){if(!n.isValid(x)||y&&n.is0(x))throw new Error(`bad point coordinate ${C}`);return x}function I(C){if(!(C instanceof _))throw new Error("Weierstrass Point expected")}function Z(C){if(!c||!c.basises)throw new Error("no endo");return Qf(C,c.basises,o.ORDER)}let D=An((C,x)=>{let{X:y,Y:g,Z:R}=C;if(n.eql(R,n.ONE))return{x:y,y:g};let A=C.is0();x==null&&(x=A?n.ONE:n.inv(R));let B=n.mul(y,x),E=n.mul(g,x),S=n.mul(R,x);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(S,n.ONE))throw new Error("invZ was invalid");return{x:B,y:E}}),V=An(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x,y}=C.toAffine();if(!n.isValid(x)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!m(x,y))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(C,x,y,g,R){return y=new _(n.mul(y.X,C),y.Y,y.Z),x=Tt(g,x),y=Tt(R,y),x.add(y)}class _{static BASE=new _(s.Gx,s.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,y,g){this.X=P("x",x),this.Y=P("y",y,!0),this.Z=P("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:y,y:g}=x||{};if(!x||!n.isValid(y)||!n.isValid(g))throw new Error("invalid affine point");if(x instanceof _)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(g)?_.ZERO:new _(y,g,n.ONE)}static fromBytes(x){let y=_.fromAffine(p(U(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return _.fromBytes(q(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return H.createCache(this,x),y||this.multiply(pr),this}assertValidity(){V(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){I(x);let{X:y,Y:g,Z:R}=this,{X:A,Y:B,Z:E}=x,S=n.eql(n.mul(y,E),n.mul(A,R)),T=n.eql(n.mul(g,E),n.mul(B,R));return S&&T}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:y}=s,g=n.mul(y,pr),{X:R,Y:A,Z:B}=this,E=n.ZERO,S=n.ZERO,T=n.ZERO,O=n.mul(R,R),F=n.mul(A,A),$=n.mul(B,B),k=n.mul(R,A);return k=n.add(k,k),T=n.mul(R,B),T=n.add(T,T),E=n.mul(x,T),S=n.mul(g,$),S=n.add(E,S),E=n.sub(F,S),S=n.add(F,S),S=n.mul(E,S),E=n.mul(k,E),T=n.mul(g,T),$=n.mul(x,$),k=n.sub(O,$),k=n.mul(x,k),k=n.add(k,T),T=n.add(O,O),O=n.add(T,O),O=n.add(O,$),O=n.mul(O,k),S=n.add(S,O),$=n.mul(A,B),$=n.add($,$),O=n.mul($,k),E=n.sub(E,O),T=n.mul($,F),T=n.add(T,T),T=n.add(T,T),new _(E,S,T)}add(x){I(x);let{X:y,Y:g,Z:R}=this,{X:A,Y:B,Z:E}=x,S=n.ZERO,T=n.ZERO,O=n.ZERO,F=s.a,$=n.mul(s.b,pr),k=n.mul(y,A),G=n.mul(g,B),X=n.mul(R,E),re=n.add(y,g),W=n.add(A,B);re=n.mul(re,W),W=n.add(k,G),re=n.sub(re,W),W=n.add(y,R);let ie=n.add(A,E);return W=n.mul(W,ie),ie=n.add(k,X),W=n.sub(W,ie),ie=n.add(g,R),S=n.add(B,E),ie=n.mul(ie,S),S=n.add(G,X),ie=n.sub(ie,S),O=n.mul(F,W),S=n.mul($,X),O=n.add(S,O),S=n.sub(G,O),O=n.add(G,O),T=n.mul(S,O),G=n.add(k,k),G=n.add(G,k),X=n.mul(F,X),W=n.mul($,W),G=n.add(G,X),X=n.sub(k,X),X=n.mul(F,X),W=n.add(W,X),k=n.mul(G,W),T=n.add(T,k),k=n.mul(ie,W),S=n.mul(re,S),S=n.sub(S,k),k=n.mul(re,G),O=n.mul(ie,O),O=n.add(O,k),new _(S,T,O)}subtract(x){return this.add(x.negate())}is0(){return this.equals(_.ZERO)}multiply(x){let{endo:y}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let g,R,A=B=>H.cached(this,B,E=>In(_,E));if(y){let{k1neg:B,k1:E,k2neg:S,k2:T}=Z(x),{p:O,f:F}=A(E),{p:$,f:k}=A(T);R=F.add(k),g=j(y.beta,O,$,B,S)}else{let{p:B,f:E}=A(x);g=B,R=E}return In(_,[g,R])[0]}multiplyUnsafe(x){let{endo:y}=e,g=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Be||g.is0())return _.ZERO;if(x===at)return g;if(H.hasCache(this))return this.multiply(x);if(y){let{k1neg:R,k1:A,k2neg:B,k2:E}=Z(x),{p1:S,p2:T}=ka(_,g,A,E);return j(y.beta,S,T,R,B)}else return H.unsafe(g,x)}toAffine(x){return D(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===at?!0:x?x(_,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===at?this:x?x(_,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Rt(x,"isCompressed"),this.assertValidity(),h(_,this,x)}toHex(x=!0){return M(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,H=new fr(_,e.endo?Math.ceil(N/2):N);return _.BASE.precompute(8),_}function Ha(t){return Uint8Array.of(t?2:3)}function $a(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function th(t,e={}){let{Fn:r}=t,n=e.randomBytes||ge,o=Object.assign($a(t.Fp,r),{seed:On(r.ORDER)});function s(h){try{let p=r.fromBytes(h);return r.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:b,publicKeyUncompressed:m}=o;try{let w=h.length;return p===!0&&w!==b||p===!1&&w!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return ur(U(h,o.seed,"seed"),r.ORDER)}function c(h,p=!0){return t.BASE.multiply(r.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:b,publicKeyUncompressed:m}=o;if(!vt(h)||"_lengths"in r&&r._lengths||p===b)return;let w=U(h,void 0,"key").length;return w===b||w===m}function u(h,p,b=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(h);return t.fromBytes(p).multiply(m).toBytes(b)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=hr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:t,utils:f,lengths:o})}function qa(t,e,r={}){We(e),Bt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||ge,o=r.hmac||((y,g)=>Ue(e,y,g)),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=th(t,r),p={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=a*Ma<s.ORDER;function m(y){let g=a>>at;return y>g}function w(y,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return g}function v(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(y,g){Nn(g);let R=h.signature,A=g==="compact"?R:g==="recovered"?R+1:void 0;return U(y,A)}class I{r;s;recovery;constructor(g,R,A){if(this.r=w("r",g),this.s=w("s",R),A!=null){if(v(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(g,R=p.format){P(g,R);let A;if(R==="der"){let{r:T,s:O}=Me.toSig(U(g));return new I(T,O)}R==="recovered"&&(A=g[0],R="compact",g=g.subarray(1));let B=h.signature/2,E=g.subarray(0,B),S=g.subarray(B,B*2);return new I(i.fromBytes(E),i.fromBytes(S),A)}static fromHex(g,R){return this.fromBytes(q(g),R)}assertRecovery(){let{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new I(this.r,this.s,g)}recoverPublicKey(g){let{r:R,s:A}=this,B=this.assertRecovery(),E=B===2||B===3?R+a:R;if(!s.isValid(E))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let S=s.toBytes(E),T=t.fromBytes(Y(Ha((B&1)===0),S)),O=i.inv(E),F=D(U(g,void 0,"msgHash")),$=i.create(-F*O),k=i.create(A*O),G=t.BASE.multiplyUnsafe($).add(T.multiplyUnsafe(k));if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return m(this.s)}toBytes(g=p.format){if(Nn(g),g==="der")return q(Me.hexFromSig(this));let{r:R,s:A}=this,B=i.toBytes(R),E=i.toBytes(A);return g==="recovered"?(v(),Y(Uint8Array.of(this.assertRecovery()),B,E)):Y(B,E)}toHex(g){return M(this.toBytes(g))}}let Z=r.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");let R=Ne(g),A=g.length*8-c;return A>0?R>>BigInt(A):R},D=r.bits2int_modN||function(g){return i.create(Z(g))},V=At(c);function j(y){return ba("num < 2^"+c,y,Be,V),i.toBytes(y)}function _(y,g){return U(y,void 0,"message"),g?U(e(y),void 0,"prehashed message"):y}function N(y,g,R){let{lowS:A,prehash:B,extraEntropy:E}=kn(R,p);y=_(y,B);let S=D(y),T=i.fromBytes(g);if(!i.isValidNot0(T))throw new Error("invalid private key");let O=[j(T),j(S)];if(E!=null&&E!==!1){let G=E===!0?n(h.secretKey):E;O.push(U(G,void 0,"extraEntropy"))}let F=Y(...O),$=S;function k(G){let X=Z(G);if(!i.isValidNot0(X))return;let re=i.inv(X),W=t.BASE.multiply(X).toAffine(),ie=i.create(W.x);if(ie===Be)return;let Ut=i.create(re*i.create($+ie*T));if(Ut===Be)return;let Xo=(W.x===ie?0:2)|Number(W.y&at),Zo=Ut;return A&&m(Ut)&&(Zo=i.neg(Ut),Xo^=1),new I(ie,Zo,b?void 0:Xo)}return{seed:F,k2sig:k}}function H(y,g,R={}){let{seed:A,k2sig:B}=N(y,g,R);return ya(e.outputLen,i.BYTES,o)(A,B).toBytes(R.format)}function C(y,g,R,A={}){let{lowS:B,prehash:E,format:S}=kn(A,p);if(R=U(R,void 0,"publicKey"),g=_(g,E),!vt(y)){let T=y instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}P(y,S);try{let T=I.fromBytes(y,S),O=t.fromBytes(R);if(B&&T.hasHighS())return!1;let{r:F,s:$}=T,k=D(g),G=i.inv($),X=i.create(k*G),re=i.create(F*G),W=t.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(re));return W.is0()?!1:i.create(W.x)===F}catch{return!1}}function x(y,g,R={}){let{prehash:A}=kn(R,p);return g=_(g,A),I.fromBytes(y,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:H,verify:C,recoverPublicKey:x,Signature:I,hash:e})}var br={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},rh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},nh=BigInt(0),Mn=BigInt(2);function oh(t){let e=br.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,f=fe(u,r,e)*u%e,d=fe(f,r,e)*u%e,h=fe(d,Mn,e)*l%e,p=fe(h,o,e)*h%e,b=fe(p,s,e)*p%e,m=fe(b,a,e)*b%e,w=fe(m,c,e)*m%e,v=fe(w,a,e)*b%e,P=fe(v,r,e)*u%e,I=fe(P,i,e)*p%e,Z=fe(I,n,e)*l%e,D=fe(Z,Mn,e);if(!mr.eql(mr.sqr(D),t))throw new Error("Cannot find square root");return D}var mr=st(br.p,{sqrt:oh}),Ke=Da(br,{Fp:mr,endo:rh}),Ot=qa(Ke,ee),ja={};function gr(t,...e){let r=ja[t];if(r===void 0){let n=ee(ga(t));r=Y(n,n),ja[t]=r}return ee(Y(r,...e))}var Hn=t=>t.toBytes(!0).slice(1),$n=t=>t%Mn===nh;function Dn(t){let{Fn:e,BASE:r}=Ke,n=e.fromBytes(t),o=r.multiply(n);return{scalar:$n(o.y)?n:e.neg(n),bytes:Hn(o)}}function Ga(t){let e=mr;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),o=e.sqrt(n);$n(o)||(o=e.neg(o));let s=Ke.fromAffine({x:t,y:o});return s.assertValidity(),s}var Lt=Ne;function Wa(...t){return Ke.Fn.create(Lt(gr("BIP0340/challenge",...t)))}function Fa(t){return Dn(t).bytes}function sh(t,e,r=ge(32)){let{Fn:n}=Ke,o=U(t,void 0,"message"),{bytes:s,scalar:i}=Dn(e),a=U(r,32,"auxRand"),c=n.toBytes(i^Lt(gr("BIP0340/aux",a))),l=gr("BIP0340/nonce",c,s,o),{bytes:u,scalar:f}=Dn(l),d=Wa(u,s,o),h=new Uint8Array(64);if(h.set(u,0),h.set(n.toBytes(n.create(f+d*i)),32),!za(h,o,s))throw new Error("sign: Invalid signature produced");return h}function za(t,e,r){let{Fp:n,Fn:o,BASE:s}=Ke,i=U(t,64,"signature"),a=U(e,void 0,"message"),c=U(r,32,"publicKey");try{let l=Ga(Lt(c)),u=Lt(i.subarray(0,32));if(!n.isValidNot0(u))return!1;let f=Lt(i.subarray(32,64));if(!o.isValidNot0(f))return!1;let d=Wa(o.toBytes(u),Hn(l),a),h=s.multiplyUnsafe(f).add(l.multiplyUnsafe(o.neg(d))),{x:p,y:b}=h.toAffine();return!(h.is0()||!$n(b)||p!==u)}catch{return!1}}var ct=(()=>{let r=(n=ge(48))=>ur(n,br.n);return{keygen:hr(r,Fa),getPublicKey:Fa,sign:sh,verify:za,Point:Ke,utils:{randomSecretKey:r,taggedHash:gr,lift_x:Ga,pointToBytes:Hn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Gn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ih(t){if(!Gn(t))throw new Error("Uint8Array expected")}function Za(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function ah(t){if(typeof t!="function")throw new Error("function expected");return!0}function Xe(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Wn(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qn(t){if(!Array.isArray(t))throw new Error("array expected")}function wr(t,e){if(!Za(!0,e))throw new Error(`${t}: array of strings expected`)}function Ya(t,e){if(!Za(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ja(...t){let e=s=>s,r=(s,i)=>a=>s(i(a)),n=t.map(s=>s.encode).reduceRight(r,e),o=t.map(s=>s.decode).reduce(r,e);return{encode:n,decode:o}}function Qa(t){let e=typeof t=="string"?t.split(""):t,r=e.length;wr("alphabet",e);let n=new Map(e.map((o,s)=>[o,s]));return{encode:o=>(qn(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:o=>(qn(o),o.map(s=>{Xe("alphabet.decode",s);let i=n.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return i}))}}function ec(t=""){return Xe("join",t),{encode:e=>(wr("join.decode",e),e.join(t)),decode:e=>(Xe("join.decode",e),e.split(t))}}function ch(t,e="="){return Wn(t),Xe("padding",e),{encode(r){for(wr("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){wr("padding.decode",r);let n=r.length;if(n*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if((n-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}var tc=(t,e)=>e===0?t:tc(e,t%e),xr=(t,e)=>t+(e-tc(t,e)),yr=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function jn(t,e,r,n){if(qn(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(xr(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${xr(e,r)}`);let o=0,s=0,i=yr[e],a=yr[r]-1,c=[];for(let l of t){if(Wn(l),l>=i)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=r;s-=r)c.push((o>>s-r&a)>>>0);let u=yr[s];if(u===void 0)throw new Error("invalid carry");o&=u-1}if(o=o<<r-s&a,!n&&s>=e)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&s>0&&c.push(o>>>0),c}function rc(t,e=!1){if(Wn(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(xr(8,t)>32||xr(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Gn(r))throw new Error("radix2.encode input should be Uint8Array");return jn(Array.from(r),8,t,!e)},decode:r=>(Ya("radix2.decode",r),Uint8Array.from(jn(r,t,8,e)))}}function Va(t){return ah(t),function(...e){try{return t.apply(null,e)}catch{}}}var lh=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",uh=(t,e)=>{Xe("base64",t);let r=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,n=e?"base64url":"base64";if(t.length>0&&!r.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:n,lastChunkHandling:"strict"})},ye=lh?{encode(t){return ih(t),t.toBase64()},decode(t){return uh(t,!1)}}:Ja(rc(6),Qa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ch(6),ec(""));var Fn=Ja(Qa("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ec("")),Ka=[996825010,642813549,513874426,1027748829,705979059];function Pt(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<Ka.length;n++)(e>>n&1)===1&&(r^=Ka[n]);return r}function Xa(t,e,r=1){let n=t.length,o=1;for(let s=0;s<n;s++){let i=t.charCodeAt(s);if(i<33||i>126)throw new Error(`Invalid prefix (${t})`);o=Pt(o)^i>>5}o=Pt(o);for(let s=0;s<n;s++)o=Pt(o)^t.charCodeAt(s)&31;for(let s of e)o=Pt(o)^s;for(let s=0;s<6;s++)o=Pt(o);return o^=r,Fn.encode(jn([o%yr[30]],30,5,!1))}function fh(t){let e=t==="bech32"?1:734539939,r=rc(5),n=r.decode,o=r.encode,s=Va(n);function i(f,d,h=90){Xe("bech32.encode prefix",f),Gn(d)&&(d=Array.from(d)),Ya("bech32.encode",d);let p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);let b=p+7+d.length;if(h!==!1&&b>h)throw new TypeError(`Length ${b} exceeds limit ${h}`);let m=f.toLowerCase(),w=Xa(m,d,e);return`${m}1${Fn.encode(d)}${w}`}function a(f,d=90){Xe("bech32.decode input",f);let h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);let p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let b=p.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');let m=p.slice(0,b),w=p.slice(b+1);if(w.length<6)throw new Error("Data must be at least 6 characters long");let v=Fn.decode(w).slice(0,-6),P=Xa(m,v,e);if(!w.endsWith(P))throw new Error(`Invalid checksum in ${f}: expected "${P}"`);return{prefix:m,words:v}}let c=Va(a);function l(f){let{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:n(h)}}function u(f,d){return i(f,o(d))}return{encode:i,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:o}}var De=fh("bech32");function hh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Er(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function _t(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function K(t,e,r=""){let n=hh(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function zn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function nc(t,e){K(t,void 0,"output");let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function J(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function oe(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function oc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var dh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sc(t,e){return t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Vn(t,e){if(sc(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function ic(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Ct(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var It=(t,e)=>{function r(n,...o){if(K(n,void 0,"key"),!dh)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let u=o[0];K(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&K(o[1],void 0,"AAD");let i=e(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");K(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,K(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(K(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(r,t),r};function lt(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!Ze(e))throw new Error("invalid output, must be aligned");return e}function Kn(t,e,r){Er(r);let n=new Uint8Array(16),o=oc(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function Ze(t){return t.byteOffset%4===0}function de(t){return Uint8Array.from(t)}var te=16;var mh=283;function cc(t){if(![16,24,32].includes(t.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+t.length)}function Qn(t){return t<<1^mh&-(t>>7)}function ut(t,e){let r=0;for(;e>0;e>>=1)r^=t&-(e&1),t=Qn(t);return r}var Yn=(()=>{let t=new Uint8Array(256);for(let r=0,n=1;r<256;r++,n^=Qn(n))t[r]=n;let e=new Uint8Array(256);e[0]=99;for(let r=0;r<255;r++){let n=t[255-r];n|=n<<8,e[t[r]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return oe(t),e})(),gh=Yn.map((t,e)=>Yn.indexOf(e)),bh=t=>t<<24|t>>>8,Xn=t=>t<<8|t>>>24;function lc(t,e){if(t.length!==256)throw new Error("Wrong sbox length");let r=new Uint32Array(256).map((l,u)=>e(t[u])),n=r.map(Xn),o=n.map(Xn),s=o.map(Xn),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]=r[l]^n[u],a[f]=o[l]^s[u],c[f]=t[l]<<8|t[u]}return{sbox:t,sbox2:c,T0:r,T1:n,T2:o,T3:s,T01:i,T23:a}}var eo=lc(Yn,t=>ut(t,3)<<24|t<<16|t<<8|ut(t,2)),uc=lc(gh,t=>ut(t,11)<<24|ut(t,13)<<16|ut(t,9)<<8|ut(t,14)),yh=(()=>{let t=new Uint8Array(16);for(let e=0,r=1;e<16;e++,r=Qn(r))t[e]=r;return t})();function to(t){K(t);let e=t.length;cc(t);let{sbox2:r}=eo,n=[];Ze(t)||n.push(t=de(t));let o=J(t),s=o.length,i=c=>Ee(r,c,c,c,c),a=new Uint32Array(e+28);a.set(o);for(let c=s;c<a.length;c++){let l=a[c-1];c%s===0?l=i(bh(l))^yh[c/s-1]:s>6&&c%s===4&&(l=i(l)),a[c]=a[c-s]^l}return oe(...n),a}function wh(t){let e=to(t),r=e.slice(),n=e.length,{sbox2:o}=eo,{T0:s,T1:i,T2:a,T3:c}=uc;for(let l=0;l<n;l+=4)for(let u=0;u<4;u++)r[l+u]=e[n-l-4+u];oe(e);for(let l=4;l<n-4;l++){let u=r[l],f=Ee(o,u,u,u,u);r[l]=s[f&255]^i[f>>>8&255]^a[f>>>16&255]^c[f>>>24]}return r}function He(t,e,r,n,o,s){return t[r<<8&65280|n>>>8&255]^e[o>>>8&65280|s>>>24&255]}function Ee(t,e,r,n,o){return t[e&255|r&65280]|t[n>>>16&255|o>>>16&65280]<<16}function Jn(t,e,r,n,o){let{sbox2:s,T01:i,T23:a}=eo,c=0;e^=t[c++],r^=t[c++],n^=t[c++],o^=t[c++];let l=t.length/4-2;for(let p=0;p<l;p++){let b=t[c++]^He(i,a,e,r,n,o),m=t[c++]^He(i,a,r,n,o,e),w=t[c++]^He(i,a,n,o,e,r),v=t[c++]^He(i,a,o,e,r,n);e=b,r=m,n=w,o=v}let u=t[c++]^Ee(s,e,r,n,o),f=t[c++]^Ee(s,r,n,o,e),d=t[c++]^Ee(s,n,o,e,r),h=t[c++]^Ee(s,o,e,r,n);return{s0:u,s1:f,s2:d,s3:h}}function xh(t,e,r,n,o){let{sbox2:s,T01:i,T23:a}=uc,c=0;e^=t[c++],r^=t[c++],n^=t[c++],o^=t[c++];let l=t.length/4-2;for(let p=0;p<l;p++){let b=t[c++]^He(i,a,e,o,n,r),m=t[c++]^He(i,a,r,e,o,n),w=t[c++]^He(i,a,n,r,e,o),v=t[c++]^He(i,a,o,n,r,e);e=b,r=m,n=w,o=v}let u=t[c++]^Ee(s,e,o,n,r),f=t[c++]^Ee(s,r,e,o,n),d=t[c++]^Ee(s,n,r,e,o),h=t[c++]^Ee(s,o,n,r,e);return{s0:u,s1:f,s2:d,s3:h}}function Eh(t){if(K(t),t.length%te!==0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size "+te)}function vh(t,e,r){K(t);let n=t.length,o=n%te;if(!e&&o!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Ze(t)||(t=de(t));let s=J(t);if(e){let a=te-o;a||(a=te),n=n+a}r=lt(n,r),Vn(t,r);let i=J(r);return{b:s,o:i,out:r}}function Rh(t,e){if(!e)return t;let r=t.length;if(!r)throw new Error("aes/pcks5: empty ciphertext not allowed");let n=t[r-1];if(n<=0||n>16)throw new Error("aes/pcks5: wrong padding");let o=t.subarray(0,-n);for(let s=0;s<n;s++)if(t[r-s-1]!==n)throw new Error("aes/pcks5: wrong padding");return o}function Sh(t){let e=new Uint8Array(16),r=J(e);e.set(t);let n=te-t.length;for(let o=te-n;o<te;o++)e[o]=n;return r}var ro=It({blockSize:16,nonceLength:16},function(e,r,n={}){let o=!n.disablePadding;return{encrypt(s,i){let a=to(e),{b:c,o:l,out:u}=vh(s,o,i),f=r,d=[a];Ze(f)||d.push(f=de(f));let h=J(f),p=h[0],b=h[1],m=h[2],w=h[3],v=0;for(;v+4<=c.length;)p^=c[v+0],b^=c[v+1],m^=c[v+2],w^=c[v+3],{s0:p,s1:b,s2:m,s3:w}=Jn(a,p,b,m,w),l[v++]=p,l[v++]=b,l[v++]=m,l[v++]=w;if(o){let P=Sh(s.subarray(v*4));p^=P[0],b^=P[1],m^=P[2],w^=P[3],{s0:p,s1:b,s2:m,s3:w}=Jn(a,p,b,m,w),l[v++]=p,l[v++]=b,l[v++]=m,l[v++]=w}return oe(...d),u},decrypt(s,i){Eh(s);let a=wh(e),c=r,l=[a];Ze(c)||l.push(c=de(c));let u=J(c);i=lt(s.length,i),Ze(s)||l.push(s=de(s)),Vn(s,i);let f=J(s),d=J(i),h=u[0],p=u[1],b=u[2],m=u[3];for(let w=0;w+4<=f.length;){let v=h,P=p,I=b,Z=m;h=f[w+0],p=f[w+1],b=f[w+2],m=f[w+3];let{s0:D,s1:V,s2:j,s3:_}=xh(a,h,p,b,m);d[w++]=D^v,d[w++]=V^P,d[w++]=j^I,d[w++]=_^Z}return oe(...l),Rh(i,o)}}});function Ah(t){return t instanceof Uint32Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint32Array"}function Zn(t,e){if(K(e,16,"block"),!Ah(t))throw new Error("_encryptBlock accepts result of expandKeyLE");let r=J(e),{s0:n,s1:o,s2:s,s3:i}=Jn(t,r[0],r[1],r[2],r[3]);return r[0]=n,r[1]=o,r[2]=s,r[3]=i,e}function ac(t){let e=0;for(let r=te-1;r>=0;r--){let n=(t[r]&128)>>>7;t[r]=t[r]<<1|e,e=n}return e&&(t[te-1]^=135),t}function vr(t,e){if(t.length!==e.length)throw new Error("xorBlock: blocks must have same length");for(let r=0;r<t.length;r++)t[r]=t[r]^e[r];return t}var Rr=class{buffer;destroyed;k1;k2;xk;constructor(e){K(e),cc(e),this.xk=to(e),this.buffer=new Uint8Array(0),this.destroyed=!1;let r=new Uint8Array(te);Zn(this.xk,r),this.k1=ac(r),this.k2=ac(new Uint8Array(this.k1))}update(e){let{destroyed:r,buffer:n}=this;if(r)throw new Error("CMAC instance was destroyed");K(e);let o=new Uint8Array(n.length+e.length);return o.set(n),o.set(e,n.length),this.buffer=o,this}digest(){if(this.destroyed)throw new Error("CMAC instance was destroyed");let{buffer:e}=this,r=e.length,n=Math.ceil(r/te),o;n===0?(n=1,o=!1):o=r%te===0;let s=(n-1)*te,i=e.subarray(s),a;if(o)a=vr(new Uint8Array(i),this.k1);else{let l=new Uint8Array(te);l.set(i),l[i.length]=128,a=vr(l,this.k2)}let c=new Uint8Array(te);for(let l=0;l<n-1;l++){let u=e.subarray(l*te,(l+1)*te);vr(c,u),Zn(this.xk,c)}return vr(c,a),Zn(this.xk,c),oe(a),c}destroy(){let{buffer:e,destroyed:r,xk:n,k1:o,k2:s}=this;r||(this.destroyed=!0,oe(e,n,o,s))}},Bh=(t,e)=>new Rr(t).update(e).digest();Bh.create=t=>new Rr(t);var hc=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Th=hc("expand 16-byte k"),Lh=hc("expand 32-byte k"),Oh=J(Th),Ph=J(Lh);function L(t,e){return t<<e|t>>>32-e}function no(t){return t.byteOffset%4===0}var Sr=64,_h=16,dc=2**32-1,fc=Uint32Array.of();function Ch(t,e,r,n,o,s,i,a){let c=o.length,l=new Uint8Array(Sr),u=J(l),f=no(o)&&no(s),d=f?J(o):fc,h=f?J(s):fc;for(let p=0;p<c;i++){if(t(e,r,n,u,i,a),i>=dc)throw new Error("arx: counter overflow");let b=Math.min(Sr,c-p);if(f&&b===Sr){let m=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let w=0,v;w<_h;w++)v=m+w,h[v]=d[v]^u[w];p+=Sr;continue}for(let m=0,w;m<b;m++)w=p+m,s[w]=o[w]^l[m];p+=b}}function oo(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ic({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return _t(o),_t(i),Er(s),Er(r),(a,c,l,u,f=0)=>{K(a,void 0,"key"),K(c,void 0,"nonce"),K(l,void 0,"data");let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),K(u,void 0,"output"),_t(f),f<0||f>=dc)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let h=[],p=a.length,b,m;if(p===32)h.push(b=de(a)),m=Ph;else if(p===16&&r)b=new Uint8Array(32),b.set(a),b.set(a,16),m=Oh,h.push(b);else throw K(a,32,"arx key"),new Error("invalid key size");no(c)||h.push(c=de(c));let w=J(b);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(m,w,J(c.subarray(0,16)),w),c=c.subarray(16)}let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,h.push(c)}let P=J(c);return Ch(t,m,w,P,l,u,f,i),oe(...h),u}}function se(t,e){return t[e++]&255|(t[e++]&255)<<8}var so=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(e){e=de(K(e,32,"key"));let r=se(e,0),n=se(e,2),o=se(e,4),s=se(e,6),i=se(e,8),a=se(e,10),c=se(e,12),l=se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>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]=se(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],h=i[6],p=i[7],b=i[8],m=i[9],w=se(e,r+0),v=se(e,r+2),P=se(e,r+4),I=se(e,r+6),Z=se(e,r+8),D=se(e,r+10),V=se(e,r+12),j=se(e,r+14),_=s[0]+(w&8191),N=s[1]+((w>>>13|v<<3)&8191),H=s[2]+((v>>>10|P<<6)&8191),C=s[3]+((P>>>7|I<<9)&8191),x=s[4]+((I>>>4|Z<<12)&8191),y=s[5]+(Z>>>1&8191),g=s[6]+((Z>>>14|D<<2)&8191),R=s[7]+((D>>>11|V<<5)&8191),A=s[8]+((V>>>8|j<<8)&8191),B=s[9]+(j>>>5|o),E=0,S=E+_*a+N*(5*m)+H*(5*b)+C*(5*p)+x*(5*h);E=S>>>13,S&=8191,S+=y*(5*d)+g*(5*f)+R*(5*u)+A*(5*l)+B*(5*c),E+=S>>>13,S&=8191;let T=E+_*c+N*a+H*(5*m)+C*(5*b)+x*(5*p);E=T>>>13,T&=8191,T+=y*(5*h)+g*(5*d)+R*(5*f)+A*(5*u)+B*(5*l),E+=T>>>13,T&=8191;let O=E+_*l+N*c+H*a+C*(5*m)+x*(5*b);E=O>>>13,O&=8191,O+=y*(5*p)+g*(5*h)+R*(5*d)+A*(5*f)+B*(5*u),E+=O>>>13,O&=8191;let F=E+_*u+N*l+H*c+C*a+x*(5*m);E=F>>>13,F&=8191,F+=y*(5*b)+g*(5*p)+R*(5*h)+A*(5*d)+B*(5*f),E+=F>>>13,F&=8191;let $=E+_*f+N*u+H*l+C*c+x*a;E=$>>>13,$&=8191,$+=y*(5*m)+g*(5*b)+R*(5*p)+A*(5*h)+B*(5*d),E+=$>>>13,$&=8191;let k=E+_*d+N*f+H*u+C*l+x*c;E=k>>>13,k&=8191,k+=y*a+g*(5*m)+R*(5*b)+A*(5*p)+B*(5*h),E+=k>>>13,k&=8191;let G=E+_*h+N*d+H*f+C*u+x*l;E=G>>>13,G&=8191,G+=y*c+g*a+R*(5*m)+A*(5*b)+B*(5*p),E+=G>>>13,G&=8191;let X=E+_*p+N*h+H*d+C*f+x*u;E=X>>>13,X&=8191,X+=y*l+g*c+R*a+A*(5*m)+B*(5*b),E+=X>>>13,X&=8191;let re=E+_*b+N*p+H*h+C*d+x*f;E=re>>>13,re&=8191,re+=y*u+g*l+R*c+A*a+B*(5*m),E+=re>>>13,re&=8191;let W=E+_*m+N*b+H*p+C*h+x*d;E=W>>>13,W&=8191,W+=y*f+g*u+R*l+A*c+B*a,E+=W>>>13,W&=8191,E=(E<<2)+E|0,E=E+S|0,S=E&8191,E=E>>>13,T+=E,s[0]=S,s[1]=T,s[2]=O,s[3]=F,s[4]=$,s[5]=k,s[6]=G,s[7]=X,s[8]=re,s[9]=W}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;oe(n)}update(e){zn(this),K(e),e=de(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){zn(this),nc(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}};function Ih(t){let e=(n,o)=>t(o).update(n).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}var pc=Ih(t=>new so(t));function bc(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],u=e[0],f=e[1],d=e[2],h=e[3],p=e[4],b=e[5],m=e[6],w=e[7],v=o,P=r[0],I=r[1],Z=r[2],D=i,V=a,j=c,_=l,N=u,H=f,C=d,x=h,y=p,g=b,R=m,A=w,B=v,E=P,S=I,T=Z;for(let F=0;F<s;F+=2)D=D+N|0,B=L(B^D,16),y=y+B|0,N=L(N^y,12),D=D+N|0,B=L(B^D,8),y=y+B|0,N=L(N^y,7),V=V+H|0,E=L(E^V,16),g=g+E|0,H=L(H^g,12),V=V+H|0,E=L(E^V,8),g=g+E|0,H=L(H^g,7),j=j+C|0,S=L(S^j,16),R=R+S|0,C=L(C^R,12),j=j+C|0,S=L(S^j,8),R=R+S|0,C=L(C^R,7),_=_+x|0,T=L(T^_,16),A=A+T|0,x=L(x^A,12),_=_+x|0,T=L(T^_,8),A=A+T|0,x=L(x^A,7),D=D+H|0,T=L(T^D,16),R=R+T|0,H=L(H^R,12),D=D+H|0,T=L(T^D,8),R=R+T|0,H=L(H^R,7),V=V+C|0,B=L(B^V,16),A=A+B|0,C=L(C^A,12),V=V+C|0,B=L(B^V,8),A=A+B|0,C=L(C^A,7),j=j+x|0,E=L(E^j,16),y=y+E|0,x=L(x^y,12),j=j+x|0,E=L(E^j,8),y=y+E|0,x=L(x^y,7),_=_+N|0,S=L(S^_,16),g=g+S|0,N=L(N^g,12),_=_+N|0,S=L(S^_,8),g=g+S|0,N=L(N^g,7);let O=0;n[O++]=i+D|0,n[O++]=a+V|0,n[O++]=c+j|0,n[O++]=l+_|0,n[O++]=u+N|0,n[O++]=f+H|0,n[O++]=d+C|0,n[O++]=h+x|0,n[O++]=p+y|0,n[O++]=b+g|0,n[O++]=m+R|0,n[O++]=w+A|0,n[O++]=v+B|0,n[O++]=P+E|0,n[O++]=I+S|0,n[O++]=Z+T|0}function kh(t,e,r,n){let o=t[0],s=t[1],i=t[2],a=t[3],c=e[0],l=e[1],u=e[2],f=e[3],d=e[4],h=e[5],p=e[6],b=e[7],m=r[0],w=r[1],v=r[2],P=r[3];for(let Z=0;Z<20;Z+=2)o=o+c|0,m=L(m^o,16),d=d+m|0,c=L(c^d,12),o=o+c|0,m=L(m^o,8),d=d+m|0,c=L(c^d,7),s=s+l|0,w=L(w^s,16),h=h+w|0,l=L(l^h,12),s=s+l|0,w=L(w^s,8),h=h+w|0,l=L(l^h,7),i=i+u|0,v=L(v^i,16),p=p+v|0,u=L(u^p,12),i=i+u|0,v=L(v^i,8),p=p+v|0,u=L(u^p,7),a=a+f|0,P=L(P^a,16),b=b+P|0,f=L(f^b,12),a=a+f|0,P=L(P^a,8),b=b+P|0,f=L(f^b,7),o=o+l|0,P=L(P^o,16),p=p+P|0,l=L(l^p,12),o=o+l|0,P=L(P^o,8),p=p+P|0,l=L(l^p,7),s=s+u|0,m=L(m^s,16),b=b+m|0,u=L(u^b,12),s=s+u|0,m=L(m^s,8),b=b+m|0,u=L(u^b,7),i=i+f|0,w=L(w^i,16),d=d+w|0,f=L(f^d,12),i=i+f|0,w=L(w^i,8),d=d+w|0,f=L(f^d,7),a=a+c|0,v=L(v^a,16),h=h+v|0,c=L(c^h,12),a=a+c|0,v=L(v^a,8),h=h+v|0,c=L(c^h,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=m,n[I++]=w,n[I++]=v,n[I++]=P}var Ar=oo(bc,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Nh=oo(bc,{counterRight:!1,counterLength:8,extendNonceFn:kh,allowShortKeys:!1});var Uh=new Uint8Array(16),mc=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(Uh.subarray(r))},Mh=new Uint8Array(32);function gc(t,e,r,n,o){o!==void 0&&K(o,void 0,"AAD");let s=t(e,r,Mh),i=Kn(n.length,o?o.length:0,!0),a=pc.create(s);o&&mc(a,o),mc(a,n),a.update(i);let c=a.digest();return oe(s,i),c}var yc=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=lt(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let l=gc(t,e,r,c,n);return i.set(l,a),oe(l),i},decrypt(s,i){i=lt(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=gc(t,e,r,a,n);if(!Ct(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),oe(l),i}}),QE=It({blockSize:64,nonceLength:12,tagLength:16},yc(Ar)),ev=It({blockSize:64,nonceLength:24,tagLength:16},yc(Nh));function xc(t,e,r){return We(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Ue(t,r,e)}var io=Uint8Array.of(0),wc=Uint8Array.of();function Ec(t,e,r,n=32){We(t),he(n,"length");let o=t.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=wc:U(r,void 0,"info");let i=new Uint8Array(s*o),a=Ue.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)io[0]=u+1,c.update(u===0?wc:l).update(r).update(io).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Se(l,io),i.slice(0,n)}var Dh=Object.defineProperty,z=(t,e)=>{for(var r in e)Dh(t,r,{get:e[r],enumerable:!0})},Hh={};z(Hh,{binarySearch:()=>ho,bytesToHex:()=>M,hexToBytes:()=>q,insertEventIntoAscendingList:()=>jh,insertEventIntoDescendingList:()=>qh,isHex32:()=>ue,mergeReverseSortedLists:()=>Fh,normalizeURL:()=>$h,utf8Decoder:()=>Oe,utf8Encoder:()=>pe});var Oe=new TextDecoder("utf-8"),pe=new TextEncoder;function $h(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}function qh(t,e){let[r,n]=ho(t,o=>e.id===o.id?0:e.created_at===o.created_at?-1:o.created_at-e.created_at);return n||t.splice(r,0,e),t}function jh(t,e){let[r,n]=ho(t,o=>e.id===o.id?0:e.created_at===o.created_at?-1:e.created_at-o.created_at);return n||t.splice(r,0,e),t}function ho(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=Math.floor((r+n)/2),s=e(t[o]);if(s===0)return[o,!0];s<0?n=o-1:r=o+1}return[r,!1]}function Fh(t,e){let r=new Array(t.length+e.length);r.length=0;let n=0,o=0,s=[];for(;n<t.length&&o<e.length;){let i;if(t[n]?.created_at>e[o]?.created_at?(i=t[n],n++):(i=e[o],o++),r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}for(;n<t.length;){let i=t[n];if(n++,r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}for(;o<e.length;){let i=e[o];if(o++,r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}return r}function ue(t){for(let e=0;e<64;e++){let r=t.charCodeAt(e);if(isNaN(r)||r<48||r>102||r>57&&r<97)return!1}return!0}var ft=Symbol("verified"),Gh=t=>t instanceof Object;function po(t){if(!Gh(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!ue(t.pubkey)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let r=t.tags[e];if(!Array.isArray(r))return!1;for(let n=0;n<r.length;n++)if(typeof r[n]!="string")return!1}return!0}var Wh=class{generateSecretKey(){return ct.utils.randomSecretKey()}getPublicKey(t){return M(ct.getPublicKey(t))}finalizeEvent(t,e){let r=t;return r.pubkey=M(ct.getPublicKey(e)),r.id=Tr(r),r.sig=M(ct.sign(q(Tr(r)),e)),r[ft]=!0,r}verifyEvent(t){if(typeof t[ft]=="boolean")return t[ft];try{let e=Tr(t);if(e!==t.id)return t[ft]=!1,!1;let r=ct.verify(q(t.sig),q(e),q(t.pubkey));return t[ft]=r,r}catch{return t[ft]=!1,!1}}};function zh(t){if(!po(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Tr(t){let e=ee(pe.encode(zh(t)));return M(e)}var Pr=new Wh,Vh=Pr.generateSecretKey,mo=Pr.getPublicKey,ve=Pr.finalizeEvent,kt=Pr.verifyEvent,Kh={};z(Kh,{AIEmbeddings:()=>jd,AppCurationSet:()=>Rm,Application:()=>Em,AuthoredPodcasts:()=>jp,BadgeAward:()=>rd,BadgeDefinition:()=>lm,Bid:()=>bd,BidConfirmation:()=>yd,BlobsAuth:()=>em,BlockedRelaysList:()=>Sp,BlossomServerList:()=>Mp,BookmarkList:()=>Ep,Bookmarksets:()=>om,Calendar:()=>$m,CalendarEventRSVP:()=>qm,CashuMintAnnouncement:()=>Jm,CashuWalletEvent:()=>Zp,CashuWalletHistory:()=>ep,CashuWalletTokens:()=>Qd,ChannelCreation:()=>Cc,ChannelHideMessage:()=>Nc,ChannelMessage:()=>kc,ChannelMetadata:()=>Ic,ChannelMuteUser:()=>Uc,ChatMessage:()=>nd,Chess:()=>pd,ClassifiedListing:()=>Om,ClientAuth:()=>Dc,CodeSnippet:()=>Td,CoinjoinPool:()=>Wd,Comment:()=>vd,CommunitiesList:()=>vp,CommunityDefinition:()=>Km,CommunityPostApproval:()=>Kd,ConferenceEvent:()=>Bm,Contacts:()=>Qh,CreateOrUpdateProduct:()=>hm,CreateOrUpdateStall:()=>fm,CuratedVideoSets:()=>im,Curationsets:()=>sm,Date:()=>Dm,DecoupledEncryptionKeyDistribution:()=>Vd,DecoupledKeyAnnouncement:()=>kp,DecoupledKeyClientAnnouncement:()=>zd,DirectMessageRelaysList:()=>Np,DraftClassifiedListing:()=>Pm,DraftEvent:()=>Nm,DraftLong:()=>gm,Emojisets:()=>bm,EncryptedDirectMessage:()=>ed,EventDeletion:()=>td,FavoriteFollowSets:()=>Cp,FavoritePodcasts:()=>Up,FavoriteRelays:()=>Tp,FedimintAnnouncement:()=>Qm,Feed:()=>Mm,FileMessage:()=>ad,FileMetadata:()=>xd,FileServerPreference:()=>Dp,Followsets:()=>tm,ForumThread:()=>sd,GenericRepost:()=>xo,Genericlists:()=>rm,GeocacheListing:()=>Zm,GeocacheLog:()=>tp,GeocacheLogEntry:()=>Ym,GeocacheProofOfFind:()=>rp,GiftWrap:()=>Mc,GitPullRequest:()=>Od,GitPullRequestUpdate:()=>Pd,GoodWikiAuthorList:()=>Hp,GoodWikiRelayList:()=>$p,GroupMetadata:()=>t0,HTTPAuth:()=>Eo,Handlerinformation:()=>Gm,Handlerrecommendation:()=>Fm,Highlights:()=>bp,InteractiveRoom:()=>Am,InterestsList:()=>Op,Interestsets:()=>um,Issue:()=>_d,JobFeedback:()=>Yd,JobRequest:()=>Xd,JobResult:()=>Zd,Label:()=>$d,LegacyNsiteFile:()=>zm,LightningPubRPC:()=>Yp,LinkSet:()=>Um,LiveChatMessage:()=>Bd,LiveEvent:()=>Sm,LongFormArticle:()=>mm,MarketplaceUI:()=>dm,MediaFollows:()=>_p,MediaStarterPacks:()=>a0,MergeRequests:()=>md,Metadata:()=>Yh,ModularArticleContent:()=>wm,ModularArticleHeader:()=>ym,MuteSets:()=>am,Mutelist:()=>yp,NWCWalletInfo:()=>Kp,NWCWalletRequest:()=>Hc,NWCWalletResponse:()=>Jp,NormalVideo:()=>ud,NostrConnect:()=>Qp,NsiteNamed:()=>Xm,NsiteRoot:()=>Xp,NutZap:()=>dp,NutZapInfo:()=>Pp,OpenTimestamps:()=>wd,Patch:()=>Ld,PeerToPeerOrderEvents:()=>e0,Photo:()=>ld,Pinlist:()=>wp,PodcastEpisode:()=>dd,PodcastMetadata:()=>qp,Poll:()=>Ed,PollResponse:()=>gd,PrivateDirectMessage:()=>_c,PrivateEventRelayList:()=>Lp,ProblemTracker:()=>Md,ProductSoldAsAuction:()=>pm,ProfileBadges:()=>cm,ProxyAnnouncement:()=>zp,PublicChatsList:()=>Rp,PublicMessage:()=>hd,Reaction:()=>wo,ReactionToWebsite:()=>cd,RecommendRelay:()=>Jh,Redirects:()=>km,RelayDiscovery:()=>vm,RelayList:()=>xp,RelayMonitorAnnouncement:()=>Fp,RelayReview:()=>jm,RelayReviews:()=>qd,Relaysets:()=>nm,ReleaseArtifactSets:()=>xm,Reply:()=>Cd,Report:()=>Dd,Reporting:()=>Hd,RepositoryAnnouncement:()=>_m,RepositoryState:()=>Cm,Repost:()=>yo,ReservedCashuWalletTokens:()=>Jd,RoomPresence:()=>Gp,Scroll:()=>Sd,Seal:()=>Pc,SearchRelaysList:()=>Ap,ShortTextNote:()=>Oc,ShortVideo:()=>fd,SimpleGroupAdmins:()=>r0,SimpleGroupCreateGroup:()=>ap,SimpleGroupCreateInvite:()=>lp,SimpleGroupDeleteEvent:()=>ip,SimpleGroupDeleteGroup:()=>cp,SimpleGroupEditMetadata:()=>sp,SimpleGroupJoinRequest:()=>up,SimpleGroupLeaveRequest:()=>fp,SimpleGroupList:()=>Bp,SimpleGroupLiveKitParticipants:()=>s0,SimpleGroupMembers:()=>n0,SimpleGroupPutUser:()=>np,SimpleGroupRemoveUser:()=>op,SimpleGroupReply:()=>id,SimpleGroupRoles:()=>o0,SimpleGroupThreadedReply:()=>od,SlideSet:()=>Lm,SoftwareApplication:()=>Wm,StarterPacks:()=>i0,StatusApplied:()=>kd,StatusClosed:()=>Nd,StatusDraft:()=>Ud,StatusOpen:()=>Id,TidalLogin:()=>pp,Time:()=>Hm,Torrent:()=>Fd,TorrentComment:()=>Gd,TransportMethodAnnouncement:()=>Vp,UserEmojiList:()=>Ip,UserGraspList:()=>Wp,UserStatuses:()=>Tm,VideoViewEvent:()=>Vm,Voice:()=>Rd,VoiceComment:()=>Ad,WebBookmarks:()=>c0,WikiArticle:()=>Im,Zap:()=>gp,ZapGoal:()=>hp,ZapRequest:()=>mp,classifyKind:()=>Xh,isAddressableKind:()=>bo,isEphemeralKind:()=>Lc,isKind:()=>Zh,isRegularKind:()=>Tc,isReplaceableKind:()=>go});function Tc(t){return t<1e4&&t!==0&&t!==3}function go(t){return t===0||t===3||1e4<=t&&t<2e4}function Lc(t){return 2e4<=t&&t<3e4}function bo(t){return 3e4<=t&&t<4e4}function Xh(t){return Tc(t)?"regular":go(t)?"replaceable":Lc(t)?"ephemeral":bo(t)?"parameterized":"unknown"}function Zh(t,e){let r=e instanceof Array?e:[e];return po(t)&&r.includes(t.kind)||!1}var Yh=0,Oc=1,Jh=2,Qh=3,ed=4,td=5,yo=6,wo=7,rd=8,nd=9,od=10,sd=11,id=12,Pc=13,_c=14,ad=15,xo=16,cd=17,ld=20,ud=21,fd=22,hd=24,Cc=40,Ic=41,kc=42,Nc=43,Uc=44,dd=54,pd=64,md=818,gd=1018,bd=1021,yd=1022,wd=1040,Mc=1059,xd=1063,Ed=1068,vd=1111,Rd=1222,Sd=1227,Ad=1244,Bd=1311,Td=1337,Ld=1617,Od=1618,Pd=1619,_d=1621,Cd=1622,Id=1630,kd=1631,Nd=1632,Ud=1633,Md=1971,Dd=1984,Hd=1984,$d=1985,qd=1986,jd=1987,Fd=2003,Gd=2004,Wd=2022,zd=4454,Vd=4455,Kd=4550,Xd=5999,Zd=6999,Yd=7e3,Jd=7374,Qd=7375,ep=7376,tp=7516,rp=7517,np=9e3,op=9001,sp=9002,ip=9005,ap=9007,cp=9008,lp=9009,up=9021,fp=9022,hp=9041,dp=9321,pp=9467,mp=9734,gp=9735,bp=9802,yp=1e4,wp=10001,xp=10002,Ep=10003,vp=10004,Rp=10005,Sp=10006,Ap=10007,Bp=10009,Tp=10012,Lp=10013,Op=10015,Pp=10019,_p=10020,Cp=10021,Ip=10030,kp=10044,Np=10050,Up=10054,Mp=10063,Dp=10096,Hp=10101,$p=10102,qp=10154,jp=10164,Fp=10166,Gp=10312,Wp=10317,zp=10377,Vp=11111,Kp=13194,Xp=15128,Zp=17375,Yp=21e3,Dc=22242,Hc=23194,Jp=23195,Qp=24133,em=24242,Eo=27235,tm=3e4,rm=30001,nm=30002,om=30003,sm=30004,im=30005,am=30007,cm=30008,lm=30009,um=30015,fm=30017,hm=30018,dm=30019,pm=30020,mm=30023,gm=30024,bm=30030,ym=30040,wm=30041,xm=30063,Em=30078,vm=30166,Rm=30267,Sm=30311,Am=30312,Bm=30313,Tm=30315,Lm=30388,Om=30402,Pm=30403,_m=30617,Cm=30618,Im=30818,km=30819,Nm=31234,Um=31388,Mm=31890,Dm=31922,Hm=31923,$m=31924,qm=31925,jm=31987,Fm=31989,Gm=31990,Wm=32267,zm=34128,Vm=34237,Km=34550,Xm=35128,Zm=37515,Ym=37516,Jm=38172,Qm=38173,e0=38383,t0=39e3,r0=39001,n0=39002,o0=39003,s0=39004,i0=39089,a0=39092,c0=39701;var l0={};z(l0,{getHex64:()=>vo,getInt:()=>$c,getSubscriptionId:()=>u0,matchEventId:()=>f0,matchEventKind:()=>d0,matchEventPubkey:()=>h0});function vo(t,e){let r=e.length+3,n=t.indexOf(`"${e}":`)+r,o=t.slice(n).indexOf('"')+n+1;return t.slice(o,o+64)}function $c(t,e){let r=e.length,n=t.indexOf(`"${e}":`)+r+3,o=t.slice(n),s=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,s),10)}function u0(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let r=t.slice(e+7+1).indexOf('"');if(r===-1)return null;let n=e+7+1+r,o=t.slice(n+1,80).indexOf('"');if(o===-1)return null;let s=n+1+o;return t.slice(n+1,s)}function f0(t,e){return e===vo(t,"id")}function h0(t,e){return e===vo(t,"pubkey")}function d0(t,e){return e===$c(t,"kind")}var p0={};z(p0,{makeAuthEvent:()=>m0});function m0(t,e){return{kind:Dc,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var g0;try{g0=WebSocket}catch{}var b0=256,lv=b0*2,uv=new TextEncoder;var y0;try{y0=WebSocket}catch{}var w0={};z(w0,{BECH32_REGEX:()=>qc,Bech32MaxSize:()=>Ro,NostrTypeGuard:()=>x0,decode:()=>_r,decodeNostrURI:()=>v0,encodeBytes:()=>Ir,naddrEncode:()=>L0,neventEncode:()=>T0,noteEncode:()=>A0,nprofileEncode:()=>B0,npubEncode:()=>S0,nsecEncode:()=>R0});var x0={isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")},Ro=5e3,qc=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function E0(t){let e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function v0(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),_r(t)}catch{return{type:"invalid",data:null}}}function _r(t){let{prefix:e,words:r}=De.decode(t,Ro),n=new Uint8Array(De.fromWords(r));switch(e){case"nprofile":{let o=ao(n);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:M(o[0][0]),relays:o[1]?o[1].map(s=>Oe.decode(s)):[]}}}case"nevent":{let o=ao(n);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:M(o[0][0]),relays:o[1]?o[1].map(s=>Oe.decode(s)):[],author:o[2]?.[0]?M(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(M(o[3][0]),16):void 0}}}case"naddr":{let o=ao(n);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:Oe.decode(o[0][0]),pubkey:M(o[2][0]),kind:parseInt(M(o[3][0]),16),relays:o[1]?o[1].map(s=>Oe.decode(s)):[]}}}case"nsec":return{type:e,data:n};case"npub":case"note":return{type:e,data:M(n)};default:throw new Error(`unknown prefix ${e}`)}}function ao(t){let e={},r=t;for(;r.length>0;){if(r.length<2)throw new Error("not enough data to read TLV");let n=r[0],o=r[1],s=r.slice(2,2+o);if(r=r.slice(2+o),s.length<o)throw new Error(`not enough data to read on TLV ${n}`);e[n]=e[n]||[],e[n].push(s)}return e}function R0(t){return Ir("nsec",t)}function S0(t){return Ir("npub",q(t))}function A0(t){return Ir("note",q(t))}function Cr(t,e){let r=De.toWords(e);return De.encode(t,r,Ro)}function Ir(t,e){return Cr(t,e)}function B0(t){let e=So({0:[q(t.pubkey)],1:(t.relays||[]).map(r=>pe.encode(r))});return Cr("nprofile",e)}function T0(t){let e;t.kind!==void 0&&(e=E0(t.kind));let r=So({0:[q(t.id)],1:(t.relays||[]).map(n=>pe.encode(n)),2:t.author?[q(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return Cr("nevent",r)}function L0(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let r=So({0:[pe.encode(t.identifier)],1:(t.relays||[]).map(n=>pe.encode(n)),2:[q(t.pubkey)],3:[new Uint8Array(e)]});return Cr("naddr",r)}function So(t){let e=[];return Object.entries(t).reverse().forEach(([r,n])=>{n.forEach(o=>{let s=new Uint8Array(o.length+2);s.set([parseInt(r)],0),s.set([o.length],1),s.set(o,2),e.push(s)})}),Y(...e)}var O0={};z(O0,{decrypt:()=>P0,encrypt:()=>jc});function jc(t,e,r){let n=t instanceof Uint8Array?t:q(t),o=Ot.getSharedSecret(n,q("02"+e)),s=Fc(o),i=Uint8Array.from(ge(16)),a=pe.encode(r),c=ro(s,i).encrypt(a),l=ye.encode(new Uint8Array(c)),u=ye.encode(new Uint8Array(i.buffer));return`${l}?iv=${u}`}function P0(t,e,r){let n=t instanceof Uint8Array?t:q(t),[o,s]=r.split("?iv="),i=Ot.getSharedSecret(n,q("02"+e)),a=Fc(i),c=ye.decode(s),l=ye.decode(o),u=ro(a,c).decrypt(l);return Oe.decode(u)}function Fc(t){return t.slice(1,33)}var _0={};z(_0,{NIP05_REGEX:()=>Ao,isNip05:()=>C0,isValid:()=>N0,queryProfile:()=>Gc,searchDomain:()=>k0,useFetchImplementation:()=>I0});var Ao=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,C0=t=>Ao.test(t||""),kr;try{kr=fetch}catch{}function I0(t){kr=t}async function k0(t,e=""){try{let r=`https://${t}/.well-known/nostr.json?name=${e}`,n=await kr(r,{redirect:"manual"});if(n.status!==200)throw Error("Wrong response code");return(await n.json()).names}catch{return{}}}async function Gc(t){let e=t.match(Ao);if(!e)return null;let[,r="_",n]=e;try{let o=`https://${n}/.well-known/nostr.json?name=${r}`,s=await kr(o,{redirect:"manual"});if(s.status!==200)throw Error("Wrong response code");let i=await s.json(),a=i.names[r];return a?{pubkey:a,relays:i.relays?.[a]}:null}catch{return null}}async function N0(t,e){let r=await Gc(e);return r?r.pubkey===t:!1}var U0={};z(U0,{parse:()=>M0});function M0(t){let e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]},r,n;for(let o=t.tags.length-1;o>=0;o--){let s=t.tags[o];if(s[0]==="e"&&s[1]&&ue(s[1])){let[i,a,c,l,u]=s,f={id:a,relays:c?[c]:[],author:u&&ue(u)?u:void 0};if(l==="root"){e.root=f;continue}if(l==="reply"){e.reply=f;continue}if(l==="mention"){e.mentions.push(f);continue}r?n=f:r=f,e.mentions.push(f);continue}if(s[0]==="q"&&s[1]&&ue(s[1])){let[i,a,c]=s;e.quotes.push({id:a,relays:c?[c]:[]})}if(s[0]==="p"&&s[1]&&ue(s[1])){e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return e.root||(e.root=n||r||e.reply),e.reply||(e.reply=r||e.root),[e.reply,e.root].forEach(o=>{if(!o)return;let s=e.mentions.indexOf(o);if(s!==-1&&e.mentions.splice(s,1),o.author){let i=e.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)}}),e.mentions.forEach(o=>{if(o.author){let s=e.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)}}),e}var D0={};z(D0,{fetchRelayInformation:()=>$0,useFetchImplementation:()=>H0});var Wc;try{Wc=fetch}catch{}function H0(t){Wc=t}async function $0(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var q0={};z(q0,{getPow:()=>j0,minePow:()=>G0});function j0(t){let e=0;for(let r=0;r<64;r+=8){let n=parseInt(t.substring(r,r+8),16);if(n===0)e+=32;else{e+=Math.clz32(n);break}}return e}function F0(t){let e=0;for(let r=0;r<t.length;r++){let n=t[r];if(n===0)e+=8;else{e+=Math.clz32(n)-24;break}}return e}function G0(t,e){let r=0,n=t,o=["nonce",r.toString(),e.toString()];for(n.tags.push(o);;){let s=Math.floor(new Date().getTime()/1e3);s!==n.created_at&&(r=0,n.created_at=s),o[1]=(++r).toString();let i=ee(pe.encode(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])));if(F0(i)>=e){n.id=M(i);break}}return n}var W0={};z(W0,{unwrapEvent:()=>rg,unwrapManyEvents:()=>ng,wrapEvent:()=>ol,wrapManyEvents:()=>tg});var z0={};z(z0,{createRumor:()=>el,createSeal:()=>tl,createWrap:()=>rl,unwrapEvent:()=>Io,unwrapManyEvents:()=>nl,wrapEvent:()=>Or,wrapManyEvents:()=>Q0});var V0={};z(V0,{decrypt:()=>Co,encrypt:()=>_o,getConversationKey:()=>Oo,v2:()=>Y0});var Bo=1,To=4294967295,Lo=65536;function Oo(t,e){let r=Ot.getSharedSecret(t,q("02"+e)).subarray(1,33);return xc(ee,r,pe.encode("nip44-v2"))}function zc(t,e){let r=Ec(ee,t,e,76);return{chacha_key:r.subarray(0,32),chacha_nonce:r.subarray(32,44),hmac_key:r.subarray(44,76)}}function Po(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),r=e<=256?32:e/8;return r*(Math.floor((t-1)/r)+1)}function K0(t){if(!Number.isSafeInteger(t)||t<Bo||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function X0(t){if(!Number.isSafeInteger(t)||t<Lo||t>To)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Vc(t){let e=pe.encode(t),r=e.length;if(r<Bo||r>To)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let n=r>=Lo?Y(new Uint8Array([0,0]),X0(r)):K0(r),o=new Uint8Array(Po(r)-r);return Y(n,e,o)}function Kc(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0),n,o;if(r===0){if(n=e.getUint32(2),n<Lo)throw new Error("invalid padding");o=6}else n=r,o=2;let s=t.subarray(o,o+n);if(n<Bo||n>To||s.length!==n||t.length!==o+Po(n))throw new Error("invalid padding");return Oe.decode(s)}function Xc(t,e,r){if(r.length!==32)throw new Error("AAD associated data must be 32 bytes");let n=Y(r,e);return Ue(ee,t,n)}function Z0(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let r;try{r=ye.decode(t)}catch(s){throw new Error("invalid base64: "+s.message)}let n=r.length;if(n<99)throw new Error("invalid data length: "+n);let o=r[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:r.subarray(1,33),ciphertext:r.subarray(33,-32),mac:r.subarray(-32)}}function _o(t,e,r=ge(32)){let{chacha_key:n,chacha_nonce:o,hmac_key:s}=zc(e,r),i=Vc(t),a=Ar(n,o,i),c=Xc(s,a,r);return ye.encode(Y(new Uint8Array([2]),r,a,c))}function Co(t,e){let{nonce:r,ciphertext:n,mac:o}=Z0(t),{chacha_key:s,chacha_nonce:i,hmac_key:a}=zc(e,r),c=Xc(a,n,r);if(!Ct(c,o))throw new Error("invalid MAC");let l=Ar(s,i,n);return Kc(l)}var Y0={utils:{getConversationKey:Oo,calcPaddedLen:Po,pad:Vc,unpad:Kc},encrypt:_o,decrypt:Co},J0=2880*60,Zc=()=>Math.round(Date.now()/1e3),Yc=()=>Math.round(Zc()-Math.random()*J0),Jc=(t,e)=>Oo(t,e),Qc=(t,e,r)=>_o(JSON.stringify(t),Jc(e,r)),vc=(t,e)=>JSON.parse(Co(t.content,Jc(e,t.pubkey)));function el(t,e){let r={created_at:Zc(),content:"",tags:[],...t,pubkey:mo(e)};return r.id=Tr(r),r}function tl(t,e,r){return ve({kind:Pc,content:Qc(t,e,r),created_at:Yc(),tags:[]},e)}function rl(t,e){let r=Vh();return ve({kind:Mc,content:Qc(t,r,e),created_at:Yc(),tags:[["p",e]]},r)}function Or(t,e,r){let n=el(t,e),o=tl(n,e,r);return rl(o,r)}function Q0(t,e,r){if(!r||r.length===0)throw new Error("At least one recipient is required.");let n=mo(e),o=[Or(t,e,n)];return r.forEach(s=>{o.push(Or(t,e,s))}),o}function Io(t,e){let r=vc(t,e);return vc(r,e)}function nl(t,e){let r=[];return t.forEach(n=>{r.push(Io(n,e))}),r.sort((n,o)=>n.created_at-o.created_at),r}function eg(t,e,r,n){let o={created_at:Math.ceil(Date.now()/1e3),kind:_c,tags:[],content:e};return(Array.isArray(t)?t:[t]).forEach(({publicKey:i,relayUrl:a})=>{o.tags.push(a?["p",i,a]:["p",i])}),n&&o.tags.push(["e",n.eventId,n.relayUrl||"","reply"]),r&&o.tags.push(["subject",r]),o}function ol(t,e,r,n,o){let s=eg(e,r,n,o);return Or(s,t,e.publicKey)}function tg(t,e,r,n,o){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:mo(t)},...e].map(i=>ol(t,i,r,n,o))}var rg=Io,ng=nl,og={};z(og,{finishRepostEvent:()=>sg,getRepostedEvent:()=>ig,getRepostedEventPointer:()=>sl});function sg(t,e,r,n){let o,s=[...t.tags??[],["e",e.id,r],["p",e.pubkey]];return e.kind===Oc?o=yo:(o=xo,s.push(["k",String(e.kind)])),ve({kind:o,tags:s,content:t.content===""||e.tags?.find(i=>i[0]==="-")?"":JSON.stringify(e),created_at:t.created_at},n)}function sl(t){if(![yo,xo].includes(t.kind))return;let e,r;for(let n=t.tags.length-1;n>=0&&(e===void 0||r===void 0);n--){let o=t.tags[n];o.length>=2&&(o[0]==="e"&&e===void 0?e=o:o[0]==="p"&&r===void 0&&(r=o))}if(e!==void 0)return{id:e[1],relays:[e[2],r?.[2]].filter(n=>typeof n=="string"),author:r?.[1]}}function ig(t,{skipVerification:e}={}){let r=sl(t);if(r===void 0||t.content==="")return;let n;try{n=JSON.parse(t.content)}catch{return}if(n.id===r.id&&!(!e&&!kt(n)))return n}var ag={};z(ag,{NOSTR_URI_REGEX:()=>ko,parse:()=>lg,test:()=>cg});var ko=new RegExp(`nostr:(${qc.source})`);function cg(t){return typeof t=="string"&&new RegExp(`^${ko.source}$`).test(t)}function lg(t){let e=t.match(new RegExp(`^${ko.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:_r(e[1])}}var ug={};z(ug,{parse:()=>hg});function Rc(t){if(t)return/^\d+$/.test(t)?parseInt(t,10):t}function il(t,e){let r=t.indexOf(":"),n=t.indexOf(":",r+1);if(r===-1||n===-1)return;let o=parseInt(t.slice(0,r),10);if(Number.isNaN(o))return;let s=t.slice(r+1,n);if(ue(s))return{kind:o,pubkey:s,identifier:t.slice(n+1),relays:e?[e]:[]}}function Sc(t){switch(t[0]){case"E":case"e":return!t[1]||!ue(t[1])?void 0:{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&ue(t[3])?t[3]:void 0};case"A":case"a":return t[1]?il(t[1],t[2]):void 0;case"I":case"i":return t[1]?{value:t[1],hint:t[2]}:void 0}}function fg(t){if(t[1]){if(t[1].includes(":"))return il(t[1],t[2]);if(ue(t[1]))return{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&ue(t[3])?t[3]:void 0}}}function Ac(t){return t.findLast(e=>e.tagName==="A"||e.tagName==="a")?.pointer||t.findLast(e=>e.tagName==="I"||e.tagName==="i")?.pointer||t.findLast(e=>e.tagName==="E"||e.tagName==="e")?.pointer}function co(t,e){if(!t||!("id"in t)||!t.author)return;let r=e.find(n=>n.pubkey===t.author);!r||!r.relays||(t.relays||(t.relays=[]),r.relays.forEach(n=>{t.relays.indexOf(n)===-1&&t.relays.push(n)}),r.relays=t.relays)}function hg(t){let e={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},r=[],n=[];for(let o of t.tags){if((o[0]==="E"||o[0]==="A"||o[0]==="I")&&o[1]){let s=Sc(o);s&&r.push({tagName:o[0],pointer:s});continue}if((o[0]==="e"||o[0]==="a"||o[0]==="i")&&o[1]){let s=Sc(o);s&&n.push({tagName:o[0],pointer:s});continue}if(o[0]==="K"){e.rootKind=Rc(o[1]);continue}if(o[0]==="k"){e.replyKind=Rc(o[1]);continue}if(o[0]==="q"){let s=fg(o);s&&e.quotes.push(s);continue}(o[0]==="P"||o[0]==="p")&&o[1]&&ue(o[1])&&e.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]})}return e.root=Ac(r),e.reply=Ac(n),co(e.root,e.profiles),co(e.reply,e.profiles),e.quotes.forEach(o=>co(o,e.profiles)),e}var dg={};z(dg,{finishReactionEvent:()=>pg,getReactedEventPointer:()=>mg});function pg(t,e,r){let n=e.tags.filter(o=>o.length>=2&&(o[0]==="e"||o[0]==="p"));return ve({...t,kind:wo,tags:[...t.tags??[],...n,["e",e.id],["p",e.pubkey]],content:t.content??"+"},r)}function mg(t){if(t.kind!==wo)return;let e,r;for(let n=t.tags.length-1;n>=0&&(e===void 0||r===void 0);n--){let o=t.tags[n];o.length>=2&&(o[0]==="e"&&e===void 0?e=o:o[0]==="p"&&r===void 0&&(r=o))}if(!(e===void 0||r===void 0))return{id:e[1],relays:[e[2],r[2]].filter(n=>n!==void 0),author:r[1]}}var gg={};z(gg,{parse:()=>yg});var lo=/\W/m,Bc=/[^\w\/] |[^\w\/]$|$|,| /m,bg=42;function*yg(t){let e=[];if(typeof t!="string"){for(let s=0;s<t.tags.length;s++){let i=t.tags[s];i[0]==="emoji"&&i.length>=3&&e.push({type:"emoji",shortcode:i[1],url:i[2]})}t=t.content}let r=t.length,n=0,o=0;e:for(;o<r;){let s=t.indexOf(":",o),i=t.indexOf("#",o);if(s===-1&&i===-1)break e;if(s===-1||i>=0&&i<s){if(i===0||t[i-1].match(lo)){let a=t.slice(i+1,i+bg).match(lo),c=a?i+1+a.index:r;yield{type:"text",text:t.slice(n,i)},yield{type:"hashtag",value:t.slice(i+1,c)},o=c,n=o;continue e}o=i+1;continue e}if(t.slice(s-5,s)==="nostr"){let a=t.slice(s+60).match(lo),c=a?s+60+a.index:r;try{let l,{data:u,type:f}=_r(t.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}n!==s-5&&(yield{type:"text",text:t.slice(n,s-5)}),yield{type:"reference",pointer:l},o=c,n=o;continue e}catch{o=s+1;continue e}}else if(t.slice(s-5,s)==="https"||t.slice(s-4,s)==="http"){let a=t.slice(s+4).match(Bc),c=a?s+4+a.index:r,l=t[s-1]==="s"?5:4;try{let u=new URL(t.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid url");if(n!==s-l&&(yield{type:"text",text:t.slice(n,s-l)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(u.pathname)){yield{type:"image",url:u.toString()},o=c,n=o;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(u.pathname)){yield{type:"video",url:u.toString()},o=c,n=o;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(u.pathname)){yield{type:"audio",url:u.toString()},o=c,n=o;continue e}yield{type:"url",url:u.toString()},o=c,n=o;continue e}catch{o=c+1;continue e}}else if(t.slice(s-3,s)==="wss"||t.slice(s-2,s)==="ws"){let a=t.slice(s+4).match(Bc),c=a?s+4+a.index:r,l=t[s-1]==="s"?3:2;try{let u=new URL(t.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid ws url");n!==s-l&&(yield{type:"text",text:t.slice(n,s-l)}),yield{type:"relay",url:u.toString()},o=c,n=o;continue e}catch{o=c+1;continue e}}else{for(let a=0;a<e.length;a++){let c=e[a];if(t[s+c.shortcode.length+1]===":"&&t.slice(s+1,s+c.shortcode.length+1)===c.shortcode){n!==s&&(yield{type:"text",text:t.slice(n,s)}),yield c,o=s+c.shortcode.length+2,n=o;continue e}}o=s+1;continue e}}n!==r&&(yield{type:"text",text:t.slice(n)})}var wg={};z(wg,{channelCreateEvent:()=>xg,channelHideMessageEvent:()=>Rg,channelMessageEvent:()=>vg,channelMetadataEvent:()=>Eg,channelMuteUserEvent:()=>Sg});var xg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Cc,tags:[...t.tags??[]],content:r,created_at:t.created_at},e)},Eg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Ic,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:r,created_at:t.created_at},e)},vg=(t,e)=>{let r=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&r.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),ve({kind:kc,tags:[...r,...t.tags??[]],content:t.content,created_at:t.created_at},e)},Rg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Nc,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:r,created_at:t.created_at},e)},Sg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Uc,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:r,created_at:t.created_at},e)},Ag={};z(Ag,{EMOJI_SHORTCODE_REGEX:()=>al,matchAll:()=>Bg,regex:()=>No,replaceAll:()=>Tg});var al=/:(\w+):/,No=()=>new RegExp(`\\B${al.source}\\B`,"g");function*Bg(t){let e=t.matchAll(No());for(let r of e)try{let[n,o]=r;yield{shortcode:n,name:o,start:r.index,end:r.index+n.length}}catch{}}function Tg(t,e){return t.replaceAll(No(),(r,n)=>e({shortcode:r,name:n}))}var Lg={};z(Lg,{useFetchImplementation:()=>Og,validateGithub:()=>Pg});var Uo;try{Uo=fetch}catch{}function Og(t){Uo=t}async function Pg(t,e,r){try{return await(await Uo(`https://gist.github.com/${e}/${r}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch{return!1}}var _g={};z(_g,{makeNwcRequestEvent:()=>Ig,parseConnectionString:()=>Cg});function Cg(t){let{host:e,pathname:r,searchParams:n}=new URL(t),o=r||e,s=n.getAll("relay"),i=n.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 Ig(t,e,r){let o=jc(e,t,JSON.stringify({method:"pay_invoice",params:{invoice:r}})),s={kind:Hc,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",t]]};return ve(s,e)}var kg={};z(kg,{normalizeIdentifier:()=>Ng});function Ng(t){return t=t.trim().toLowerCase(),t=t.normalize("NFKC"),Array.from(t).map(e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-").join("")}var Ug={};z(Ug,{getSatoshisAmountFromBolt11:()=>jg,getZapEndpoint:()=>Dg,makeZapReceipt:()=>qg,makeZapRequest:()=>Hg,useFetchImplementation:()=>Mg,validateZapRequest:()=>$g});var Mo;try{Mo=fetch}catch{}function Mg(t){Mo=t}async function Dg(t){try{let e="",{lud06:r,lud16:n}=JSON.parse(t.content);if(n){let[i,a]=n.split("@");e=new URL(`/.well-known/lnurlp/${i}`,`https://${a}`).toString()}else if(r){let{words:i}=De.decode(r,1e3),a=De.fromWords(i);e=Oe.decode(a)}else return null;let s=await(await Mo(e)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function Hg(t){let e={kind:9734,created_at:Math.round(Date.now()/1e3),content:t.comment||"",tags:[["p","pubkey"in t?t.pubkey:t.event.pubkey],["amount",t.amount.toString()],["relays",...t.relays]]};if("event"in t){if(e.tags.push(["e",t.event.id]),go(t.event.kind)){let r=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(r)}else if(bo(t.event.kind)){let r=t.event.tags.find(([o,s])=>o==="d"&&s);if(!r)throw new Error("d tag not found or is empty");let n=["a",`${t.event.kind}:${t.event.pubkey}:${r[1]}`];e.tags.push(n)}e.tags.push(["k",t.event.kind.toString()])}return e}function $g(t){let e;try{e=JSON.parse(t)}catch{return"Invalid zap request JSON."}if(!po(e))return"Zap request is not a valid Nostr event.";if(!kt(e))return"Invalid signature on zap request.";let r=e.tags.find(([s,i])=>s==="p"&&i);if(!r)return"Zap request doesn't have a 'p' tag.";if(!ue(r[1]))return"Zap request 'p' tag is not valid hex.";let n=e.tags.find(([s,i])=>s==="e"&&i);return n&&!ue(n[1])?"Zap request 'e' tag is not valid hex.":e.tags.find(([s,i])=>s==="relays"&&i)?null:"Zap request doesn't have a 'relays' tag."}function qg({zapRequest:t,preimage:e,bolt11:r,paidAt:n}){let o=JSON.parse(t),s=o.tags.filter(([a])=>a==="e"||a==="p"||a==="a"),i={kind:9735,created_at:Math.round(n.getTime()/1e3),content:"",tags:[...s,["P",o.pubkey],["bolt11",r],["description",t]]};return e&&i.tags.push(["preimage",e]),i}function jg(t){if(t.length<50)return 0;t=t.substring(0,50);let e=t.lastIndexOf("1");if(e===-1)return 0;let r=t.substring(0,e);if(!r.startsWith("lnbc"))return 0;let n=r.substring(4);if(n.length<1)return 0;let o=n[n.length-1],s=o.charCodeAt(0)-48,i=s>=0&&s<=9,a=n.length-1;if(i&&a++,a<1)return 0;let c=parseInt(n.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 Fg={};z(Fg,{Negentropy:()=>ll,NegentropyStorageVector:()=>zg,NegentropySync:()=>Vg});var uo=97,ht=32,cl=16,Ye={Skip:0,Fingerprint:1,IdList:2},Le=class{_raw;length;constructor(t){typeof t=="number"?(this._raw=new Uint8Array(t),this.length=0):t instanceof Uint8Array?(this._raw=new Uint8Array(t),this.length=t.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof Le&&(t=t.unwrap()),typeof t.length!="number")throw Error("bad length");let e=t.length+this.length;if(this.capacity<e){let r=this._raw,n=Math.max(this.capacity*2,e);this._raw=new Uint8Array(n),this._raw.set(r)}this._raw.set(t,this.length),this.length+=t.length}shift(){let t=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,t}shiftN(t=1){let e=this._raw.subarray(0,t);return this._raw=this._raw.subarray(t),this.length-=t,e}};function Br(t){let e=0;for(;;){if(t.length===0)throw Error("parse ends prematurely");let r=t.shift();if(e=e<<7|r&127,(r&128)===0)break}return e}function Te(t){if(t===0)return new Le(new Uint8Array([0]));let e=[];for(;t!==0;)e.push(t&127),t>>>=7;e.reverse();for(let r=0;r<e.length-1;r++)e[r]|=128;return new Le(new Uint8Array(e))}function Gg(t){return Lr(t,1)[0]}function Lr(t,e){if(t.length<e)throw Error("parse ends prematurely");return t.shiftN(e)}var Wg=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(ht)}add(t){let e=0,r=0,n=new DataView(this.buf.buffer),o=new DataView(t.buffer);for(let s=0;s<8;s++){let i=s*4,a=n.getUint32(i,!0),c=o.getUint32(i,!0),l=a;l+=e,l+=c,l>4294967295&&(r=1),n.setUint32(i,l&4294967295,!0),e=r,r=0}}negate(){let t=new DataView(this.buf.buffer);for(let r=0;r<8;r++){let n=r*4;t.setUint32(n,~t.getUint32(n,!0))}let e=new Uint8Array(ht);e[0]=1,this.add(e)}getFingerprint(t){let e=new Le;return e.extend(this.buf),e.extend(Te(t)),ee(e.unwrap()).subarray(0,cl)}},zg=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");let r=q(e);if(r.byteLength!==ht)throw Error("bad id size for added item");this.items.push({timestamp:t,id:r})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(fo);for(let t=1;t<this.items.length;t++)if(fo(this.items[t-1],this.items[t])===0)throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(t){if(this._checkSealed(),t>=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,r){this._checkSealed(),this._checkBounds(t,e);for(let n=t;n<e&&r(this.items[n],n);++n);}findLowerBound(t,e,r){return this._checkSealed(),this._checkBounds(t,e),this._binarySearch(this.items,t,e,n=>fo(n,r)<0)}fingerprint(t,e){let r=new Wg;return r.setToZero(),this.iterate(t,e,n=>(r.add(n.id),!0)),r.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,r,n){let o=r-e;for(;o>0;){let s=e,i=Math.floor(o/2);s+=i,n(t[s])?(e=++s,o-=i+1):o=i}return e}},ll=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(t,e=6e4){if(e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}initiate(){let t=new Le;return t.extend(new Uint8Array([uo])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),M(t.unwrap())}reconcile(t,e,r){let n=new Le(q(t));this.lastTimestampIn=this.lastTimestampOut=0;let o=new Le;o.extend(new Uint8Array([uo]));let s=Gg(n);if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(s!==uo)throw Error("unsupported negentropy protocol version requested: "+(s-96));let i=this.storage.size(),a=this._bound(0),c=0,l=!1;for(;n.length!==0;){let u=new Le,f=()=>{l&&(l=!1,u.extend(this.encodeBound(a)),u.extend(Te(Ye.Skip)))},d=this.decodeBound(n),h=Br(n),p=c,b=this.storage.findLowerBound(c,i,d);if(h===Ye.Skip)l=!0;else if(h===Ye.Fingerprint){let m=Lr(n,cl),w=this.storage.fingerprint(p,b);ul(m,w)!==0?(f(),this.splitRange(p,b,d,u)):l=!0}else if(h===Ye.IdList){let m=Br(n),w={};for(let v=0;v<m;v++){let P=Lr(n,ht);w[M(P)]=P}if(l=!0,this.storage.iterate(p,b,v=>{let P=v.id,I=M(P);return w[I]?delete w[M(P)]:e?.(I),!0}),r)for(let v of Object.values(w))r(M(v))}else throw Error("unexpected mode");if(this.exceededFrameSizeLimit(o.length+u.length)){let m=this.storage.fingerprint(b,i);o.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),o.extend(Te(Ye.Fingerprint)),o.extend(m);break}else o.extend(u);c=b,a=d}return o.length===1?null:M(o.unwrap())}splitRange(t,e,r,n){let o=e-t,s=16;if(o<s*2)n.extend(this.encodeBound(r)),n.extend(Te(Ye.IdList)),n.extend(Te(o)),this.storage.iterate(t,e,i=>(n.extend(i.id),!0));else{let i=Math.floor(o/s),a=o%s,c=t;for(let l=0;l<s;l++){let u=i+(l<a?1:0),f=this.storage.fingerprint(c,c+u);c+=u;let d;if(c===e)d=r;else{let h,p;this.storage.iterate(c-1,c+1,(b,m)=>(m===c-1?h=b:p=b,!0)),d=this.getMinimalBound(h,p)}n.extend(this.encodeBound(d)),n.extend(Te(Ye.Fingerprint)),n.extend(f)}}}exceededFrameSizeLimit(t){return t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=Br(t);return e=e===0?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),r=Br(t);if(r>ht)throw Error("bound key too long");let n=Lr(t,r);return{timestamp:e,id:n}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,Te(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,Te(t+1)}encodeBound(t){let e=new Le;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(Te(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let r=0,n=e.id,o=t.id;for(let s=0;s<ht&&n[s]===o[s];s++)r++;return this._bound(e.timestamp,e.id.subarray(0,r+1))}}};function ul(t,e){for(let r=0;r<t.byteLength;r++){if(t[r]<e[r])return-1;if(t[r]>e[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength<e.byteLength?-1:0}function fo(t,e){return t.timestamp===e.timestamp?ul(t.id,e.id):t.timestamp-e.timestamp}var Vg=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(t,e,r,n={}){this.relay=t,this.storage=e,this.neg=new ll(e),this.onhave=n.onhave,this.onneed=n.onneed,this.filter=r,this.subscription=this.relay.prepareSubscription([{}],{label:n.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(),n.onclose?.())}catch(s){console.error("negentropy reconcile error:",s),n?.onclose?.(`reconcile error: ${s}`)}break}case"NEG-CLOSE":{let s=o[2];console.warn("negentropy error:",s),n.onclose?.(s);break}case"NEG-ERR":n.onclose?.()}}}async start(){let t=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${t}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},Kg={};z(Kg,{getToken:()=>Xg,hashPayload:()=>Do,unpackEventFromToken:()=>hl,validateEvent:()=>yl,validateEventKind:()=>pl,validateEventMethodTag:()=>gl,validateEventPayloadTag:()=>bl,validateEventTimestamp:()=>dl,validateEventUrlTag:()=>ml,validateToken:()=>Zg});var fl="Nostr ";async function Xg(t,e,r,n=!1,o){let s={kind:Eo,tags:[["u",t],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};o&&s.tags.push(["payload",Do(o)]);let i=await r(s);return(n?fl:"")+ye.encode(pe.encode(JSON.stringify(i)))}async function Zg(t,e,r){let n=await hl(t).catch(s=>{throw s});return await yl(n,e,r).catch(s=>{throw s})}async function hl(t){if(!t)throw new Error("Missing token");t=t.replace(fl,"");let e=Oe.decode(ye.decode(t));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function dl(t){return t.created_at?Math.round(new Date().getTime()/1e3)-t.created_at<60:!1}function pl(t){return t.kind===Eo}function ml(t,e){let r=t.tags.find(n=>n[0]==="u");return r?r.length>0&&r[1]===e:!1}function gl(t,e){let r=t.tags.find(n=>n[0]==="method");return r?r.length>0&&r[1].toLowerCase()===e.toLowerCase():!1}function Do(t){let e=ee(pe.encode(JSON.stringify(t)));return M(e)}function bl(t,e){let r=t.tags.find(o=>o[0]==="payload");if(!r)return!1;let n=Do(e);return r.length>0&&r[1]===n}async function yl(t,e,r,n){if(!kt(t))throw new Error("Invalid nostr event, signature invalid");if(!pl(t))throw new Error("Invalid nostr event, kind invalid");if(!dl(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!ml(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!gl(t,r))throw new Error("Invalid nostr event, method tag invalid");if(n&&typeof n=="object"&&Object.keys(n).length>0&&!bl(t,n))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}var wl=24242,Yg=60;function $o(t,e,r){if(!t)return Pe("missing authorization");let[n,o]=t.split(" ");if(n!=="Nostr"||!o)return Pe("authorization scheme must be Nostr");let s=Jg(o);if(!s)return Pe("authorization is not a nostr event");if(s.kind!==wl)return Pe(`authorization kind must be ${wl}`);if(!Ho(s,"t").includes(e))return Pe(`authorization t tag must be ${e}`);let i=Number(Ho(s,"expiration")[0]);return Number.isFinite(i)?i<=r?Pe("authorization expired"):s.created_at>r+Yg?Pe("authorization created in the future"):kt(s)?{ok:!0,pubkey:s.pubkey,hashes:Ho(s,"x")}:Pe("authorization signature is invalid"):Pe("authorization has no expiration")}function qo(t,e){return t.ok&&t.hashes.includes(e)}function Pe(t){return{ok:!1,reason:t}}function Jg(t){try{let e=JSON.parse(Buffer.from(t,"base64").toString("utf8"));return e&&typeof e=="object"&&Array.isArray(e.tags)?e:null}catch{return null}}function Ho(t,e){return t.tags.filter(r=>r[0]===e&&typeof r[1]=="string").map(r=>r[1])}var xl="application/octet-stream",Qg=/^([0-9a-f]{64})(?:\.([A-Za-z0-9]{1,10}))?$/,eb={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/svg+xml":"svg","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/ogg":"ogg","application/pdf":"pdf","text/plain":"txt"};function El(t){let e=Qg.exec(t);return e?{sha256:e[1],ext:e[2]??null}:null}function tb(t){return eb[t.split(";")[0].trim().toLowerCase()]??null}function vl(t,e){let r=t.get("x-forwarded-host");if(!r)return new URL(e).origin;let n=t.get("x-forwarded-proto")??"https",o=(t.get("x-forwarded-prefix")??"").replace(/\/+$/,"");return`${n}://${r}${o}`}function jo(t,e){let r=tb(t.type);return{url:`${e}/${t.sha256}${r?`.${r}`:""}`,sha256:t.sha256,size:t.size,type:t.type,uploaded:t.uploaded}}var dt="[0-9a-f]{64}",pt={"access-control-allow-origin":"*","access-control-allow-headers":"Authorization, Content-Type, X-SHA-256, X-Content-Length, X-Content-Type","access-control-allow-methods":"GET, HEAD, PUT, DELETE, OPTIONS","access-control-expose-headers":"X-Reason","access-control-max-age":"86400"};function Tl(t){let e=new ne,r=()=>new Response(null,{status:204,headers:pt});e.options("/upload",r),e.options("/list/:pubkey",r),e.options(`/:sha{${dt}}`,r),e.options(`/:file{${dt}\\.[A-Za-z0-9]+}`,r),e.get("/upload",o=>{if(o.req.method!=="HEAD")return we(404,"use PUT /upload");let s=t.admits(Nr(o.req.header("x-content-length")));return s.ok?new Response(null,{status:200,headers:pt}):we(s.status,s.reason)}),e.put("/upload",async o=>{let s=$o(o.req.header("authorization"),"upload",Bl());if(!s.ok)return we(401,s.reason);let i=t.admits(Nr(o.req.header("content-length")));if(!i.ok)return we(i.status,i.reason);let a=await t.upload(o.req.raw.body??new Blob([]).stream(),{type:o.req.header("content-type")||xl,pubkey:s.pubkey,allowed:c=>qo(s,c)});return a.ok?Al(jo(a.entry,Sl(o))):we(a.status,a.reason)}),e.get(`/list/:pubkey{${dt}}`,o=>{let s=t.list(o.req.param("pubkey"),{since:Nr(o.req.query("since"))??void 0,until:Nr(o.req.query("until"))??void 0});return Al(s.map(i=>jo(i,Sl(o))))});let n=async(o,s)=>{let i=El(s);if(!i)return we(404,"not a sha256");if(o.req.method==="HEAD"){let c=t.head(i.sha256);return c?new Response(null,{status:200,headers:Rl(c)}):we(404,"blob not found")}let a=await t.open(i.sha256);return a?new Response(a.read.stream,{status:200,headers:Rl(a.entry)}):we(404,"blob not found")};return e.get(`/:sha{${dt}}`,o=>n(o,o.req.param("sha"))),e.get(`/:file{${dt}\\.[A-Za-z0-9]+}`,o=>n(o,o.req.param("file"))),e.delete(`/:sha{${dt}}`,async o=>{let s=o.req.param("sha"),i=$o(o.req.header("authorization"),"delete",Bl());return i.ok?qo(i,s)?await t.remove(s,i.pubkey)?new Response(null,{status:200,headers:pt}):we(404,"blob not found for this pubkey"):we(401,"authorization x tag does not match the blob"):we(401,i.reason)}),e}function Rl(t){return{...pt,"content-type":t.type,"content-length":String(t.size),"x-content-type-options":"nosniff","cache-control":"public, max-age=31536000, immutable"}}function Sl(t){return vl(t.req.raw.headers,t.req.url)}function Al(t){return new Response(JSON.stringify(t),{status:200,headers:{...pt,"content-type":"application/json"}})}function we(t,e){return new Response(null,{status:t,headers:{...pt,"x-reason":e}})}function Nr(t){if(t===void 0||t==="")return null;let e=Number(t);return Number.isFinite(e)?e:null}function Bl(){return Math.floor(Date.now()/1e3)}var rb="20.86.1";function Ll(t){let e=new ne;e.use("*",Yi());let r=async()=>{let n=await t.retention.status(),{status:o,...s}=n;return{status:o,store:s,service:"blob",version:rb}};return e.get("/blob/healthz",async n=>n.json(await r())),e.get("/health",async n=>n.json(await r())),t.blossom&&e.route("/",Tl(t.blossom)),e.use("*",ea(t.token)),e.route("/",bn({blob:t.usecase,respond:nt,log:n=>console.log(`[planx-blob] ${n}`),getDeadlineMs:t.nxGetDeadlineMs})),e.route("/",ta(t.usecase)),e.route("/",ra(t.usecase)),e.route("/",oa(t.usecase)),e.route("/",sa(t.usecase)),e.route("/",ia(t.usecase)),e}import{join as nb}from"node:path";var ob="blossom.db",sb=`
47
+ `,Qs=" ";function nf(t){let e=t.map(r=>`${r.hash}${Qs}${r.subtreeBytes}`).join(Jr);return Buffer.from(`v2${Jr}${e}`,"utf-8")}function Kt(t){let e=t.toString("utf-8").split(Jr);if(e[0]!=="v2")throw new Error(`unsupported manifest version: ${e[0]}`);return e.slice(1).filter(r=>r.length>0).map(r=>{let[n,o]=r.split(Qs);return{hash:n,subtreeBytes:Number(o)}})}async function ei(t,e={}){let r=[],n=t.map(s=>({hash:s.hash,subtreeBytes:s.size})),o=n.reduce((s,i)=>s+i.subtreeBytes,0);if(n.length===1)return{rootHash:n[0].hash,totalBytes:o,objects:r};for(;;){let s=of(n,e),i=[];for(let a of s){let c=nf(a),l=await bt(1,c);r.push({hash:l,type:1,payload:c}),i.push({hash:l,subtreeBytes:a.reduce((u,f)=>u+f.subtreeBytes,0)})}if(i.length===1)return{rootHash:i[0].hash,totalBytes:o,objects:r};n=i}}function of(t,e){let r=e.minEntries??ef,n=e.avgEntries??tf,o=e.maxEntries??rf;if(t.length<=o)return[t];let s=(1<<Math.round(Math.log2(Math.max(2,n))))-1,i=[],a=0;for(;a<t.length;){let c=Math.min(a+o,t.length);for(let l=a+r;l<c;l+=1)if((sf(t[l].hash)&s)===0){c=l+1;break}i.push(t.slice(a,c)),a=c}return i}function sf(t){return parseInt(t.slice(-8),16)>>>0}async function ti(t,e){return t.batch(async()=>{let r=[];for await(let o of Js(e)){let s=await bt(0,o);await t.write(s,o),r.push({hash:s,size:o.length})}let n=await ei(r);for(let o of n.objects){await t.write(o.hash,o.payload);for(let s of Kt(o.payload))await t.link(o.hash,s.hash)}return n.rootHash})}function af(t,e){return yt(t,1,e)}async function Fe(t,e){if(!await af(t,e))return null;try{return Kt(e)}catch{throw console.error(`[planx-blob] malformed manifest, rejecting ${t}`),new Error(`malformed manifest: ${t}`)}}async function ri(t,e){let r=await e(t);if(!r)return null;let n=await Fe(t,r);return n?n.reduce((o,s)=>o+s.subtreeBytes,0):r.length}async function*en(t,e){let r=await e(t);if(!r)throw new Error(`missing object: ${t}`);let n=await Fe(t,r);if(!n){yield r;return}for(let o of n)yield*en(o.hash,e)}async function ni(t,e,r){let n;try{n=await Fe(e,r)}catch{return}if(!n)return;let o=n;await t.batch(async()=>{for(let s of o)await t.link(e,s.hash)})}async function oi(t,e){let r=[t];for(;r.length>0;){let n=[];for(let s of r)await e.has(s)||n.push(s);if(n.length>0&&!await e.fetchMissing(n))return!1;let o=[];for(let s of r){let i=await e.read(s);if(!i)return!1;try{o.push(...(await Fe(s,i)??[]).map(a=>a.hash))}catch{return!1}}r=o}return!0}async function Ge(t,e){return(await Promise.all(t.map(async n=>({peer:n,score:await cf(n.id,e)})))).sort((n,o)=>n.score<o.score?1:n.score>o.score?-1:0).map(n=>n.peer)}async function cf(t,e){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${t}:${e}`));return Buffer.from(r).toString("hex")}function si(t,e){let r=new Map;for(let o of e.keys())r.set(o,[]);let n=[];for(let o of t){let s=[...e.entries()].filter(([,i])=>i.has(o));if(s.length===0){n.push(o);continue}s.sort(([i],[a])=>(r.get(i)?.length??0)-(r.get(a)?.length??0)),r.get(s[0][0])?.push(o)}return{queues:r,unclaimed:n}}var ii=8;async function ai(t,e){if(e.length===0)return!0;let r=await lf(t,e),{queues:n,unclaimed:o}=si(e,r),s={ownedBy:r,queues:n,started:new Set,done:new Set,tried:new Map,retry:[],busy:new Map,inFlight:0,wake:[]},i=Array.from({length:ii},()=>t.peers).flat();await Promise.all(i.map(a=>uf(t,s,a)));for(let a of[...o,...e.filter(c=>!s.done.has(c))])if(!s.done.has(a)){if(!await t.fallback(a))return!1;s.done.add(a)}return!0}async function lf(t,e){let r=new Map;return await Promise.all(t.peers.map(async n=>{let o=await t.have(n,e);if(o===null)return;let s=new Set(o);r.set(n.id,new Set(e.filter(i=>!s.has(i))))})),r}async function uf(t,e,r){for(;;){let n=hf(e,r.id);if(n===null){if(e.inFlight===0)return;await new Promise(o=>e.wake.push(o));continue}e.started.add(n),li(e,n).add(r.id),!e.done.has(n)&&await ff(t,e,r,n)}}async function ff(t,e,r,n){let o=!1;e.inFlight+=1,e.busy.set(r.id,(e.busy.get(r.id)??0)+1);try{o=await t.fetchFrom(r,n)}finally{e.inFlight-=1,e.busy.set(r.id,(e.busy.get(r.id)??1)-1),o?e.done.add(n):df(e,n)&&e.retry.push(n);for(let s of e.wake.splice(0))s()}}function hf(t,e){let r=t.queues.get(e)??[];for(;r.length>0;){let o=r.shift();if(!t.started.has(o))return o}let n=t.retry.findIndex(o=>!t.done.has(o)&&ci(t,o,e));if(n>=0)return t.retry.splice(n,1)[0];for(let[o,s]of t.queues){if(o===e||(t.busy.get(o)??0)<ii)continue;let i=s.findIndex(a=>!t.started.has(a)&&t.ownedBy.get(e)?.has(a));if(i>=0)return s.splice(i,1)[0]}return null}function ci(t,e,r){return(t.ownedBy.get(r)?.has(e)??!1)&&!li(t,e).has(r)}function df(t,e){return[...t.ownedBy.keys()].some(r=>ci(t,e,r))}function li(t,e){let r=t.tried.get(e);return r||t.tried.set(e,r=new Set),r}async function tn(t,e=()=>{}){return t.length===0?null:new Promise(r=>{let n=t.length,o=!1,s=()=>{n-=1,n===0&&!o&&(o=!0,r(null))};for(let i of t)i.then(a=>{if(a===null)return s();if(o)return e(a);o=!0,r(a)},s)})}async function ui(t,e,r){let{client:n,hash:o}=r,s=new Map,i=u=>{let f=new AbortController;return s.set(u.id,f),f.signal},a=u=>f=>f?{peer:u,stream:f}:null,c=[...t.slice(0,e).map(u=>n.get(u,o,{signal:i(u)}).then(a(u)).catch(()=>null)),...t.slice(e).map(u=>{let f=i(u);return n.head(u,o,{signal:f}).then(d=>d?n.get(u,o,{signal:f}):null).then(a(u)).catch(()=>null)})],l=await tn(c,u=>{u.stream.cancel().catch(()=>{})});for(let[u,f]of s)u!==l?.peer.id&&f.abort();return l?.stream??null}function fi(t,e){return async r=>{let n=await hi(t,r);return n||(e?(t.onRemote(),pi(t,r)):null)}}async function hi(t,e){let r=await t.store.read(e);return r?await t.accepts(e,r)?r:(console.warn(`[planx-blob] local chunk failed verification, discarding ${e}`),await t.store.discard(e),null):null}function di(t,e){return{has:r=>t.store.has(r),read:r=>hi(t,r),fetchMissing:async r=>e?(t.onRemote(),ai({peers:await t.livePeers(),have:(n,o)=>t.client.have(n,o),fetchFrom:(n,o)=>pf(t,n,o),fallback:async n=>await pi(t,n)!==null},r)):!1}}async function pi(t,e){let r=await Ge(await t.livePeers(),e),n=await ui(r,t.replication,{client:t.client,hash:e});return n?mi(t,e,n):null}async function pf(t,e,r){let n=await t.client.get(e,r);return n?await mi(t,r,n)!==null:!1}async function mi(t,e,r){let n;try{n=Buffer.from(await new Response(r).arrayBuffer())}catch{return null}return await t.accepts(e,n)?(await t.store.write(e,n),await ni(t.store,e,n),n):null}function gi(t=e=>console.error(e)){let e=new Set;return(r,n)=>{let o=`${r.id} ${n}`;e.has(o)||(e.size>=64&&e.clear(),e.add(o),t(`[planx-blob] replica put failed peer=${r.id} reason=${n}`))}}var mf=8*1024*1024;async function wi(t,e){let r=await t.livePeers(),n=new Map,o=new Set,s=[e];for(;s.length>0;){let i=s.pop();if(o.has(i))continue;o.add(i);let a=await t.store.read(i);if(a){for(let c of(await Ge(r,i)).slice(0,t.replication)){let l=n.get(c.id)??{peer:c,pending:[],bytes:0,legacy:!1,failed:!1};n.set(c.id,l),l.pending.push({hash:i,data:a}),l.bytes+=a.length,l.bytes>=mf&&await bi(t,l)}s.push(...await gf(i,a))}}await Promise.all([...n.values()].map(i=>bi(t,i)))}async function gf(t,e){try{return(await Fe(t,e)??[]).map(r=>r.hash).reverse()}catch{return[]}}async function bi(t,e){let r=e.pending;if(e.pending=[],e.bytes=0,!(r.length===0||e.failed)){if(!e.legacy){let n=await t.client.putBatch(e.peer,r);if(n.ok)return;if(!n.unsupported)return yi(t,e,n.reason);e.legacy=!0}for(let n of r){let o=await t.client.put(e.peer,n.hash,n.data).catch(s=>({ok:!1,reason:`error ${String(s)}`}));if(!o.ok)return yi(t,e,o.reason)}}}function yi(t,e,r){e.failed=!0,t.onFailure(e.peer,r)}function xi(t){return new ReadableStream({async pull(e){try{let r=await t.next();if(r.done)return e.close();e.enqueue(new Uint8Array(r.value))}catch(r){e.error(r)}},cancel:()=>{t.return(void 0)}})}async function Ei(t,e,r){let n=await Ge(await t.livePeers(),e);await Promise.all(n.slice(0,t.replication).map(o=>t.client.putAlias(o,e,r)))}async function vi(t,e){if(_e(e))return null;let r=await Ge(await t.livePeers(),e);return tn(r.map(async n=>{let o=await t.client.getAlias(n,e);return o&&_e(o)?o:null}))}var bf=2,Xt=class{constructor(e,r,n,o={}){this.store=e;this.peers=r;this.client=n;this.options=o;this.reportReplicaFailure=gi();this.metrics=o.metrics??new rt}async get(e,r){let n=this.now(),o=await this.rootOf(e,r.relay),s={value:!1},i={store:this.store,client:this.client,replication:this.replication(),livePeers:()=>this.peers.livePeers(),accepts:(l,u)=>this.accepts(l,u),onRemote:()=>{s.value=!0}},a=fi(i,r.relay),c;try{c=await ri(o,a)}catch{c=null}return c===null||!await this.store.batch(()=>oi(o,di(i,r.relay)))?(this.metrics.recordMiss(this.now()-n),null):(s.value?this.metrics.recordRelayHit(this.now()-n):this.metrics.recordLocalHit(this.now()-n),{size:c,stream:xi(en(o,a))})}async rootOf(e,r){let n=await this.store.resolveAlias(e);if(n)return await this.store.touchAlias(e,this.now()),n;if(!r)return e;let o=await vi(await this.aliasDeps(),e);return o?(await this.store.setAlias(e,o),o):e}async aliasDeps(){return{client:this.client,livePeers:()=>this.peers.livePeers(),replication:this.replication()}}now(){return(this.options.now??(()=>Date.now()))()}async accepts(e,r){return await yt(e,0,r)||await yt(e,1,r)?!0:(console.error(`[planx-blob] hash mismatch, rejecting ${e}`),!1)}async put(e){let r=this.now(),n=await Vt(e),o;try{o=await ti(this.store,n.path),wi(this.replicationDeps(),o).catch(()=>{})}finally{await n.discard()}return this.metrics.recordPut(this.now()-r),await this.options.retention?.afterPut(),o}async bind(e,r){await this.store.setAlias(e,r,this.now()),this.aliasDeps().then(n=>Ei(n,e,r)).catch(()=>{})}replicationDeps(){return{store:this.store,client:this.client,livePeers:()=>this.peers.livePeers(),replication:this.replication(),onFailure:(e,r)=>{this.metrics.recordReplicaFailure(e.id,r),this.reportReplicaFailure(e,r)}}}replication(){return this.options.replication??bf}};var Ri=Symbol();var Si=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData();var yf=1e4,Zt=t=>"headers"in t,Ti=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,o=(Zt(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?wf(t,{all:r,dot:n}):{}};async function wf(t,e){if(!Zt(t)&&t.bodyCache.formData)return Ai(await t.bodyCache.formData,e);let r=Zt(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=Si(n,r.get("Content-Type")||"");Zt(t)||(t.bodyCache.formData=o);let s=await o;return s?Ai(s,e):{}}function Ai(t,e){let r=Object.create(null),n={count:0};return t.forEach((o,s)=>{e.all||s.endsWith("[]")?xf(r,s,o):r[s]=o}),e.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Ef(r,o,s,n),delete r[o])}),r}var xf=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},Ef=(t,e,r,n)=>{if(/(?:^|\.)__proto__\./.test(e))return;let o=t,s=e.split(".",34);s.length>33&&Bi(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=yf&&Bi(),o[i]=Object.create(null)),o=o[i])})},Bi=()=>{throw new Error("Nesting limit exceeded")};var nn=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},Li=t=>{let{groups:e,path:r}=vf(t),n=nn(r);return Rf(n,e)},vf=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},Rf=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},Yt={},Oi=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return Yt[n]||(r[2]?Yt[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:Yt[n]=[t,r[1],!0]),Yt[n]}return null},Pi=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},Sf=t=>Pi(t,decodeURI),on=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return Sf(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var _i=t=>{let e=on(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},Ce=(t,e,...r)=>(r.length&&(e=Ce(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Jt=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},Qt=t=>t.indexOf("%")!==-1?Pi(t,Af):t,rn=t=>(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),Qt(t)),Ci=(t,e,r)=>{let n=t.indexOf("#",8);n!==-1&&(t=t.slice(0,n));let o;if(!r&&e&&e.indexOf("%")===-1&&e.indexOf("+")===-1){let a=t.indexOf("?",8);if(a===-1)return;for(t.startsWith(e,a+1)||(a=t.indexOf(`&${e}`,a+1));a!==-1;){let c=t.charCodeAt(a+e.length+1);if(c===61){let l=a+e.length+2,u=t.indexOf("&",l);return rn(t.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=t.indexOf(`&${e}`,a+1)}if(o=/[%+]/.test(t),!o)return}let s=Object.create(null);o??=/[%+]/.test(t);let i=t.indexOf("?",8);for(;i!==-1;){let a=t.indexOf("&",i+1),c=t.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=t.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=rn(l)),i=a,l==="")continue;let u;c===-1?u="":(u=t.slice(c+1,a===-1?void 0:a),o&&(u=rn(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return e?s[e]:s},Ii=Ci,ki=(t,e)=>Ci(t,e,!0),Af=decodeURIComponent;var Ni=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex]?.[1][t],r=this.#n(e);return r&&Qt(r)}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of e){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=Qt(n))}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Ii(this.url,t)}queries(t){return ki(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ti(this,t)}#o=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;for(let o in e)return e[o].then(s=>{o==="json"&&(s=JSON.stringify(s));let i=o==="formData"?void 0:r.headers.get("content-type");return new Response(s,{headers:i?{"Content-Type":i}:void 0})[t]()});return e[t]=r[t]()};json(){return this.#o("text").then(t=>JSON.parse(t))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#o("blob")}formData(){return this.#o("formData")}addValidatedData(t,e){(this.#t??={})[t]=e}valid(t){return this.#t?.[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ri](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ui={Stringify:1,BeforeStream:2,Stream:3},Bf=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var sn=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>sn(c,e,!1,n,o))).then(()=>o[0]));return r?Bf(await i,s):i};var Tf="text/plain; charset=UTF-8",an=(t,e)=>({"Content-Type":t,...e}),Et=(t,e)=>new Response(t,e),cn=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#f;#h;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#h=e.path,this.#f=e.matchResult)}get req(){return this.#e??=new Ni(this.#t,this.#h,this.#f),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=Et(null,{headers:this.#a??=new Headers})}set res(t){if(this.#o&&t){t=Et(t.body,t);for(let[e,r]of this.#o.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#o.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#o=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#o=Et(this.#o.body,this.#o));let n=this.#o?this.#o.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#o?new Headers(this.#o.headers):this.#a;if(typeof e=="object"&&e.headers){n??=new Headers;for(let[s,i]of new Headers(e.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}}}let o=typeof e=="number"?e:e?.status??this.#s;return Et(t,{status:o,headers:n??r})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,an(Tf,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,an("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,an("text/html; charset=UTF-8",r));return typeof t=="object"?sn(t,Ui.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>Et(),this.#l(this))};var ln=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(f){if(f instanceof Error&&e)n.error=f,c=await e(f,n),l=!0;else throw f}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Mi=["get","post","put","delete","options","patch","query"],er="Can not add a route since the matcher is already built.",tr=class extends Error{};var Di="__COMPOSED_HANDLER";var Lf=t=>t.text("404 Not Found",404),Hi=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},$i=class qi{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Mi,"all"].forEach(o=>{this[o]=(s,...i)=>{let a=o.toUpperCase();return typeof s=="string"?this.#t=s:this.#s(a,this.#t,s),i.forEach(c=>{this.#s(a,this.#t,c)}),this}}),this.on=(o,s,...i)=>{for(let a of[s].flat()){this.#t=a;for(let c of[o].flat()){let l=c.toUpperCase();for(let u of i)this.#s(l,this.#t,u)}}return this},this.use=(o,...s)=>(typeof o=="string"?this.#t=o:(this.#t="*",s.unshift(o)),s.forEach(i=>{this.#s("ALL",this.#t,i)}),this);let{strict:r,...n}=e;Object.assign(this,n),this.getPath=r??!0?e.getPath??on:_i}#e(){let e=new qi({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Lf;errorHandler=Hi;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Hi?s=o.handler:(s=async(i,a)=>(await ln([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Di]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=Ce(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=Ce(this._basePath,e),l=c==="/"?0:c.length;return u=>{let f=new URL(u.url);return f.pathname=this.getPath(u).slice(l)||"/",new Request(f,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s("ALL",Ce(e,"*"),a),this}#s(e,r,n,o){r=Ce(this._basePath,r);let s={basePath:o!==void 0?Ce(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#n(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#o(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new cn(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=ln(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,a)}})()}fetch=(e,...r)=>this.#o(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${Ce("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#o(e.request,e,void 0,e.request.method))})}};var Q=()=>Object.create(null);var rr=[];function un(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r.ALL,a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],rr];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var hn="[^/]+";var dn="(?:|/.*)",Ie=Symbol(),ji=new Set(".\\+*[^]$()");function Of(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1?1:t===".*"||t==="(?:|/.*)"?e==="(?:|/.*)"?-1:1:e===".*"||e==="(?:|/.*)"?-1:t==="[^/]+"?1:e==="[^/]+"?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Fi=class fn{#t;#e;#r=Q();insert(e,r,n,o,s){let i=this;for(let a=0,c=e.length;a<c;a++){let l=e[a],u=l.length===1?l==="*"?a===c-1?["","",".*"]:["","",hn]:null:l==="/*"?["","",dn]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(u){let d=u[1],h=u[2]||"[^/]+";if(d&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))||h.length===1&&ji.has(h)))throw Ie;if(f=i.#r[h],!f){if(h!==".*"&&h!=="(?:|/.*)"){for(let p in i.#r)if((h.length>1||p.length>1)&&p!==".*"&&p!=="(?:|/.*)")throw Ie}f=i.#r[h]=new fn}d!==""&&(f.#e??=o.varIndex++,n.push([d,f.#e]))}else if(f=i.#r[l],!f){for(let d in i.#r)if(d.length>1&&d!==".*"&&d!=="(?:|/.*)")throw Ie;f=i.#r[l]=new fn}i=f}if(i.#t!==void 0)throw Ie;i.#t=s?-1:r}buildRegExpStr(){let e=Object.keys(this.#r).sort(Of).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:ji.has(r)?`\\${r}`:r)+o}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&e.unshift(`#${this.#t}`),e.length===0?"":e.length===1?e[0]:"(?:"+e.join("|")+")"}};var pn=class{#t={varIndex:0};#e=new Fi;#r=0;paths=Q();insert(t,e){if(e){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=t;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[t]=[this.#r++,r]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var Gi=Q();function Wi(t){return Gi[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,r)=>r?`\\${r}`:e==="/*"?dn:e==="*"?".*":`/:${hn}`)}$`)}function nr(t,e){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(Wi(r).test(e))return[...t[r]]}var or=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:Q()},this.#e={ALL:Q()},this.#r={ALL:new pn}}#s(t,e){try{this.#r[t].insert(e,!/\*|\/:/.test(e))}catch(r){throw r===Ie?new tr(e):r}}add(t,e,r){let n=this.#t,o=this.#e;if(!n)throw new Error(er);if(!n[t]){this.#r[t]=new pn;for(let a of[n,o]){a[t]=Q();for(let c in a.ALL)a[t][c]=[...a.ALL[c]],this.#s(t,c)}}e==="/*"&&(e="*");let s=t==="ALL"?Object.keys(n):[t];if(/\*$/.test(e)){let a=Wi(e);for(let c of s)n[c][e]||(this.#s(c,e),n[c][e]=nr(n[c],e)||nr(n.ALL,e)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,e]);return}let i=Jt(e)||[e];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=nr(n[c],a)||nr(n.ALL,a)||[]),o[c][a].push([r,a])}match=un;buildAllMatchers(){let t=Q();for(let e of Object.keys(this.#e))t[e]=this.#n(e);return this.#t=this.#e=this.#r=void 0,Gi=Q(),t}#n(t){let e=this.#t[t],r=this.#e[t],n=this.#r[t],o=Q(),s=[],[i,a,c]=n.buildRegExp();for(let l of[e,r])for(let u in l){let f=l[u],d=n.paths[u];if(!d){o[u]=[f.map(([h])=>[h,Q()]),rr];continue}s[d[0]]=f.map(([h,p])=>[h,n.paths[p][1].reduceRight((b,[m],w)=>(b[m]=c[d[1][w][1]],b),Q())])}return[i,a.map(l=>s[l]),o]}};var zi=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(er);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof tr)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var mn=Q(),Pf=0,Vi=class Ki{#t=[];#e=Q();#r=[];#s;#n=mn;insert(e,r,n){let o=this,s=Li(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=Oi(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(u),d=f?u[0]:u||c,h=o.#e[d]||=new Ki;u&&!h.#s&&(h.#s=u,o.#r.push(h)),o=h,f&&i.add(u[1])}o.#t.push({[e]:{handler:n,possibleKeys:[...i],score:++Pf}})}#o(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c.ALL;if(l){l.params=Q(),e.push(l);for(let u=0,f=l.possibleKeys.length;u<f;u++){let d=l.possibleKeys[u];l.params[d]=s?.[d]&&!u?s[d]:o[d]??s?.[d]}}}}search(e,r){let n=[];this.#n=mn;let o=[this],s=nn(r),i=[],a=s.length,c=null;for(let l=0;l<a;l++){let u=s[l],f=l===a-1,d=[];for(let p=0,b=o.length;p<b;p++){let m=o[p],w=m.#e[u];w&&(w.#n=m.#n,f?(w.#e["*"]&&this.#o(n,w.#e["*"],e,m.#n),this.#o(n,w,e,m.#n)):d.push(w));for(let v of m.#r){let P=v.#s,I=m.#n===mn?{}:{...m.#n};if(typeof P=="string"){(P==="*"||u.startsWith(P.slice(0,-1)))&&(this.#o(n,v,e,m.#n),P==="*"&&(v.#n=I,d.push(v)));continue}let[,Z,D]=P;if(!(!u&&D===!0)){if(D!==!0){if(!c){c=[];let _=r[0]==="/"?1:0;for(let N=0;N<a;N++)c[N]=_,_+=s[N].length+1}let V=r.slice(c[l]),j=D.exec(V);if(j){I[Z]=j[0],this.#o(n,v,e,m.#n,I),j[0].length===V.length&&v.#e["*"]&&this.#o(n,v.#e["*"],e,m.#n,I);for(let _ in v.#e){v.#n=I;let N=j[0].match(/\//g)?.length??0;(i[N]||=[]).push(v);break}continue}}(D===!0||D.test(u))&&(I[Z]=u,f?(this.#o(n,v,e,I,m.#n),v.#e["*"]&&this.#o(n,v.#e["*"],e,I,m.#n)):(v.#n=I,d.push(v)))}}}let h=i.shift();o=h?d.concat(h):d}return n[1]&&n.sort((l,u)=>l.score-u.score),[n.map(({handler:l,params:u})=>[l,u])]}};var gn=class{name="TrieRouter";#t=new Vi;add(t,e,r){for(let n of Jt(e)||[e])this.#t.insert(t,n,r)}match(t,e){return this.#t.search(t,e)}};var ne=class extends $i{constructor(t={}){super(t),this.router=t.router??new zi({routers:[new or,new gn]})}};import{isIP as _f}from"node:net";var Cf="x-planx-l7-peer",Xi=new Set(["127.0.0.1","localhost","::1","[::1]"]);function Zi(t){let e=t.trim().toLowerCase();return e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.replace(/:\d+$/,"")}function If(t){return!!t&&Xi.has(Zi(t))}function kf(t){return t?_f(Zi(t).replace(/^\[|\]$/g,""))!==0:!1}function Nf(t){if(!t)return!1;try{let e=new URL(t);return(e.protocol==="http:"||e.protocol==="https:")&&Xi.has(e.hostname.toLowerCase())}catch{return!1}}function Uf(t){return t.host&&!If(t.host)&&!kf(t.host)?"bad-host":t.origin&&!Nf(t.origin)&&!t.l7Peer?"bad-origin":"allow"}function Yi(){return async(t,e)=>{let r=Uf({host:t.req.header("host"),origin:t.req.header("origin"),l7Peer:t.req.header(Cf)});if(r!=="allow")return new Response(JSON.stringify({error:"Forbidden",reason:r}),{status:403,headers:{"content-type":"application/json"}});await e()}}var Mf=8e3,Qi=Symbol("nx-cache-get-deadline");function Df(t,e){return e>0?new Promise((r,n)=>{let o=setTimeout(()=>r(Qi),e);t.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),n(s)})}):t}function Ji(t){return t?`hit size=${t.size}`:"miss"}function Hf(t){return t instanceof Error?t.message:String(t)}function bn(t){let e=new ne,r=t.now??(()=>Date.now()),n=t.getDeadlineMs??Mf,o=(s,i,a)=>{s.then(c=>{c?.stream.cancel().catch(()=>{}),t.log?.(`nx get ${i} relay settled after deadline -> ${Ji(c)} (${r()-a}ms)`)},c=>t.log?.(`nx get ${i} relay failed after deadline: ${Hf(c)}`))};return e.get("/blob/nx/v1/cache/:hash",async s=>{let i=s.req.param("hash"),a=r();t.log?.(`nx get ${i} start`);let c=t.blob.get(i,{relay:!0}),l=await Df(c,n);return l===Qi?(t.log?.(`nx get ${i} -> miss deadline=${n}ms (${r()-a}ms, relay continues)`),o(c,i,a),t.respond(s,null)):(t.log?.(`nx get ${i} -> ${Ji(l)} (${r()-a}ms)`),t.respond(s,l))}),e.put("/blob/nx/v1/cache/:hash",async s=>{let i=s.req.param("hash"),a=r(),c=await t.blob.put(s.req.raw.body??Buffer.alloc(0));return await t.blob.bind(i,c),t.log?.(`nx put ${i} -> root=${c} (${r()-a}ms)`),s.body(null,200)}),e}function ea(t){return async(e,r)=>{if(e.req.header("authorization")!==`Bearer ${t}`)return e.body(null,401);await r()}}function nt(t,e){return e?t.body(e.stream,200,{"content-type":"application/octet-stream","content-length":String(e.size)}):t.body(null,404)}function ta(t){let e=new ne;return e.on("HEAD","/blob/objects/:hash",async r=>{let n=await t.get(r.req.param("hash"),{relay:!1});return n?(await n.stream.cancel(),r.body(null,200)):r.body(null,404)}),e.get("/blob/objects/:hash",async r=>{if(r.req.query("raw")==="1"){let o=await t.store.read(r.req.param("hash"));return o?r.body(new Uint8Array(o),200,{"content-type":"application/octet-stream","content-length":String(o.length)}):r.body(null,404)}let n=r.req.query("noRelay")!=="1";return nt(r,await t.get(r.req.param("hash"),{relay:n}))}),e.post("/blob/objects/batch",async r=>{let n=Ws(Buffer.from(await r.req.arrayBuffer()));return!n||n.some(o=>!xe(o.hash))?r.body(null,400):(await t.store.batch(async()=>{for(let o of n)await t.store.write(o.hash,o.data)}),r.json({stored:n.length}))}),e.put("/blob/objects/:hash",async r=>(await t.store.write(r.req.param("hash"),r.req.raw.body??Buffer.alloc(0)),r.body(null,200))),e}function ra(t){let e=new ne;return e.get("/blob/metrics",async r=>{let n=t.metrics.snapshot();return r.json({...n,totalBytes:await t.store.totalBytes()})}),e}var $f=4096;function oa(t){let e=new ne;return e.post("/blob/have",async r=>{let n=await na(r);if(!n)return r.body(null,400);let o=[];return await t.store.batch(async()=>{for(let s of n)await t.store.has(s)||o.push(s)}),r.json({missing:o})}),e.post("/blob/batch",async r=>{let n=await na(r);if(!n)return r.body(null,400);let o={},s=[];for(let i of n){let a=await t.store.read(i);a?o[i]=a.toString("base64"):s.push(i)}return r.json({blobs:o,missing:s})}),e}async function na(t){try{let e=await t.req.json();return!Array.isArray(e)||e.length>$f?null:e.filter(r=>typeof r=="string")}catch{return null}}function sa(t){let e=new ne;return e.get("/blob/aliases/:name",async r=>{let n=await t.store.resolveAlias(r.req.param("name"));return n?r.text(n,200):r.body(null,404)}),e.put("/blob/aliases/:name",async r=>{let n=(await r.req.text()).trim();return _e(n)?(await t.store.setAlias(r.req.param("name"),n),r.body(null,200)):r.body(null,400)}),e}function ia(t){let e=new ne;return e.get("/blob/names/:name",async r=>nt(r,await t.get(r.req.param("name"),{relay:!0}))),e.put("/blob/names/:name",async r=>{let n=await t.put(r.req.raw.body??Buffer.alloc(0));return await t.bind(r.req.param("name"),n),r.body(null,200)}),e}function vt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function he(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function U(t,e,r=""){let n=vt(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function We(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");he(t.outputLen),he(t.blockLen)}function ot(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ca(t,e){U(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Se(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function me(t,e){return t<<32-e|t>>>e}var la=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",qf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function M(t){if(U(t),la)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=qf[t[r]];return e}var Re={_0:48,_9:57,A:65,F:70,a:97,f:102};function aa(t){if(t>=Re._0&&t<=Re._9)return t-Re._0;if(t>=Re.A&&t<=Re.F)return t-(Re.A-10);if(t>=Re.a&&t<=Re.f)return t-(Re.a-10)}function q(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(la)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=aa(t.charCodeAt(s)),a=aa(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Y(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];U(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function ua(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function ge(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var fa=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function ha(t,e,r){return t&e^~t&r}function da(t,e,r){return t&e^t&r^e&r}var ir=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=sr(this.buffer)}update(e){ot(this),U(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=sr(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ot(this),ca(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Se(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)r[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=sr(e),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:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ae=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var jf=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]),ke=new Uint32Array(64),yn=class extends ir{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)ke[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let d=ke[f-15],h=ke[f-2],p=me(d,7)^me(d,18)^d>>>3,b=me(h,17)^me(h,19)^h>>>10;ke[f]=b+ke[f-7]+p+ke[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=me(a,6)^me(a,11)^me(a,25),h=u+d+ha(a,c,l)+jf[f]+ke[f]|0,b=(me(n,2)^me(n,13)^me(n,22))+da(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+b|0}n=n+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(n,o,s,i,a,c,l,u)}roundClean(){Se(ke)}destroy(){this.set(0,0,0,0,0,0,0,0),Se(this.buffer)}},wn=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=ua(()=>new wn,fa(1));var En=BigInt(0),xn=BigInt(1);function Rt(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function pa(t){if(typeof t=="bigint"){if(!ar(t))throw new Error("positive bigint expected, got "+t)}else he(t);return t}function St(t){let e=pa(t).toString(16);return e.length&1?"0"+e:e}function ma(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?En:BigInt("0x"+t)}function Ne(t){return ma(M(t))}function vn(t){return ma(M(Ff(U(t)).reverse()))}function cr(t,e){he(e),t=pa(t);let r=q(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Rn(t,e){return cr(t,e).reverse()}function Ff(t){return Uint8Array.from(t)}function ga(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var ar=t=>typeof t=="bigint"&&En<=t;function Gf(t,e,r){return ar(t)&&ar(e)&&ar(r)&&e<=t&&t<r}function ba(t,e,r,n){if(!Gf(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Sn(t){let e;for(e=0;t>En;t>>=xn,e+=1);return e}var At=t=>(xn<<BigInt(t))-xn;function ya(t,e,r){if(he(t,"hashLen"),he(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),l=n(t),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...m)=>r(l,Y(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,w=[];for(;m<e;){c=d();let v=c.slice();w.push(v),m+=c.length}return Y(...w)};return(m,w)=>{f(),h(m);let v;for(;!(v=w(p()));)h();return f(),v}}function Bt(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,a){let c=t[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])=>n(a,c,i));o(e,!1),o(r,!0)}function An(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}var ce=BigInt(0),ae=BigInt(1),ze=BigInt(2),Ea=BigInt(3),va=BigInt(4),Ra=BigInt(5),Wf=BigInt(7),Sa=BigInt(8),zf=BigInt(9),Aa=BigInt(16);function be(t,e){let r=t%e;return r>=ce?r:e+r}function fe(t,e,r){let n=t;for(;e-- >ce;)n*=n,n%=r;return n}function wa(t,e){if(t===ce)throw new Error("invert: expected non-zero number");if(e<=ce)throw new Error("invert: expected positive modulus, got "+e);let r=be(t,e),n=e,o=ce,s=ae,i=ae,a=ce;for(;r!==ce;){let l=n/r,u=n%r,f=o-i*l,d=s-a*l;n=r,r=u,o=i,s=a,i=f,a=d}if(n!==ae)throw new Error("invert: does not exist");return be(o,e)}function Tn(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Ba(t,e){let r=(t.ORDER+ae)/va,n=t.pow(e,r);return Tn(t,n,e),n}function Vf(t,e){let r=(t.ORDER-Ra)/Sa,n=t.mul(e,ze),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,ze),o),a=t.mul(s,t.sub(i,t.ONE));return Tn(t,a,e),a}function Kf(t){let e=st(t),r=Ta(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Wf)/Aa;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let b=a.eql(a.sqr(u),c),m=a.cmov(l,u,b);return Tn(a,m,c),m}}function Ta(t){if(t<Ea)throw new Error("sqrt is not defined for small field");let e=t-ae,r=0;for(;e%ze===ce;)e/=ze,r++;let n=ze,o=st(t);for(;xa(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Ba;let s=o.pow(n,e),i=(e+ae)/ze;return function(c,l){if(c.is0(l))return l;if(xa(c,l)!==1)throw new Error("Cannot find square root");let u=r,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,b=c.sqr(d);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===u)throw new Error("Cannot find square root");let m=ae<<BigInt(u-p-1),w=c.pow(f,m);u=p,f=c.sqr(w),d=c.mul(d,f),h=c.mul(h,w)}return h}}function Xf(t){return t%va===Ea?Ba:t%Sa===Ra?Vf:t%Aa===zf?Kf(t):Ta(t)}var Zf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ln(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Zf.reduce((n,o)=>(n[o]="function",n),e);return Bt(t,r),t}function Yf(t,e,r){if(r<ce)throw new Error("invalid exponent, negatives unsupported");if(r===ce)return t.ONE;if(r===ae)return e;let n=t.ONE,o=e;for(;r>ce;)r&ae&&(n=t.mul(n,o)),o=t.sqr(o),r>>=ae;return n}function lr(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function xa(t,e){let r=(t.ORDER-ae)/ze,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Jf(t,e){e!==void 0&&he(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Bn=class{ORDER;BITS;BYTES;isLE;ZERO=ce;ONE=ae;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ce)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=Jf(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return be(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ce<=e&&e<this.ORDER}is0(e){return e===ce}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return be(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return be(e*e,this.ORDER)}add(e,r){return be(e+r,this.ORDER)}sub(e,r){return be(e-r,this.ORDER)}mul(e,r){return be(e*r,this.ORDER)}pow(e,r){return Yf(this,e,r)}div(e,r){return be(e*wa(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return wa(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Xf(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Rn(e,this.BYTES):cr(e,this.BYTES)}fromBytes(e,r=!1){U(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?vn(e):Ne(e);if(a&&(c=be(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return lr(this,e)}cmov(e,r,n){return n?r:e}};function st(t,e={}){return new Bn(t,e)}function La(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function On(t){let e=La(t);return e+Math.ceil(e/2)}function ur(t,e,r=!1){U(t);let n=t.length,o=La(e),s=On(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?vn(t):Ne(t),a=be(i,e-ae)+ae;return r?Rn(a,o):cr(a,o)}var it=BigInt(0),Ve=BigInt(1);function Tt(t,e){let r=e.negate();return t?r:e}function In(t,e){let r=lr(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Ca(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pn(t,e){Ca(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=At(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Oa(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Ve);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var _n=new WeakMap,Ia=new WeakMap;function Cn(t){return Ia.get(t)||1}function Pa(t){if(t!==it)throw new Error("invalid wNAF")}var fr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>it;)r&Ve&&(n=n.add(o)),o=o.double(),r>>=Ve;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Pn(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;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(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Pn(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=Oa(n,a,i);n=c,u?s=s.add(Tt(d,r[h])):o=o.add(Tt(f,r[l]))}return Pa(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Pn(e,this.bits);for(let i=0;i<s.windows&&n!==it;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Oa(n,i,s);if(n=a,!l){let f=r[c];o=o.add(u?f.negate():f)}}return Pa(n),o}getPrecomputes(e,r,n){let o=_n.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),_n.set(r,o))),o}cached(e,r,n){let o=Cn(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Cn(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Ca(r,this.bits),Ia.set(e,r),_n.delete(e)}hasCache(e){return Cn(e)!==1}};function ka(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>it||n>it;)r&Ve&&(s=s.add(o)),n&Ve&&(i=i.add(o)),o=o.double(),r>>=Ve,n>>=Ve;return{p1:s,p2:i}}function _a(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ln(e),e}else return st(t,{isLE:r})}function Na(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>it))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_a(e.p,r.Fp,n),s=_a(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function hr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var dr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(We(e),U(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Se(o)}update(e){return ot(this),this.iHash.update(e),this}digestInto(e){ot(this),U(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ue=(t,e,r)=>new dr(t,e).update(r).digest();Ue.create=(t,e)=>new dr(t,e);var Ua=(t,e)=>(t+(t>=0?e:-e)/Ma)/e;function Qf(t,e,r){let[[n,o],[s,i]]=e,a=Ua(i*t,r),c=Ua(-o*t,r),l=t-a*n-c*s,u=-a*o-c*i,f=l<Be,d=u<Be;f&&(l=-l),d&&(u=-u);let h=At(Math.ceil(Sn(r)/2))+at;if(l<Be||l>=h||u<Be||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Nn(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function kn(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Rt(r.lowS,"lowS"),Rt(r.prehash,"prehash"),r.format!==void 0&&Nn(r.format),r}var Un=class extends Error{constructor(e=""){super(e)}},Me={Err:Un,_tlv:{encode:(t,e)=>{let{Err:r}=Me;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=St(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?St(o.length/2|128):"";return St(t)+s+o+e},decode(t,e){let{Err:r}=Me,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Me;if(t<Be)throw new e("integer: negative integers are not allowed");let r=St(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Me;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ne(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Me,o=U(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=Me,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},Be=BigInt(0),at=BigInt(1),Ma=BigInt(2),pr=BigInt(3),eh=BigInt(4);function Da(t,e={}){let r=Na("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Bt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=$a(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(C,x,y){let{x:g,y:R}=x.toAffine(),A=n.toBytes(g);if(Rt(y,"isCompressed"),y){u();let B=!n.isOdd(R);return Y(Ha(B),A)}else return Y(Uint8Array.of(4),A,n.toBytes(R))}function d(C){U(C,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,g=C.length,R=C[0],A=C.subarray(1);if(g===x&&(R===2||R===3)){let B=n.fromBytes(A);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let E=b(B),S;try{S=n.sqrt(E)}catch(F){let $=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+$)}u();let T=n.isOdd(S);return(R&1)===1!==T&&(S=n.neg(S)),{x:B,y:S}}else if(g===y&&R===4){let B=n.BYTES,E=n.fromBytes(A.subarray(0,B)),S=n.fromBytes(A.subarray(B,B*2));if(!m(E,S))throw new Error("bad point: is not on curve");return{x:E,y:S}}else throw new Error(`bad point: got length ${g}, expected compressed=${x} or uncompressed=${y}`)}let h=e.toBytes||f,p=e.fromBytes||d;function b(C){let x=n.sqr(C),y=n.mul(x,C);return n.add(n.add(y,n.mul(C,s.a)),s.b)}function m(C,x){let y=n.sqr(x),g=b(C);return n.eql(y,g)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,pr),eh),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,v)))throw new Error("bad curve params: a or b");function P(C,x,y=!1){if(!n.isValid(x)||y&&n.is0(x))throw new Error(`bad point coordinate ${C}`);return x}function I(C){if(!(C instanceof _))throw new Error("Weierstrass Point expected")}function Z(C){if(!c||!c.basises)throw new Error("no endo");return Qf(C,c.basises,o.ORDER)}let D=An((C,x)=>{let{X:y,Y:g,Z:R}=C;if(n.eql(R,n.ONE))return{x:y,y:g};let A=C.is0();x==null&&(x=A?n.ONE:n.inv(R));let B=n.mul(y,x),E=n.mul(g,x),S=n.mul(R,x);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(S,n.ONE))throw new Error("invZ was invalid");return{x:B,y:E}}),V=An(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x,y}=C.toAffine();if(!n.isValid(x)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!m(x,y))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(C,x,y,g,R){return y=new _(n.mul(y.X,C),y.Y,y.Z),x=Tt(g,x),y=Tt(R,y),x.add(y)}class _{static BASE=new _(s.Gx,s.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,y,g){this.X=P("x",x),this.Y=P("y",y,!0),this.Z=P("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:y,y:g}=x||{};if(!x||!n.isValid(y)||!n.isValid(g))throw new Error("invalid affine point");if(x instanceof _)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(g)?_.ZERO:new _(y,g,n.ONE)}static fromBytes(x){let y=_.fromAffine(p(U(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return _.fromBytes(q(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return H.createCache(this,x),y||this.multiply(pr),this}assertValidity(){V(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){I(x);let{X:y,Y:g,Z:R}=this,{X:A,Y:B,Z:E}=x,S=n.eql(n.mul(y,E),n.mul(A,R)),T=n.eql(n.mul(g,E),n.mul(B,R));return S&&T}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:y}=s,g=n.mul(y,pr),{X:R,Y:A,Z:B}=this,E=n.ZERO,S=n.ZERO,T=n.ZERO,O=n.mul(R,R),F=n.mul(A,A),$=n.mul(B,B),k=n.mul(R,A);return k=n.add(k,k),T=n.mul(R,B),T=n.add(T,T),E=n.mul(x,T),S=n.mul(g,$),S=n.add(E,S),E=n.sub(F,S),S=n.add(F,S),S=n.mul(E,S),E=n.mul(k,E),T=n.mul(g,T),$=n.mul(x,$),k=n.sub(O,$),k=n.mul(x,k),k=n.add(k,T),T=n.add(O,O),O=n.add(T,O),O=n.add(O,$),O=n.mul(O,k),S=n.add(S,O),$=n.mul(A,B),$=n.add($,$),O=n.mul($,k),E=n.sub(E,O),T=n.mul($,F),T=n.add(T,T),T=n.add(T,T),new _(E,S,T)}add(x){I(x);let{X:y,Y:g,Z:R}=this,{X:A,Y:B,Z:E}=x,S=n.ZERO,T=n.ZERO,O=n.ZERO,F=s.a,$=n.mul(s.b,pr),k=n.mul(y,A),G=n.mul(g,B),X=n.mul(R,E),re=n.add(y,g),W=n.add(A,B);re=n.mul(re,W),W=n.add(k,G),re=n.sub(re,W),W=n.add(y,R);let ie=n.add(A,E);return W=n.mul(W,ie),ie=n.add(k,X),W=n.sub(W,ie),ie=n.add(g,R),S=n.add(B,E),ie=n.mul(ie,S),S=n.add(G,X),ie=n.sub(ie,S),O=n.mul(F,W),S=n.mul($,X),O=n.add(S,O),S=n.sub(G,O),O=n.add(G,O),T=n.mul(S,O),G=n.add(k,k),G=n.add(G,k),X=n.mul(F,X),W=n.mul($,W),G=n.add(G,X),X=n.sub(k,X),X=n.mul(F,X),W=n.add(W,X),k=n.mul(G,W),T=n.add(T,k),k=n.mul(ie,W),S=n.mul(re,S),S=n.sub(S,k),k=n.mul(re,G),O=n.mul(ie,O),O=n.add(O,k),new _(S,T,O)}subtract(x){return this.add(x.negate())}is0(){return this.equals(_.ZERO)}multiply(x){let{endo:y}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let g,R,A=B=>H.cached(this,B,E=>In(_,E));if(y){let{k1neg:B,k1:E,k2neg:S,k2:T}=Z(x),{p:O,f:F}=A(E),{p:$,f:k}=A(T);R=F.add(k),g=j(y.beta,O,$,B,S)}else{let{p:B,f:E}=A(x);g=B,R=E}return In(_,[g,R])[0]}multiplyUnsafe(x){let{endo:y}=e,g=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Be||g.is0())return _.ZERO;if(x===at)return g;if(H.hasCache(this))return this.multiply(x);if(y){let{k1neg:R,k1:A,k2neg:B,k2:E}=Z(x),{p1:S,p2:T}=ka(_,g,A,E);return j(y.beta,S,T,R,B)}else return H.unsafe(g,x)}toAffine(x){return D(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===at?!0:x?x(_,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===at?this:x?x(_,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Rt(x,"isCompressed"),this.assertValidity(),h(_,this,x)}toHex(x=!0){return M(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,H=new fr(_,e.endo?Math.ceil(N/2):N);return _.BASE.precompute(8),_}function Ha(t){return Uint8Array.of(t?2:3)}function $a(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function th(t,e={}){let{Fn:r}=t,n=e.randomBytes||ge,o=Object.assign($a(t.Fp,r),{seed:On(r.ORDER)});function s(h){try{let p=r.fromBytes(h);return r.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:b,publicKeyUncompressed:m}=o;try{let w=h.length;return p===!0&&w!==b||p===!1&&w!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return ur(U(h,o.seed,"seed"),r.ORDER)}function c(h,p=!0){return t.BASE.multiply(r.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:b,publicKeyUncompressed:m}=o;if(!vt(h)||"_lengths"in r&&r._lengths||p===b)return;let w=U(h,void 0,"key").length;return w===b||w===m}function u(h,p,b=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(h);return t.fromBytes(p).multiply(m).toBytes(b)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=hr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:t,utils:f,lengths:o})}function qa(t,e,r={}){We(e),Bt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||ge,o=r.hmac||((y,g)=>Ue(e,y,g)),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=th(t,r),p={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=a*Ma<s.ORDER;function m(y){let g=a>>at;return y>g}function w(y,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return g}function v(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(y,g){Nn(g);let R=h.signature,A=g==="compact"?R:g==="recovered"?R+1:void 0;return U(y,A)}class I{r;s;recovery;constructor(g,R,A){if(this.r=w("r",g),this.s=w("s",R),A!=null){if(v(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(g,R=p.format){P(g,R);let A;if(R==="der"){let{r:T,s:O}=Me.toSig(U(g));return new I(T,O)}R==="recovered"&&(A=g[0],R="compact",g=g.subarray(1));let B=h.signature/2,E=g.subarray(0,B),S=g.subarray(B,B*2);return new I(i.fromBytes(E),i.fromBytes(S),A)}static fromHex(g,R){return this.fromBytes(q(g),R)}assertRecovery(){let{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new I(this.r,this.s,g)}recoverPublicKey(g){let{r:R,s:A}=this,B=this.assertRecovery(),E=B===2||B===3?R+a:R;if(!s.isValid(E))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let S=s.toBytes(E),T=t.fromBytes(Y(Ha((B&1)===0),S)),O=i.inv(E),F=D(U(g,void 0,"msgHash")),$=i.create(-F*O),k=i.create(A*O),G=t.BASE.multiplyUnsafe($).add(T.multiplyUnsafe(k));if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return m(this.s)}toBytes(g=p.format){if(Nn(g),g==="der")return q(Me.hexFromSig(this));let{r:R,s:A}=this,B=i.toBytes(R),E=i.toBytes(A);return g==="recovered"?(v(),Y(Uint8Array.of(this.assertRecovery()),B,E)):Y(B,E)}toHex(g){return M(this.toBytes(g))}}let Z=r.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");let R=Ne(g),A=g.length*8-c;return A>0?R>>BigInt(A):R},D=r.bits2int_modN||function(g){return i.create(Z(g))},V=At(c);function j(y){return ba("num < 2^"+c,y,Be,V),i.toBytes(y)}function _(y,g){return U(y,void 0,"message"),g?U(e(y),void 0,"prehashed message"):y}function N(y,g,R){let{lowS:A,prehash:B,extraEntropy:E}=kn(R,p);y=_(y,B);let S=D(y),T=i.fromBytes(g);if(!i.isValidNot0(T))throw new Error("invalid private key");let O=[j(T),j(S)];if(E!=null&&E!==!1){let G=E===!0?n(h.secretKey):E;O.push(U(G,void 0,"extraEntropy"))}let F=Y(...O),$=S;function k(G){let X=Z(G);if(!i.isValidNot0(X))return;let re=i.inv(X),W=t.BASE.multiply(X).toAffine(),ie=i.create(W.x);if(ie===Be)return;let Ut=i.create(re*i.create($+ie*T));if(Ut===Be)return;let Xo=(W.x===ie?0:2)|Number(W.y&at),Zo=Ut;return A&&m(Ut)&&(Zo=i.neg(Ut),Xo^=1),new I(ie,Zo,b?void 0:Xo)}return{seed:F,k2sig:k}}function H(y,g,R={}){let{seed:A,k2sig:B}=N(y,g,R);return ya(e.outputLen,i.BYTES,o)(A,B).toBytes(R.format)}function C(y,g,R,A={}){let{lowS:B,prehash:E,format:S}=kn(A,p);if(R=U(R,void 0,"publicKey"),g=_(g,E),!vt(y)){let T=y instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}P(y,S);try{let T=I.fromBytes(y,S),O=t.fromBytes(R);if(B&&T.hasHighS())return!1;let{r:F,s:$}=T,k=D(g),G=i.inv($),X=i.create(k*G),re=i.create(F*G),W=t.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(re));return W.is0()?!1:i.create(W.x)===F}catch{return!1}}function x(y,g,R={}){let{prehash:A}=kn(R,p);return g=_(g,A),I.fromBytes(y,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:H,verify:C,recoverPublicKey:x,Signature:I,hash:e})}var br={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},rh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},nh=BigInt(0),Mn=BigInt(2);function oh(t){let e=br.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,f=fe(u,r,e)*u%e,d=fe(f,r,e)*u%e,h=fe(d,Mn,e)*l%e,p=fe(h,o,e)*h%e,b=fe(p,s,e)*p%e,m=fe(b,a,e)*b%e,w=fe(m,c,e)*m%e,v=fe(w,a,e)*b%e,P=fe(v,r,e)*u%e,I=fe(P,i,e)*p%e,Z=fe(I,n,e)*l%e,D=fe(Z,Mn,e);if(!mr.eql(mr.sqr(D),t))throw new Error("Cannot find square root");return D}var mr=st(br.p,{sqrt:oh}),Ke=Da(br,{Fp:mr,endo:rh}),Ot=qa(Ke,ee),ja={};function gr(t,...e){let r=ja[t];if(r===void 0){let n=ee(ga(t));r=Y(n,n),ja[t]=r}return ee(Y(r,...e))}var Hn=t=>t.toBytes(!0).slice(1),$n=t=>t%Mn===nh;function Dn(t){let{Fn:e,BASE:r}=Ke,n=e.fromBytes(t),o=r.multiply(n);return{scalar:$n(o.y)?n:e.neg(n),bytes:Hn(o)}}function Ga(t){let e=mr;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),o=e.sqrt(n);$n(o)||(o=e.neg(o));let s=Ke.fromAffine({x:t,y:o});return s.assertValidity(),s}var Lt=Ne;function Wa(...t){return Ke.Fn.create(Lt(gr("BIP0340/challenge",...t)))}function Fa(t){return Dn(t).bytes}function sh(t,e,r=ge(32)){let{Fn:n}=Ke,o=U(t,void 0,"message"),{bytes:s,scalar:i}=Dn(e),a=U(r,32,"auxRand"),c=n.toBytes(i^Lt(gr("BIP0340/aux",a))),l=gr("BIP0340/nonce",c,s,o),{bytes:u,scalar:f}=Dn(l),d=Wa(u,s,o),h=new Uint8Array(64);if(h.set(u,0),h.set(n.toBytes(n.create(f+d*i)),32),!za(h,o,s))throw new Error("sign: Invalid signature produced");return h}function za(t,e,r){let{Fp:n,Fn:o,BASE:s}=Ke,i=U(t,64,"signature"),a=U(e,void 0,"message"),c=U(r,32,"publicKey");try{let l=Ga(Lt(c)),u=Lt(i.subarray(0,32));if(!n.isValidNot0(u))return!1;let f=Lt(i.subarray(32,64));if(!o.isValidNot0(f))return!1;let d=Wa(o.toBytes(u),Hn(l),a),h=s.multiplyUnsafe(f).add(l.multiplyUnsafe(o.neg(d))),{x:p,y:b}=h.toAffine();return!(h.is0()||!$n(b)||p!==u)}catch{return!1}}var ct=(()=>{let r=(n=ge(48))=>ur(n,br.n);return{keygen:hr(r,Fa),getPublicKey:Fa,sign:sh,verify:za,Point:Ke,utils:{randomSecretKey:r,taggedHash:gr,lift_x:Ga,pointToBytes:Hn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Gn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ih(t){if(!Gn(t))throw new Error("Uint8Array expected")}function Za(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function ah(t){if(typeof t!="function")throw new Error("function expected");return!0}function Xe(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Wn(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qn(t){if(!Array.isArray(t))throw new Error("array expected")}function wr(t,e){if(!Za(!0,e))throw new Error(`${t}: array of strings expected`)}function Ya(t,e){if(!Za(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ja(...t){let e=s=>s,r=(s,i)=>a=>s(i(a)),n=t.map(s=>s.encode).reduceRight(r,e),o=t.map(s=>s.decode).reduce(r,e);return{encode:n,decode:o}}function Qa(t){let e=typeof t=="string"?t.split(""):t,r=e.length;wr("alphabet",e);let n=new Map(e.map((o,s)=>[o,s]));return{encode:o=>(qn(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:o=>(qn(o),o.map(s=>{Xe("alphabet.decode",s);let i=n.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return i}))}}function ec(t=""){return Xe("join",t),{encode:e=>(wr("join.decode",e),e.join(t)),decode:e=>(Xe("join.decode",e),e.split(t))}}function ch(t,e="="){return Wn(t),Xe("padding",e),{encode(r){for(wr("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){wr("padding.decode",r);let n=r.length;if(n*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if((n-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}var tc=(t,e)=>e===0?t:tc(e,t%e),xr=(t,e)=>t+(e-tc(t,e)),yr=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function jn(t,e,r,n){if(qn(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(xr(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${xr(e,r)}`);let o=0,s=0,i=yr[e],a=yr[r]-1,c=[];for(let l of t){if(Wn(l),l>=i)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=r;s-=r)c.push((o>>s-r&a)>>>0);let u=yr[s];if(u===void 0)throw new Error("invalid carry");o&=u-1}if(o=o<<r-s&a,!n&&s>=e)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&s>0&&c.push(o>>>0),c}function rc(t,e=!1){if(Wn(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(xr(8,t)>32||xr(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Gn(r))throw new Error("radix2.encode input should be Uint8Array");return jn(Array.from(r),8,t,!e)},decode:r=>(Ya("radix2.decode",r),Uint8Array.from(jn(r,t,8,e)))}}function Va(t){return ah(t),function(...e){try{return t.apply(null,e)}catch{}}}var lh=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",uh=(t,e)=>{Xe("base64",t);let r=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,n=e?"base64url":"base64";if(t.length>0&&!r.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:n,lastChunkHandling:"strict"})},ye=lh?{encode(t){return ih(t),t.toBase64()},decode(t){return uh(t,!1)}}:Ja(rc(6),Qa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ch(6),ec(""));var Fn=Ja(Qa("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ec("")),Ka=[996825010,642813549,513874426,1027748829,705979059];function Pt(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<Ka.length;n++)(e>>n&1)===1&&(r^=Ka[n]);return r}function Xa(t,e,r=1){let n=t.length,o=1;for(let s=0;s<n;s++){let i=t.charCodeAt(s);if(i<33||i>126)throw new Error(`Invalid prefix (${t})`);o=Pt(o)^i>>5}o=Pt(o);for(let s=0;s<n;s++)o=Pt(o)^t.charCodeAt(s)&31;for(let s of e)o=Pt(o)^s;for(let s=0;s<6;s++)o=Pt(o);return o^=r,Fn.encode(jn([o%yr[30]],30,5,!1))}function fh(t){let e=t==="bech32"?1:734539939,r=rc(5),n=r.decode,o=r.encode,s=Va(n);function i(f,d,h=90){Xe("bech32.encode prefix",f),Gn(d)&&(d=Array.from(d)),Ya("bech32.encode",d);let p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);let b=p+7+d.length;if(h!==!1&&b>h)throw new TypeError(`Length ${b} exceeds limit ${h}`);let m=f.toLowerCase(),w=Xa(m,d,e);return`${m}1${Fn.encode(d)}${w}`}function a(f,d=90){Xe("bech32.decode input",f);let h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);let p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let b=p.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');let m=p.slice(0,b),w=p.slice(b+1);if(w.length<6)throw new Error("Data must be at least 6 characters long");let v=Fn.decode(w).slice(0,-6),P=Xa(m,v,e);if(!w.endsWith(P))throw new Error(`Invalid checksum in ${f}: expected "${P}"`);return{prefix:m,words:v}}let c=Va(a);function l(f){let{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:n(h)}}function u(f,d){return i(f,o(d))}return{encode:i,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:o}}var De=fh("bech32");function hh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Er(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function _t(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function K(t,e,r=""){let n=hh(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function zn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function nc(t,e){K(t,void 0,"output");let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function J(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function oe(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function oc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var dh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sc(t,e){return t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Vn(t,e){if(sc(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function ic(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Ct(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var It=(t,e)=>{function r(n,...o){if(K(n,void 0,"key"),!dh)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let u=o[0];K(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&K(o[1],void 0,"AAD");let i=e(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");K(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,K(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(K(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(r,t),r};function lt(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!Ze(e))throw new Error("invalid output, must be aligned");return e}function Kn(t,e,r){Er(r);let n=new Uint8Array(16),o=oc(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function Ze(t){return t.byteOffset%4===0}function de(t){return Uint8Array.from(t)}var te=16;var mh=283;function cc(t){if(![16,24,32].includes(t.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+t.length)}function Qn(t){return t<<1^mh&-(t>>7)}function ut(t,e){let r=0;for(;e>0;e>>=1)r^=t&-(e&1),t=Qn(t);return r}var Yn=(()=>{let t=new Uint8Array(256);for(let r=0,n=1;r<256;r++,n^=Qn(n))t[r]=n;let e=new Uint8Array(256);e[0]=99;for(let r=0;r<255;r++){let n=t[255-r];n|=n<<8,e[t[r]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return oe(t),e})(),gh=Yn.map((t,e)=>Yn.indexOf(e)),bh=t=>t<<24|t>>>8,Xn=t=>t<<8|t>>>24;function lc(t,e){if(t.length!==256)throw new Error("Wrong sbox length");let r=new Uint32Array(256).map((l,u)=>e(t[u])),n=r.map(Xn),o=n.map(Xn),s=o.map(Xn),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]=r[l]^n[u],a[f]=o[l]^s[u],c[f]=t[l]<<8|t[u]}return{sbox:t,sbox2:c,T0:r,T1:n,T2:o,T3:s,T01:i,T23:a}}var eo=lc(Yn,t=>ut(t,3)<<24|t<<16|t<<8|ut(t,2)),uc=lc(gh,t=>ut(t,11)<<24|ut(t,13)<<16|ut(t,9)<<8|ut(t,14)),yh=(()=>{let t=new Uint8Array(16);for(let e=0,r=1;e<16;e++,r=Qn(r))t[e]=r;return t})();function to(t){K(t);let e=t.length;cc(t);let{sbox2:r}=eo,n=[];Ze(t)||n.push(t=de(t));let o=J(t),s=o.length,i=c=>Ee(r,c,c,c,c),a=new Uint32Array(e+28);a.set(o);for(let c=s;c<a.length;c++){let l=a[c-1];c%s===0?l=i(bh(l))^yh[c/s-1]:s>6&&c%s===4&&(l=i(l)),a[c]=a[c-s]^l}return oe(...n),a}function wh(t){let e=to(t),r=e.slice(),n=e.length,{sbox2:o}=eo,{T0:s,T1:i,T2:a,T3:c}=uc;for(let l=0;l<n;l+=4)for(let u=0;u<4;u++)r[l+u]=e[n-l-4+u];oe(e);for(let l=4;l<n-4;l++){let u=r[l],f=Ee(o,u,u,u,u);r[l]=s[f&255]^i[f>>>8&255]^a[f>>>16&255]^c[f>>>24]}return r}function He(t,e,r,n,o,s){return t[r<<8&65280|n>>>8&255]^e[o>>>8&65280|s>>>24&255]}function Ee(t,e,r,n,o){return t[e&255|r&65280]|t[n>>>16&255|o>>>16&65280]<<16}function Jn(t,e,r,n,o){let{sbox2:s,T01:i,T23:a}=eo,c=0;e^=t[c++],r^=t[c++],n^=t[c++],o^=t[c++];let l=t.length/4-2;for(let p=0;p<l;p++){let b=t[c++]^He(i,a,e,r,n,o),m=t[c++]^He(i,a,r,n,o,e),w=t[c++]^He(i,a,n,o,e,r),v=t[c++]^He(i,a,o,e,r,n);e=b,r=m,n=w,o=v}let u=t[c++]^Ee(s,e,r,n,o),f=t[c++]^Ee(s,r,n,o,e),d=t[c++]^Ee(s,n,o,e,r),h=t[c++]^Ee(s,o,e,r,n);return{s0:u,s1:f,s2:d,s3:h}}function xh(t,e,r,n,o){let{sbox2:s,T01:i,T23:a}=uc,c=0;e^=t[c++],r^=t[c++],n^=t[c++],o^=t[c++];let l=t.length/4-2;for(let p=0;p<l;p++){let b=t[c++]^He(i,a,e,o,n,r),m=t[c++]^He(i,a,r,e,o,n),w=t[c++]^He(i,a,n,r,e,o),v=t[c++]^He(i,a,o,n,r,e);e=b,r=m,n=w,o=v}let u=t[c++]^Ee(s,e,o,n,r),f=t[c++]^Ee(s,r,e,o,n),d=t[c++]^Ee(s,n,r,e,o),h=t[c++]^Ee(s,o,n,r,e);return{s0:u,s1:f,s2:d,s3:h}}function Eh(t){if(K(t),t.length%te!==0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size "+te)}function vh(t,e,r){K(t);let n=t.length,o=n%te;if(!e&&o!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");Ze(t)||(t=de(t));let s=J(t);if(e){let a=te-o;a||(a=te),n=n+a}r=lt(n,r),Vn(t,r);let i=J(r);return{b:s,o:i,out:r}}function Rh(t,e){if(!e)return t;let r=t.length;if(!r)throw new Error("aes/pcks5: empty ciphertext not allowed");let n=t[r-1];if(n<=0||n>16)throw new Error("aes/pcks5: wrong padding");let o=t.subarray(0,-n);for(let s=0;s<n;s++)if(t[r-s-1]!==n)throw new Error("aes/pcks5: wrong padding");return o}function Sh(t){let e=new Uint8Array(16),r=J(e);e.set(t);let n=te-t.length;for(let o=te-n;o<te;o++)e[o]=n;return r}var ro=It({blockSize:16,nonceLength:16},function(e,r,n={}){let o=!n.disablePadding;return{encrypt(s,i){let a=to(e),{b:c,o:l,out:u}=vh(s,o,i),f=r,d=[a];Ze(f)||d.push(f=de(f));let h=J(f),p=h[0],b=h[1],m=h[2],w=h[3],v=0;for(;v+4<=c.length;)p^=c[v+0],b^=c[v+1],m^=c[v+2],w^=c[v+3],{s0:p,s1:b,s2:m,s3:w}=Jn(a,p,b,m,w),l[v++]=p,l[v++]=b,l[v++]=m,l[v++]=w;if(o){let P=Sh(s.subarray(v*4));p^=P[0],b^=P[1],m^=P[2],w^=P[3],{s0:p,s1:b,s2:m,s3:w}=Jn(a,p,b,m,w),l[v++]=p,l[v++]=b,l[v++]=m,l[v++]=w}return oe(...d),u},decrypt(s,i){Eh(s);let a=wh(e),c=r,l=[a];Ze(c)||l.push(c=de(c));let u=J(c);i=lt(s.length,i),Ze(s)||l.push(s=de(s)),Vn(s,i);let f=J(s),d=J(i),h=u[0],p=u[1],b=u[2],m=u[3];for(let w=0;w+4<=f.length;){let v=h,P=p,I=b,Z=m;h=f[w+0],p=f[w+1],b=f[w+2],m=f[w+3];let{s0:D,s1:V,s2:j,s3:_}=xh(a,h,p,b,m);d[w++]=D^v,d[w++]=V^P,d[w++]=j^I,d[w++]=_^Z}return oe(...l),Rh(i,o)}}});function Ah(t){return t instanceof Uint32Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint32Array"}function Zn(t,e){if(K(e,16,"block"),!Ah(t))throw new Error("_encryptBlock accepts result of expandKeyLE");let r=J(e),{s0:n,s1:o,s2:s,s3:i}=Jn(t,r[0],r[1],r[2],r[3]);return r[0]=n,r[1]=o,r[2]=s,r[3]=i,e}function ac(t){let e=0;for(let r=te-1;r>=0;r--){let n=(t[r]&128)>>>7;t[r]=t[r]<<1|e,e=n}return e&&(t[te-1]^=135),t}function vr(t,e){if(t.length!==e.length)throw new Error("xorBlock: blocks must have same length");for(let r=0;r<t.length;r++)t[r]=t[r]^e[r];return t}var Rr=class{buffer;destroyed;k1;k2;xk;constructor(e){K(e),cc(e),this.xk=to(e),this.buffer=new Uint8Array(0),this.destroyed=!1;let r=new Uint8Array(te);Zn(this.xk,r),this.k1=ac(r),this.k2=ac(new Uint8Array(this.k1))}update(e){let{destroyed:r,buffer:n}=this;if(r)throw new Error("CMAC instance was destroyed");K(e);let o=new Uint8Array(n.length+e.length);return o.set(n),o.set(e,n.length),this.buffer=o,this}digest(){if(this.destroyed)throw new Error("CMAC instance was destroyed");let{buffer:e}=this,r=e.length,n=Math.ceil(r/te),o;n===0?(n=1,o=!1):o=r%te===0;let s=(n-1)*te,i=e.subarray(s),a;if(o)a=vr(new Uint8Array(i),this.k1);else{let l=new Uint8Array(te);l.set(i),l[i.length]=128,a=vr(l,this.k2)}let c=new Uint8Array(te);for(let l=0;l<n-1;l++){let u=e.subarray(l*te,(l+1)*te);vr(c,u),Zn(this.xk,c)}return vr(c,a),Zn(this.xk,c),oe(a),c}destroy(){let{buffer:e,destroyed:r,xk:n,k1:o,k2:s}=this;r||(this.destroyed=!0,oe(e,n,o,s))}},Bh=(t,e)=>new Rr(t).update(e).digest();Bh.create=t=>new Rr(t);var hc=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Th=hc("expand 16-byte k"),Lh=hc("expand 32-byte k"),Oh=J(Th),Ph=J(Lh);function L(t,e){return t<<e|t>>>32-e}function no(t){return t.byteOffset%4===0}var Sr=64,_h=16,dc=2**32-1,fc=Uint32Array.of();function Ch(t,e,r,n,o,s,i,a){let c=o.length,l=new Uint8Array(Sr),u=J(l),f=no(o)&&no(s),d=f?J(o):fc,h=f?J(s):fc;for(let p=0;p<c;i++){if(t(e,r,n,u,i,a),i>=dc)throw new Error("arx: counter overflow");let b=Math.min(Sr,c-p);if(f&&b===Sr){let m=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let w=0,v;w<_h;w++)v=m+w,h[v]=d[v]^u[w];p+=Sr;continue}for(let m=0,w;m<b;m++)w=p+m,s[w]=o[w]^l[m];p+=b}}function oo(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ic({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return _t(o),_t(i),Er(s),Er(r),(a,c,l,u,f=0)=>{K(a,void 0,"key"),K(c,void 0,"nonce"),K(l,void 0,"data");let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),K(u,void 0,"output"),_t(f),f<0||f>=dc)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let h=[],p=a.length,b,m;if(p===32)h.push(b=de(a)),m=Ph;else if(p===16&&r)b=new Uint8Array(32),b.set(a),b.set(a,16),m=Oh,h.push(b);else throw K(a,32,"arx key"),new Error("invalid key size");no(c)||h.push(c=de(c));let w=J(b);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(m,w,J(c.subarray(0,16)),w),c=c.subarray(16)}let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,h.push(c)}let P=J(c);return Ch(t,m,w,P,l,u,f,i),oe(...h),u}}function se(t,e){return t[e++]&255|(t[e++]&255)<<8}var so=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(e){e=de(K(e,32,"key"));let r=se(e,0),n=se(e,2),o=se(e,4),s=se(e,6),i=se(e,8),a=se(e,10),c=se(e,12),l=se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>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]=se(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],h=i[6],p=i[7],b=i[8],m=i[9],w=se(e,r+0),v=se(e,r+2),P=se(e,r+4),I=se(e,r+6),Z=se(e,r+8),D=se(e,r+10),V=se(e,r+12),j=se(e,r+14),_=s[0]+(w&8191),N=s[1]+((w>>>13|v<<3)&8191),H=s[2]+((v>>>10|P<<6)&8191),C=s[3]+((P>>>7|I<<9)&8191),x=s[4]+((I>>>4|Z<<12)&8191),y=s[5]+(Z>>>1&8191),g=s[6]+((Z>>>14|D<<2)&8191),R=s[7]+((D>>>11|V<<5)&8191),A=s[8]+((V>>>8|j<<8)&8191),B=s[9]+(j>>>5|o),E=0,S=E+_*a+N*(5*m)+H*(5*b)+C*(5*p)+x*(5*h);E=S>>>13,S&=8191,S+=y*(5*d)+g*(5*f)+R*(5*u)+A*(5*l)+B*(5*c),E+=S>>>13,S&=8191;let T=E+_*c+N*a+H*(5*m)+C*(5*b)+x*(5*p);E=T>>>13,T&=8191,T+=y*(5*h)+g*(5*d)+R*(5*f)+A*(5*u)+B*(5*l),E+=T>>>13,T&=8191;let O=E+_*l+N*c+H*a+C*(5*m)+x*(5*b);E=O>>>13,O&=8191,O+=y*(5*p)+g*(5*h)+R*(5*d)+A*(5*f)+B*(5*u),E+=O>>>13,O&=8191;let F=E+_*u+N*l+H*c+C*a+x*(5*m);E=F>>>13,F&=8191,F+=y*(5*b)+g*(5*p)+R*(5*h)+A*(5*d)+B*(5*f),E+=F>>>13,F&=8191;let $=E+_*f+N*u+H*l+C*c+x*a;E=$>>>13,$&=8191,$+=y*(5*m)+g*(5*b)+R*(5*p)+A*(5*h)+B*(5*d),E+=$>>>13,$&=8191;let k=E+_*d+N*f+H*u+C*l+x*c;E=k>>>13,k&=8191,k+=y*a+g*(5*m)+R*(5*b)+A*(5*p)+B*(5*h),E+=k>>>13,k&=8191;let G=E+_*h+N*d+H*f+C*u+x*l;E=G>>>13,G&=8191,G+=y*c+g*a+R*(5*m)+A*(5*b)+B*(5*p),E+=G>>>13,G&=8191;let X=E+_*p+N*h+H*d+C*f+x*u;E=X>>>13,X&=8191,X+=y*l+g*c+R*a+A*(5*m)+B*(5*b),E+=X>>>13,X&=8191;let re=E+_*b+N*p+H*h+C*d+x*f;E=re>>>13,re&=8191,re+=y*u+g*l+R*c+A*a+B*(5*m),E+=re>>>13,re&=8191;let W=E+_*m+N*b+H*p+C*h+x*d;E=W>>>13,W&=8191,W+=y*f+g*u+R*l+A*c+B*a,E+=W>>>13,W&=8191,E=(E<<2)+E|0,E=E+S|0,S=E&8191,E=E>>>13,T+=E,s[0]=S,s[1]=T,s[2]=O,s[3]=F,s[4]=$,s[5]=k,s[6]=G,s[7]=X,s[8]=re,s[9]=W}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;oe(n)}update(e){zn(this),K(e),e=de(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){zn(this),nc(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}};function Ih(t){let e=(n,o)=>t(o).update(n).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}var pc=Ih(t=>new so(t));function bc(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],u=e[0],f=e[1],d=e[2],h=e[3],p=e[4],b=e[5],m=e[6],w=e[7],v=o,P=r[0],I=r[1],Z=r[2],D=i,V=a,j=c,_=l,N=u,H=f,C=d,x=h,y=p,g=b,R=m,A=w,B=v,E=P,S=I,T=Z;for(let F=0;F<s;F+=2)D=D+N|0,B=L(B^D,16),y=y+B|0,N=L(N^y,12),D=D+N|0,B=L(B^D,8),y=y+B|0,N=L(N^y,7),V=V+H|0,E=L(E^V,16),g=g+E|0,H=L(H^g,12),V=V+H|0,E=L(E^V,8),g=g+E|0,H=L(H^g,7),j=j+C|0,S=L(S^j,16),R=R+S|0,C=L(C^R,12),j=j+C|0,S=L(S^j,8),R=R+S|0,C=L(C^R,7),_=_+x|0,T=L(T^_,16),A=A+T|0,x=L(x^A,12),_=_+x|0,T=L(T^_,8),A=A+T|0,x=L(x^A,7),D=D+H|0,T=L(T^D,16),R=R+T|0,H=L(H^R,12),D=D+H|0,T=L(T^D,8),R=R+T|0,H=L(H^R,7),V=V+C|0,B=L(B^V,16),A=A+B|0,C=L(C^A,12),V=V+C|0,B=L(B^V,8),A=A+B|0,C=L(C^A,7),j=j+x|0,E=L(E^j,16),y=y+E|0,x=L(x^y,12),j=j+x|0,E=L(E^j,8),y=y+E|0,x=L(x^y,7),_=_+N|0,S=L(S^_,16),g=g+S|0,N=L(N^g,12),_=_+N|0,S=L(S^_,8),g=g+S|0,N=L(N^g,7);let O=0;n[O++]=i+D|0,n[O++]=a+V|0,n[O++]=c+j|0,n[O++]=l+_|0,n[O++]=u+N|0,n[O++]=f+H|0,n[O++]=d+C|0,n[O++]=h+x|0,n[O++]=p+y|0,n[O++]=b+g|0,n[O++]=m+R|0,n[O++]=w+A|0,n[O++]=v+B|0,n[O++]=P+E|0,n[O++]=I+S|0,n[O++]=Z+T|0}function kh(t,e,r,n){let o=t[0],s=t[1],i=t[2],a=t[3],c=e[0],l=e[1],u=e[2],f=e[3],d=e[4],h=e[5],p=e[6],b=e[7],m=r[0],w=r[1],v=r[2],P=r[3];for(let Z=0;Z<20;Z+=2)o=o+c|0,m=L(m^o,16),d=d+m|0,c=L(c^d,12),o=o+c|0,m=L(m^o,8),d=d+m|0,c=L(c^d,7),s=s+l|0,w=L(w^s,16),h=h+w|0,l=L(l^h,12),s=s+l|0,w=L(w^s,8),h=h+w|0,l=L(l^h,7),i=i+u|0,v=L(v^i,16),p=p+v|0,u=L(u^p,12),i=i+u|0,v=L(v^i,8),p=p+v|0,u=L(u^p,7),a=a+f|0,P=L(P^a,16),b=b+P|0,f=L(f^b,12),a=a+f|0,P=L(P^a,8),b=b+P|0,f=L(f^b,7),o=o+l|0,P=L(P^o,16),p=p+P|0,l=L(l^p,12),o=o+l|0,P=L(P^o,8),p=p+P|0,l=L(l^p,7),s=s+u|0,m=L(m^s,16),b=b+m|0,u=L(u^b,12),s=s+u|0,m=L(m^s,8),b=b+m|0,u=L(u^b,7),i=i+f|0,w=L(w^i,16),d=d+w|0,f=L(f^d,12),i=i+f|0,w=L(w^i,8),d=d+w|0,f=L(f^d,7),a=a+c|0,v=L(v^a,16),h=h+v|0,c=L(c^h,12),a=a+c|0,v=L(v^a,8),h=h+v|0,c=L(c^h,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=m,n[I++]=w,n[I++]=v,n[I++]=P}var Ar=oo(bc,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Nh=oo(bc,{counterRight:!1,counterLength:8,extendNonceFn:kh,allowShortKeys:!1});var Uh=new Uint8Array(16),mc=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(Uh.subarray(r))},Mh=new Uint8Array(32);function gc(t,e,r,n,o){o!==void 0&&K(o,void 0,"AAD");let s=t(e,r,Mh),i=Kn(n.length,o?o.length:0,!0),a=pc.create(s);o&&mc(a,o),mc(a,n),a.update(i);let c=a.digest();return oe(s,i),c}var yc=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=lt(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let l=gc(t,e,r,c,n);return i.set(l,a),oe(l),i},decrypt(s,i){i=lt(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=gc(t,e,r,a,n);if(!Ct(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),oe(l),i}}),QE=It({blockSize:64,nonceLength:12,tagLength:16},yc(Ar)),ev=It({blockSize:64,nonceLength:24,tagLength:16},yc(Nh));function xc(t,e,r){return We(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Ue(t,r,e)}var io=Uint8Array.of(0),wc=Uint8Array.of();function Ec(t,e,r,n=32){We(t),he(n,"length");let o=t.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=wc:U(r,void 0,"info");let i=new Uint8Array(s*o),a=Ue.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)io[0]=u+1,c.update(u===0?wc:l).update(r).update(io).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Se(l,io),i.slice(0,n)}var Dh=Object.defineProperty,z=(t,e)=>{for(var r in e)Dh(t,r,{get:e[r],enumerable:!0})},Hh={};z(Hh,{binarySearch:()=>ho,bytesToHex:()=>M,hexToBytes:()=>q,insertEventIntoAscendingList:()=>jh,insertEventIntoDescendingList:()=>qh,isHex32:()=>ue,mergeReverseSortedLists:()=>Fh,normalizeURL:()=>$h,utf8Decoder:()=>Oe,utf8Encoder:()=>pe});var Oe=new TextDecoder("utf-8"),pe=new TextEncoder;function $h(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}function qh(t,e){let[r,n]=ho(t,o=>e.id===o.id?0:e.created_at===o.created_at?-1:o.created_at-e.created_at);return n||t.splice(r,0,e),t}function jh(t,e){let[r,n]=ho(t,o=>e.id===o.id?0:e.created_at===o.created_at?-1:e.created_at-o.created_at);return n||t.splice(r,0,e),t}function ho(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=Math.floor((r+n)/2),s=e(t[o]);if(s===0)return[o,!0];s<0?n=o-1:r=o+1}return[r,!1]}function Fh(t,e){let r=new Array(t.length+e.length);r.length=0;let n=0,o=0,s=[];for(;n<t.length&&o<e.length;){let i;if(t[n]?.created_at>e[o]?.created_at?(i=t[n],n++):(i=e[o],o++),r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}for(;n<t.length;){let i=t[n];if(n++,r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}for(;o<e.length;){let i=e[o];if(o++,r.length>0&&r[r.length-1].created_at===i.created_at){if(s.includes(i.id))continue}else s.length=0;r.push(i),s.push(i.id)}return r}function ue(t){for(let e=0;e<64;e++){let r=t.charCodeAt(e);if(isNaN(r)||r<48||r>102||r>57&&r<97)return!1}return!0}var ft=Symbol("verified"),Gh=t=>t instanceof Object;function po(t){if(!Gh(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!ue(t.pubkey)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let r=t.tags[e];if(!Array.isArray(r))return!1;for(let n=0;n<r.length;n++)if(typeof r[n]!="string")return!1}return!0}var Wh=class{generateSecretKey(){return ct.utils.randomSecretKey()}getPublicKey(t){return M(ct.getPublicKey(t))}finalizeEvent(t,e){let r=t;return r.pubkey=M(ct.getPublicKey(e)),r.id=Tr(r),r.sig=M(ct.sign(q(Tr(r)),e)),r[ft]=!0,r}verifyEvent(t){if(typeof t[ft]=="boolean")return t[ft];try{let e=Tr(t);if(e!==t.id)return t[ft]=!1,!1;let r=ct.verify(q(t.sig),q(e),q(t.pubkey));return t[ft]=r,r}catch{return t[ft]=!1,!1}}};function zh(t){if(!po(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Tr(t){let e=ee(pe.encode(zh(t)));return M(e)}var Pr=new Wh,Vh=Pr.generateSecretKey,mo=Pr.getPublicKey,ve=Pr.finalizeEvent,kt=Pr.verifyEvent,Kh={};z(Kh,{AIEmbeddings:()=>jd,AppCurationSet:()=>Rm,Application:()=>Em,AuthoredPodcasts:()=>jp,BadgeAward:()=>rd,BadgeDefinition:()=>lm,Bid:()=>bd,BidConfirmation:()=>yd,BlobsAuth:()=>em,BlockedRelaysList:()=>Sp,BlossomServerList:()=>Mp,BookmarkList:()=>Ep,Bookmarksets:()=>om,Calendar:()=>$m,CalendarEventRSVP:()=>qm,CashuMintAnnouncement:()=>Jm,CashuWalletEvent:()=>Zp,CashuWalletHistory:()=>ep,CashuWalletTokens:()=>Qd,ChannelCreation:()=>Cc,ChannelHideMessage:()=>Nc,ChannelMessage:()=>kc,ChannelMetadata:()=>Ic,ChannelMuteUser:()=>Uc,ChatMessage:()=>nd,Chess:()=>pd,ClassifiedListing:()=>Om,ClientAuth:()=>Dc,CodeSnippet:()=>Td,CoinjoinPool:()=>Wd,Comment:()=>vd,CommunitiesList:()=>vp,CommunityDefinition:()=>Km,CommunityPostApproval:()=>Kd,ConferenceEvent:()=>Bm,Contacts:()=>Qh,CreateOrUpdateProduct:()=>hm,CreateOrUpdateStall:()=>fm,CuratedVideoSets:()=>im,Curationsets:()=>sm,Date:()=>Dm,DecoupledEncryptionKeyDistribution:()=>Vd,DecoupledKeyAnnouncement:()=>kp,DecoupledKeyClientAnnouncement:()=>zd,DirectMessageRelaysList:()=>Np,DraftClassifiedListing:()=>Pm,DraftEvent:()=>Nm,DraftLong:()=>gm,Emojisets:()=>bm,EncryptedDirectMessage:()=>ed,EventDeletion:()=>td,FavoriteFollowSets:()=>Cp,FavoritePodcasts:()=>Up,FavoriteRelays:()=>Tp,FedimintAnnouncement:()=>Qm,Feed:()=>Mm,FileMessage:()=>ad,FileMetadata:()=>xd,FileServerPreference:()=>Dp,Followsets:()=>tm,ForumThread:()=>sd,GenericRepost:()=>xo,Genericlists:()=>rm,GeocacheListing:()=>Zm,GeocacheLog:()=>tp,GeocacheLogEntry:()=>Ym,GeocacheProofOfFind:()=>rp,GiftWrap:()=>Mc,GitPullRequest:()=>Od,GitPullRequestUpdate:()=>Pd,GoodWikiAuthorList:()=>Hp,GoodWikiRelayList:()=>$p,GroupMetadata:()=>t0,HTTPAuth:()=>Eo,Handlerinformation:()=>Gm,Handlerrecommendation:()=>Fm,Highlights:()=>bp,InteractiveRoom:()=>Am,InterestsList:()=>Op,Interestsets:()=>um,Issue:()=>_d,JobFeedback:()=>Yd,JobRequest:()=>Xd,JobResult:()=>Zd,Label:()=>$d,LegacyNsiteFile:()=>zm,LightningPubRPC:()=>Yp,LinkSet:()=>Um,LiveChatMessage:()=>Bd,LiveEvent:()=>Sm,LongFormArticle:()=>mm,MarketplaceUI:()=>dm,MediaFollows:()=>_p,MediaStarterPacks:()=>a0,MergeRequests:()=>md,Metadata:()=>Yh,ModularArticleContent:()=>wm,ModularArticleHeader:()=>ym,MuteSets:()=>am,Mutelist:()=>yp,NWCWalletInfo:()=>Kp,NWCWalletRequest:()=>Hc,NWCWalletResponse:()=>Jp,NormalVideo:()=>ud,NostrConnect:()=>Qp,NsiteNamed:()=>Xm,NsiteRoot:()=>Xp,NutZap:()=>dp,NutZapInfo:()=>Pp,OpenTimestamps:()=>wd,Patch:()=>Ld,PeerToPeerOrderEvents:()=>e0,Photo:()=>ld,Pinlist:()=>wp,PodcastEpisode:()=>dd,PodcastMetadata:()=>qp,Poll:()=>Ed,PollResponse:()=>gd,PrivateDirectMessage:()=>_c,PrivateEventRelayList:()=>Lp,ProblemTracker:()=>Md,ProductSoldAsAuction:()=>pm,ProfileBadges:()=>cm,ProxyAnnouncement:()=>zp,PublicChatsList:()=>Rp,PublicMessage:()=>hd,Reaction:()=>wo,ReactionToWebsite:()=>cd,RecommendRelay:()=>Jh,Redirects:()=>km,RelayDiscovery:()=>vm,RelayList:()=>xp,RelayMonitorAnnouncement:()=>Fp,RelayReview:()=>jm,RelayReviews:()=>qd,Relaysets:()=>nm,ReleaseArtifactSets:()=>xm,Reply:()=>Cd,Report:()=>Dd,Reporting:()=>Hd,RepositoryAnnouncement:()=>_m,RepositoryState:()=>Cm,Repost:()=>yo,ReservedCashuWalletTokens:()=>Jd,RoomPresence:()=>Gp,Scroll:()=>Sd,Seal:()=>Pc,SearchRelaysList:()=>Ap,ShortTextNote:()=>Oc,ShortVideo:()=>fd,SimpleGroupAdmins:()=>r0,SimpleGroupCreateGroup:()=>ap,SimpleGroupCreateInvite:()=>lp,SimpleGroupDeleteEvent:()=>ip,SimpleGroupDeleteGroup:()=>cp,SimpleGroupEditMetadata:()=>sp,SimpleGroupJoinRequest:()=>up,SimpleGroupLeaveRequest:()=>fp,SimpleGroupList:()=>Bp,SimpleGroupLiveKitParticipants:()=>s0,SimpleGroupMembers:()=>n0,SimpleGroupPutUser:()=>np,SimpleGroupRemoveUser:()=>op,SimpleGroupReply:()=>id,SimpleGroupRoles:()=>o0,SimpleGroupThreadedReply:()=>od,SlideSet:()=>Lm,SoftwareApplication:()=>Wm,StarterPacks:()=>i0,StatusApplied:()=>kd,StatusClosed:()=>Nd,StatusDraft:()=>Ud,StatusOpen:()=>Id,TidalLogin:()=>pp,Time:()=>Hm,Torrent:()=>Fd,TorrentComment:()=>Gd,TransportMethodAnnouncement:()=>Vp,UserEmojiList:()=>Ip,UserGraspList:()=>Wp,UserStatuses:()=>Tm,VideoViewEvent:()=>Vm,Voice:()=>Rd,VoiceComment:()=>Ad,WebBookmarks:()=>c0,WikiArticle:()=>Im,Zap:()=>gp,ZapGoal:()=>hp,ZapRequest:()=>mp,classifyKind:()=>Xh,isAddressableKind:()=>bo,isEphemeralKind:()=>Lc,isKind:()=>Zh,isRegularKind:()=>Tc,isReplaceableKind:()=>go});function Tc(t){return t<1e4&&t!==0&&t!==3}function go(t){return t===0||t===3||1e4<=t&&t<2e4}function Lc(t){return 2e4<=t&&t<3e4}function bo(t){return 3e4<=t&&t<4e4}function Xh(t){return Tc(t)?"regular":go(t)?"replaceable":Lc(t)?"ephemeral":bo(t)?"parameterized":"unknown"}function Zh(t,e){let r=e instanceof Array?e:[e];return po(t)&&r.includes(t.kind)||!1}var Yh=0,Oc=1,Jh=2,Qh=3,ed=4,td=5,yo=6,wo=7,rd=8,nd=9,od=10,sd=11,id=12,Pc=13,_c=14,ad=15,xo=16,cd=17,ld=20,ud=21,fd=22,hd=24,Cc=40,Ic=41,kc=42,Nc=43,Uc=44,dd=54,pd=64,md=818,gd=1018,bd=1021,yd=1022,wd=1040,Mc=1059,xd=1063,Ed=1068,vd=1111,Rd=1222,Sd=1227,Ad=1244,Bd=1311,Td=1337,Ld=1617,Od=1618,Pd=1619,_d=1621,Cd=1622,Id=1630,kd=1631,Nd=1632,Ud=1633,Md=1971,Dd=1984,Hd=1984,$d=1985,qd=1986,jd=1987,Fd=2003,Gd=2004,Wd=2022,zd=4454,Vd=4455,Kd=4550,Xd=5999,Zd=6999,Yd=7e3,Jd=7374,Qd=7375,ep=7376,tp=7516,rp=7517,np=9e3,op=9001,sp=9002,ip=9005,ap=9007,cp=9008,lp=9009,up=9021,fp=9022,hp=9041,dp=9321,pp=9467,mp=9734,gp=9735,bp=9802,yp=1e4,wp=10001,xp=10002,Ep=10003,vp=10004,Rp=10005,Sp=10006,Ap=10007,Bp=10009,Tp=10012,Lp=10013,Op=10015,Pp=10019,_p=10020,Cp=10021,Ip=10030,kp=10044,Np=10050,Up=10054,Mp=10063,Dp=10096,Hp=10101,$p=10102,qp=10154,jp=10164,Fp=10166,Gp=10312,Wp=10317,zp=10377,Vp=11111,Kp=13194,Xp=15128,Zp=17375,Yp=21e3,Dc=22242,Hc=23194,Jp=23195,Qp=24133,em=24242,Eo=27235,tm=3e4,rm=30001,nm=30002,om=30003,sm=30004,im=30005,am=30007,cm=30008,lm=30009,um=30015,fm=30017,hm=30018,dm=30019,pm=30020,mm=30023,gm=30024,bm=30030,ym=30040,wm=30041,xm=30063,Em=30078,vm=30166,Rm=30267,Sm=30311,Am=30312,Bm=30313,Tm=30315,Lm=30388,Om=30402,Pm=30403,_m=30617,Cm=30618,Im=30818,km=30819,Nm=31234,Um=31388,Mm=31890,Dm=31922,Hm=31923,$m=31924,qm=31925,jm=31987,Fm=31989,Gm=31990,Wm=32267,zm=34128,Vm=34237,Km=34550,Xm=35128,Zm=37515,Ym=37516,Jm=38172,Qm=38173,e0=38383,t0=39e3,r0=39001,n0=39002,o0=39003,s0=39004,i0=39089,a0=39092,c0=39701;var l0={};z(l0,{getHex64:()=>vo,getInt:()=>$c,getSubscriptionId:()=>u0,matchEventId:()=>f0,matchEventKind:()=>d0,matchEventPubkey:()=>h0});function vo(t,e){let r=e.length+3,n=t.indexOf(`"${e}":`)+r,o=t.slice(n).indexOf('"')+n+1;return t.slice(o,o+64)}function $c(t,e){let r=e.length,n=t.indexOf(`"${e}":`)+r+3,o=t.slice(n),s=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,s),10)}function u0(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let r=t.slice(e+7+1).indexOf('"');if(r===-1)return null;let n=e+7+1+r,o=t.slice(n+1,80).indexOf('"');if(o===-1)return null;let s=n+1+o;return t.slice(n+1,s)}function f0(t,e){return e===vo(t,"id")}function h0(t,e){return e===vo(t,"pubkey")}function d0(t,e){return e===$c(t,"kind")}var p0={};z(p0,{makeAuthEvent:()=>m0});function m0(t,e){return{kind:Dc,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var g0;try{g0=WebSocket}catch{}var b0=256,lv=b0*2,uv=new TextEncoder;var y0;try{y0=WebSocket}catch{}var w0={};z(w0,{BECH32_REGEX:()=>qc,Bech32MaxSize:()=>Ro,NostrTypeGuard:()=>x0,decode:()=>_r,decodeNostrURI:()=>v0,encodeBytes:()=>Ir,naddrEncode:()=>L0,neventEncode:()=>T0,noteEncode:()=>A0,nprofileEncode:()=>B0,npubEncode:()=>S0,nsecEncode:()=>R0});var x0={isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")},Ro=5e3,qc=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function E0(t){let e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function v0(t){try{return t.startsWith("nostr:")&&(t=t.substring(6)),_r(t)}catch{return{type:"invalid",data:null}}}function _r(t){let{prefix:e,words:r}=De.decode(t,Ro),n=new Uint8Array(De.fromWords(r));switch(e){case"nprofile":{let o=ao(n);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:M(o[0][0]),relays:o[1]?o[1].map(s=>Oe.decode(s)):[]}}}case"nevent":{let o=ao(n);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:M(o[0][0]),relays:o[1]?o[1].map(s=>Oe.decode(s)):[],author:o[2]?.[0]?M(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(M(o[3][0]),16):void 0}}}case"naddr":{let o=ao(n);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:Oe.decode(o[0][0]),pubkey:M(o[2][0]),kind:parseInt(M(o[3][0]),16),relays:o[1]?o[1].map(s=>Oe.decode(s)):[]}}}case"nsec":return{type:e,data:n};case"npub":case"note":return{type:e,data:M(n)};default:throw new Error(`unknown prefix ${e}`)}}function ao(t){let e={},r=t;for(;r.length>0;){if(r.length<2)throw new Error("not enough data to read TLV");let n=r[0],o=r[1],s=r.slice(2,2+o);if(r=r.slice(2+o),s.length<o)throw new Error(`not enough data to read on TLV ${n}`);e[n]=e[n]||[],e[n].push(s)}return e}function R0(t){return Ir("nsec",t)}function S0(t){return Ir("npub",q(t))}function A0(t){return Ir("note",q(t))}function Cr(t,e){let r=De.toWords(e);return De.encode(t,r,Ro)}function Ir(t,e){return Cr(t,e)}function B0(t){let e=So({0:[q(t.pubkey)],1:(t.relays||[]).map(r=>pe.encode(r))});return Cr("nprofile",e)}function T0(t){let e;t.kind!==void 0&&(e=E0(t.kind));let r=So({0:[q(t.id)],1:(t.relays||[]).map(n=>pe.encode(n)),2:t.author?[q(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return Cr("nevent",r)}function L0(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let r=So({0:[pe.encode(t.identifier)],1:(t.relays||[]).map(n=>pe.encode(n)),2:[q(t.pubkey)],3:[new Uint8Array(e)]});return Cr("naddr",r)}function So(t){let e=[];return Object.entries(t).reverse().forEach(([r,n])=>{n.forEach(o=>{let s=new Uint8Array(o.length+2);s.set([parseInt(r)],0),s.set([o.length],1),s.set(o,2),e.push(s)})}),Y(...e)}var O0={};z(O0,{decrypt:()=>P0,encrypt:()=>jc});function jc(t,e,r){let n=t instanceof Uint8Array?t:q(t),o=Ot.getSharedSecret(n,q("02"+e)),s=Fc(o),i=Uint8Array.from(ge(16)),a=pe.encode(r),c=ro(s,i).encrypt(a),l=ye.encode(new Uint8Array(c)),u=ye.encode(new Uint8Array(i.buffer));return`${l}?iv=${u}`}function P0(t,e,r){let n=t instanceof Uint8Array?t:q(t),[o,s]=r.split("?iv="),i=Ot.getSharedSecret(n,q("02"+e)),a=Fc(i),c=ye.decode(s),l=ye.decode(o),u=ro(a,c).decrypt(l);return Oe.decode(u)}function Fc(t){return t.slice(1,33)}var _0={};z(_0,{NIP05_REGEX:()=>Ao,isNip05:()=>C0,isValid:()=>N0,queryProfile:()=>Gc,searchDomain:()=>k0,useFetchImplementation:()=>I0});var Ao=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,C0=t=>Ao.test(t||""),kr;try{kr=fetch}catch{}function I0(t){kr=t}async function k0(t,e=""){try{let r=`https://${t}/.well-known/nostr.json?name=${e}`,n=await kr(r,{redirect:"manual"});if(n.status!==200)throw Error("Wrong response code");return(await n.json()).names}catch{return{}}}async function Gc(t){let e=t.match(Ao);if(!e)return null;let[,r="_",n]=e;try{let o=`https://${n}/.well-known/nostr.json?name=${r}`,s=await kr(o,{redirect:"manual"});if(s.status!==200)throw Error("Wrong response code");let i=await s.json(),a=i.names[r];return a?{pubkey:a,relays:i.relays?.[a]}:null}catch{return null}}async function N0(t,e){let r=await Gc(e);return r?r.pubkey===t:!1}var U0={};z(U0,{parse:()=>M0});function M0(t){let e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]},r,n;for(let o=t.tags.length-1;o>=0;o--){let s=t.tags[o];if(s[0]==="e"&&s[1]&&ue(s[1])){let[i,a,c,l,u]=s,f={id:a,relays:c?[c]:[],author:u&&ue(u)?u:void 0};if(l==="root"){e.root=f;continue}if(l==="reply"){e.reply=f;continue}if(l==="mention"){e.mentions.push(f);continue}r?n=f:r=f,e.mentions.push(f);continue}if(s[0]==="q"&&s[1]&&ue(s[1])){let[i,a,c]=s;e.quotes.push({id:a,relays:c?[c]:[]})}if(s[0]==="p"&&s[1]&&ue(s[1])){e.profiles.push({pubkey:s[1],relays:s[2]?[s[2]]:[]});continue}}return e.root||(e.root=n||r||e.reply),e.reply||(e.reply=r||e.root),[e.reply,e.root].forEach(o=>{if(!o)return;let s=e.mentions.indexOf(o);if(s!==-1&&e.mentions.splice(s,1),o.author){let i=e.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)}}),e.mentions.forEach(o=>{if(o.author){let s=e.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)}}),e}var D0={};z(D0,{fetchRelayInformation:()=>$0,useFetchImplementation:()=>H0});var Wc;try{Wc=fetch}catch{}function H0(t){Wc=t}async function $0(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var q0={};z(q0,{getPow:()=>j0,minePow:()=>G0});function j0(t){let e=0;for(let r=0;r<64;r+=8){let n=parseInt(t.substring(r,r+8),16);if(n===0)e+=32;else{e+=Math.clz32(n);break}}return e}function F0(t){let e=0;for(let r=0;r<t.length;r++){let n=t[r];if(n===0)e+=8;else{e+=Math.clz32(n)-24;break}}return e}function G0(t,e){let r=0,n=t,o=["nonce",r.toString(),e.toString()];for(n.tags.push(o);;){let s=Math.floor(new Date().getTime()/1e3);s!==n.created_at&&(r=0,n.created_at=s),o[1]=(++r).toString();let i=ee(pe.encode(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])));if(F0(i)>=e){n.id=M(i);break}}return n}var W0={};z(W0,{unwrapEvent:()=>rg,unwrapManyEvents:()=>ng,wrapEvent:()=>ol,wrapManyEvents:()=>tg});var z0={};z(z0,{createRumor:()=>el,createSeal:()=>tl,createWrap:()=>rl,unwrapEvent:()=>Io,unwrapManyEvents:()=>nl,wrapEvent:()=>Or,wrapManyEvents:()=>Q0});var V0={};z(V0,{decrypt:()=>Co,encrypt:()=>_o,getConversationKey:()=>Oo,v2:()=>Y0});var Bo=1,To=4294967295,Lo=65536;function Oo(t,e){let r=Ot.getSharedSecret(t,q("02"+e)).subarray(1,33);return xc(ee,r,pe.encode("nip44-v2"))}function zc(t,e){let r=Ec(ee,t,e,76);return{chacha_key:r.subarray(0,32),chacha_nonce:r.subarray(32,44),hmac_key:r.subarray(44,76)}}function Po(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),r=e<=256?32:e/8;return r*(Math.floor((t-1)/r)+1)}function K0(t){if(!Number.isSafeInteger(t)||t<Bo||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function X0(t){if(!Number.isSafeInteger(t)||t<Lo||t>To)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Vc(t){let e=pe.encode(t),r=e.length;if(r<Bo||r>To)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let n=r>=Lo?Y(new Uint8Array([0,0]),X0(r)):K0(r),o=new Uint8Array(Po(r)-r);return Y(n,e,o)}function Kc(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0),n,o;if(r===0){if(n=e.getUint32(2),n<Lo)throw new Error("invalid padding");o=6}else n=r,o=2;let s=t.subarray(o,o+n);if(n<Bo||n>To||s.length!==n||t.length!==o+Po(n))throw new Error("invalid padding");return Oe.decode(s)}function Xc(t,e,r){if(r.length!==32)throw new Error("AAD associated data must be 32 bytes");let n=Y(r,e);return Ue(ee,t,n)}function Z0(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let r;try{r=ye.decode(t)}catch(s){throw new Error("invalid base64: "+s.message)}let n=r.length;if(n<99)throw new Error("invalid data length: "+n);let o=r[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:r.subarray(1,33),ciphertext:r.subarray(33,-32),mac:r.subarray(-32)}}function _o(t,e,r=ge(32)){let{chacha_key:n,chacha_nonce:o,hmac_key:s}=zc(e,r),i=Vc(t),a=Ar(n,o,i),c=Xc(s,a,r);return ye.encode(Y(new Uint8Array([2]),r,a,c))}function Co(t,e){let{nonce:r,ciphertext:n,mac:o}=Z0(t),{chacha_key:s,chacha_nonce:i,hmac_key:a}=zc(e,r),c=Xc(a,n,r);if(!Ct(c,o))throw new Error("invalid MAC");let l=Ar(s,i,n);return Kc(l)}var Y0={utils:{getConversationKey:Oo,calcPaddedLen:Po,pad:Vc,unpad:Kc},encrypt:_o,decrypt:Co},J0=2880*60,Zc=()=>Math.round(Date.now()/1e3),Yc=()=>Math.round(Zc()-Math.random()*J0),Jc=(t,e)=>Oo(t,e),Qc=(t,e,r)=>_o(JSON.stringify(t),Jc(e,r)),vc=(t,e)=>JSON.parse(Co(t.content,Jc(e,t.pubkey)));function el(t,e){let r={created_at:Zc(),content:"",tags:[],...t,pubkey:mo(e)};return r.id=Tr(r),r}function tl(t,e,r){return ve({kind:Pc,content:Qc(t,e,r),created_at:Yc(),tags:[]},e)}function rl(t,e){let r=Vh();return ve({kind:Mc,content:Qc(t,r,e),created_at:Yc(),tags:[["p",e]]},r)}function Or(t,e,r){let n=el(t,e),o=tl(n,e,r);return rl(o,r)}function Q0(t,e,r){if(!r||r.length===0)throw new Error("At least one recipient is required.");let n=mo(e),o=[Or(t,e,n)];return r.forEach(s=>{o.push(Or(t,e,s))}),o}function Io(t,e){let r=vc(t,e);return vc(r,e)}function nl(t,e){let r=[];return t.forEach(n=>{r.push(Io(n,e))}),r.sort((n,o)=>n.created_at-o.created_at),r}function eg(t,e,r,n){let o={created_at:Math.ceil(Date.now()/1e3),kind:_c,tags:[],content:e};return(Array.isArray(t)?t:[t]).forEach(({publicKey:i,relayUrl:a})=>{o.tags.push(a?["p",i,a]:["p",i])}),n&&o.tags.push(["e",n.eventId,n.relayUrl||"","reply"]),r&&o.tags.push(["subject",r]),o}function ol(t,e,r,n,o){let s=eg(e,r,n,o);return Or(s,t,e.publicKey)}function tg(t,e,r,n,o){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:mo(t)},...e].map(i=>ol(t,i,r,n,o))}var rg=Io,ng=nl,og={};z(og,{finishRepostEvent:()=>sg,getRepostedEvent:()=>ig,getRepostedEventPointer:()=>sl});function sg(t,e,r,n){let o,s=[...t.tags??[],["e",e.id,r],["p",e.pubkey]];return e.kind===Oc?o=yo:(o=xo,s.push(["k",String(e.kind)])),ve({kind:o,tags:s,content:t.content===""||e.tags?.find(i=>i[0]==="-")?"":JSON.stringify(e),created_at:t.created_at},n)}function sl(t){if(![yo,xo].includes(t.kind))return;let e,r;for(let n=t.tags.length-1;n>=0&&(e===void 0||r===void 0);n--){let o=t.tags[n];o.length>=2&&(o[0]==="e"&&e===void 0?e=o:o[0]==="p"&&r===void 0&&(r=o))}if(e!==void 0)return{id:e[1],relays:[e[2],r?.[2]].filter(n=>typeof n=="string"),author:r?.[1]}}function ig(t,{skipVerification:e}={}){let r=sl(t);if(r===void 0||t.content==="")return;let n;try{n=JSON.parse(t.content)}catch{return}if(n.id===r.id&&!(!e&&!kt(n)))return n}var ag={};z(ag,{NOSTR_URI_REGEX:()=>ko,parse:()=>lg,test:()=>cg});var ko=new RegExp(`nostr:(${qc.source})`);function cg(t){return typeof t=="string"&&new RegExp(`^${ko.source}$`).test(t)}function lg(t){let e=t.match(new RegExp(`^${ko.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:_r(e[1])}}var ug={};z(ug,{parse:()=>hg});function Rc(t){if(t)return/^\d+$/.test(t)?parseInt(t,10):t}function il(t,e){let r=t.indexOf(":"),n=t.indexOf(":",r+1);if(r===-1||n===-1)return;let o=parseInt(t.slice(0,r),10);if(Number.isNaN(o))return;let s=t.slice(r+1,n);if(ue(s))return{kind:o,pubkey:s,identifier:t.slice(n+1),relays:e?[e]:[]}}function Sc(t){switch(t[0]){case"E":case"e":return!t[1]||!ue(t[1])?void 0:{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&ue(t[3])?t[3]:void 0};case"A":case"a":return t[1]?il(t[1],t[2]):void 0;case"I":case"i":return t[1]?{value:t[1],hint:t[2]}:void 0}}function fg(t){if(t[1]){if(t[1].includes(":"))return il(t[1],t[2]);if(ue(t[1]))return{id:t[1],relays:t[2]?[t[2]]:[],author:t[3]&&ue(t[3])?t[3]:void 0}}}function Ac(t){return t.findLast(e=>e.tagName==="A"||e.tagName==="a")?.pointer||t.findLast(e=>e.tagName==="I"||e.tagName==="i")?.pointer||t.findLast(e=>e.tagName==="E"||e.tagName==="e")?.pointer}function co(t,e){if(!t||!("id"in t)||!t.author)return;let r=e.find(n=>n.pubkey===t.author);!r||!r.relays||(t.relays||(t.relays=[]),r.relays.forEach(n=>{t.relays.indexOf(n)===-1&&t.relays.push(n)}),r.relays=t.relays)}function hg(t){let e={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},r=[],n=[];for(let o of t.tags){if((o[0]==="E"||o[0]==="A"||o[0]==="I")&&o[1]){let s=Sc(o);s&&r.push({tagName:o[0],pointer:s});continue}if((o[0]==="e"||o[0]==="a"||o[0]==="i")&&o[1]){let s=Sc(o);s&&n.push({tagName:o[0],pointer:s});continue}if(o[0]==="K"){e.rootKind=Rc(o[1]);continue}if(o[0]==="k"){e.replyKind=Rc(o[1]);continue}if(o[0]==="q"){let s=fg(o);s&&e.quotes.push(s);continue}(o[0]==="P"||o[0]==="p")&&o[1]&&ue(o[1])&&e.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]})}return e.root=Ac(r),e.reply=Ac(n),co(e.root,e.profiles),co(e.reply,e.profiles),e.quotes.forEach(o=>co(o,e.profiles)),e}var dg={};z(dg,{finishReactionEvent:()=>pg,getReactedEventPointer:()=>mg});function pg(t,e,r){let n=e.tags.filter(o=>o.length>=2&&(o[0]==="e"||o[0]==="p"));return ve({...t,kind:wo,tags:[...t.tags??[],...n,["e",e.id],["p",e.pubkey]],content:t.content??"+"},r)}function mg(t){if(t.kind!==wo)return;let e,r;for(let n=t.tags.length-1;n>=0&&(e===void 0||r===void 0);n--){let o=t.tags[n];o.length>=2&&(o[0]==="e"&&e===void 0?e=o:o[0]==="p"&&r===void 0&&(r=o))}if(!(e===void 0||r===void 0))return{id:e[1],relays:[e[2],r[2]].filter(n=>n!==void 0),author:r[1]}}var gg={};z(gg,{parse:()=>yg});var lo=/\W/m,Bc=/[^\w\/] |[^\w\/]$|$|,| /m,bg=42;function*yg(t){let e=[];if(typeof t!="string"){for(let s=0;s<t.tags.length;s++){let i=t.tags[s];i[0]==="emoji"&&i.length>=3&&e.push({type:"emoji",shortcode:i[1],url:i[2]})}t=t.content}let r=t.length,n=0,o=0;e:for(;o<r;){let s=t.indexOf(":",o),i=t.indexOf("#",o);if(s===-1&&i===-1)break e;if(s===-1||i>=0&&i<s){if(i===0||t[i-1].match(lo)){let a=t.slice(i+1,i+bg).match(lo),c=a?i+1+a.index:r;yield{type:"text",text:t.slice(n,i)},yield{type:"hashtag",value:t.slice(i+1,c)},o=c,n=o;continue e}o=i+1;continue e}if(t.slice(s-5,s)==="nostr"){let a=t.slice(s+60).match(lo),c=a?s+60+a.index:r;try{let l,{data:u,type:f}=_r(t.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}n!==s-5&&(yield{type:"text",text:t.slice(n,s-5)}),yield{type:"reference",pointer:l},o=c,n=o;continue e}catch{o=s+1;continue e}}else if(t.slice(s-5,s)==="https"||t.slice(s-4,s)==="http"){let a=t.slice(s+4).match(Bc),c=a?s+4+a.index:r,l=t[s-1]==="s"?5:4;try{let u=new URL(t.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid url");if(n!==s-l&&(yield{type:"text",text:t.slice(n,s-l)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(u.pathname)){yield{type:"image",url:u.toString()},o=c,n=o;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(u.pathname)){yield{type:"video",url:u.toString()},o=c,n=o;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(u.pathname)){yield{type:"audio",url:u.toString()},o=c,n=o;continue e}yield{type:"url",url:u.toString()},o=c,n=o;continue e}catch{o=c+1;continue e}}else if(t.slice(s-3,s)==="wss"||t.slice(s-2,s)==="ws"){let a=t.slice(s+4).match(Bc),c=a?s+4+a.index:r,l=t[s-1]==="s"?3:2;try{let u=new URL(t.slice(s-l,c));if(u.hostname.indexOf(".")===-1)throw new Error("invalid ws url");n!==s-l&&(yield{type:"text",text:t.slice(n,s-l)}),yield{type:"relay",url:u.toString()},o=c,n=o;continue e}catch{o=c+1;continue e}}else{for(let a=0;a<e.length;a++){let c=e[a];if(t[s+c.shortcode.length+1]===":"&&t.slice(s+1,s+c.shortcode.length+1)===c.shortcode){n!==s&&(yield{type:"text",text:t.slice(n,s)}),yield c,o=s+c.shortcode.length+2,n=o;continue e}}o=s+1;continue e}}n!==r&&(yield{type:"text",text:t.slice(n)})}var wg={};z(wg,{channelCreateEvent:()=>xg,channelHideMessageEvent:()=>Rg,channelMessageEvent:()=>vg,channelMetadataEvent:()=>Eg,channelMuteUserEvent:()=>Sg});var xg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Cc,tags:[...t.tags??[]],content:r,created_at:t.created_at},e)},Eg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Ic,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:r,created_at:t.created_at},e)},vg=(t,e)=>{let r=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&r.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),ve({kind:kc,tags:[...r,...t.tags??[]],content:t.content,created_at:t.created_at},e)},Rg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Nc,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:r,created_at:t.created_at},e)},Sg=(t,e)=>{let r;if(typeof t.content=="object")r=JSON.stringify(t.content);else if(typeof t.content=="string")r=t.content;else return;return ve({kind:Uc,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:r,created_at:t.created_at},e)},Ag={};z(Ag,{EMOJI_SHORTCODE_REGEX:()=>al,matchAll:()=>Bg,regex:()=>No,replaceAll:()=>Tg});var al=/:(\w+):/,No=()=>new RegExp(`\\B${al.source}\\B`,"g");function*Bg(t){let e=t.matchAll(No());for(let r of e)try{let[n,o]=r;yield{shortcode:n,name:o,start:r.index,end:r.index+n.length}}catch{}}function Tg(t,e){return t.replaceAll(No(),(r,n)=>e({shortcode:r,name:n}))}var Lg={};z(Lg,{useFetchImplementation:()=>Og,validateGithub:()=>Pg});var Uo;try{Uo=fetch}catch{}function Og(t){Uo=t}async function Pg(t,e,r){try{return await(await Uo(`https://gist.github.com/${e}/${r}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch{return!1}}var _g={};z(_g,{makeNwcRequestEvent:()=>Ig,parseConnectionString:()=>Cg});function Cg(t){let{host:e,pathname:r,searchParams:n}=new URL(t),o=r||e,s=n.getAll("relay"),i=n.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 Ig(t,e,r){let o=jc(e,t,JSON.stringify({method:"pay_invoice",params:{invoice:r}})),s={kind:Hc,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",t]]};return ve(s,e)}var kg={};z(kg,{normalizeIdentifier:()=>Ng});function Ng(t){return t=t.trim().toLowerCase(),t=t.normalize("NFKC"),Array.from(t).map(e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-").join("")}var Ug={};z(Ug,{getSatoshisAmountFromBolt11:()=>jg,getZapEndpoint:()=>Dg,makeZapReceipt:()=>qg,makeZapRequest:()=>Hg,useFetchImplementation:()=>Mg,validateZapRequest:()=>$g});var Mo;try{Mo=fetch}catch{}function Mg(t){Mo=t}async function Dg(t){try{let e="",{lud06:r,lud16:n}=JSON.parse(t.content);if(n){let[i,a]=n.split("@");e=new URL(`/.well-known/lnurlp/${i}`,`https://${a}`).toString()}else if(r){let{words:i}=De.decode(r,1e3),a=De.fromWords(i);e=Oe.decode(a)}else return null;let s=await(await Mo(e)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function Hg(t){let e={kind:9734,created_at:Math.round(Date.now()/1e3),content:t.comment||"",tags:[["p","pubkey"in t?t.pubkey:t.event.pubkey],["amount",t.amount.toString()],["relays",...t.relays]]};if("event"in t){if(e.tags.push(["e",t.event.id]),go(t.event.kind)){let r=["a",`${t.event.kind}:${t.event.pubkey}:`];e.tags.push(r)}else if(bo(t.event.kind)){let r=t.event.tags.find(([o,s])=>o==="d"&&s);if(!r)throw new Error("d tag not found or is empty");let n=["a",`${t.event.kind}:${t.event.pubkey}:${r[1]}`];e.tags.push(n)}e.tags.push(["k",t.event.kind.toString()])}return e}function $g(t){let e;try{e=JSON.parse(t)}catch{return"Invalid zap request JSON."}if(!po(e))return"Zap request is not a valid Nostr event.";if(!kt(e))return"Invalid signature on zap request.";let r=e.tags.find(([s,i])=>s==="p"&&i);if(!r)return"Zap request doesn't have a 'p' tag.";if(!ue(r[1]))return"Zap request 'p' tag is not valid hex.";let n=e.tags.find(([s,i])=>s==="e"&&i);return n&&!ue(n[1])?"Zap request 'e' tag is not valid hex.":e.tags.find(([s,i])=>s==="relays"&&i)?null:"Zap request doesn't have a 'relays' tag."}function qg({zapRequest:t,preimage:e,bolt11:r,paidAt:n}){let o=JSON.parse(t),s=o.tags.filter(([a])=>a==="e"||a==="p"||a==="a"),i={kind:9735,created_at:Math.round(n.getTime()/1e3),content:"",tags:[...s,["P",o.pubkey],["bolt11",r],["description",t]]};return e&&i.tags.push(["preimage",e]),i}function jg(t){if(t.length<50)return 0;t=t.substring(0,50);let e=t.lastIndexOf("1");if(e===-1)return 0;let r=t.substring(0,e);if(!r.startsWith("lnbc"))return 0;let n=r.substring(4);if(n.length<1)return 0;let o=n[n.length-1],s=o.charCodeAt(0)-48,i=s>=0&&s<=9,a=n.length-1;if(i&&a++,a<1)return 0;let c=parseInt(n.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 Fg={};z(Fg,{Negentropy:()=>ll,NegentropyStorageVector:()=>zg,NegentropySync:()=>Vg});var uo=97,ht=32,cl=16,Ye={Skip:0,Fingerprint:1,IdList:2},Le=class{_raw;length;constructor(t){typeof t=="number"?(this._raw=new Uint8Array(t),this.length=0):t instanceof Uint8Array?(this._raw=new Uint8Array(t),this.length=t.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(t){if(t instanceof Le&&(t=t.unwrap()),typeof t.length!="number")throw Error("bad length");let e=t.length+this.length;if(this.capacity<e){let r=this._raw,n=Math.max(this.capacity*2,e);this._raw=new Uint8Array(n),this._raw.set(r)}this._raw.set(t,this.length),this.length+=t.length}shift(){let t=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,t}shiftN(t=1){let e=this._raw.subarray(0,t);return this._raw=this._raw.subarray(t),this.length-=t,e}};function Br(t){let e=0;for(;;){if(t.length===0)throw Error("parse ends prematurely");let r=t.shift();if(e=e<<7|r&127,(r&128)===0)break}return e}function Te(t){if(t===0)return new Le(new Uint8Array([0]));let e=[];for(;t!==0;)e.push(t&127),t>>>=7;e.reverse();for(let r=0;r<e.length-1;r++)e[r]|=128;return new Le(new Uint8Array(e))}function Gg(t){return Lr(t,1)[0]}function Lr(t,e){if(t.length<e)throw Error("parse ends prematurely");return t.shiftN(e)}var Wg=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(ht)}add(t){let e=0,r=0,n=new DataView(this.buf.buffer),o=new DataView(t.buffer);for(let s=0;s<8;s++){let i=s*4,a=n.getUint32(i,!0),c=o.getUint32(i,!0),l=a;l+=e,l+=c,l>4294967295&&(r=1),n.setUint32(i,l&4294967295,!0),e=r,r=0}}negate(){let t=new DataView(this.buf.buffer);for(let r=0;r<8;r++){let n=r*4;t.setUint32(n,~t.getUint32(n,!0))}let e=new Uint8Array(ht);e[0]=1,this.add(e)}getFingerprint(t){let e=new Le;return e.extend(this.buf),e.extend(Te(t)),ee(e.unwrap()).subarray(0,cl)}},zg=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(t,e){if(this.sealed)throw Error("already sealed");let r=q(e);if(r.byteLength!==ht)throw Error("bad id size for added item");this.items.push({timestamp:t,id:r})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(fo);for(let t=1;t<this.items.length;t++)if(fo(this.items[t-1],this.items[t])===0)throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(t){if(this._checkSealed(),t>=this.items.length)throw Error("out of range");return this.items[t]}iterate(t,e,r){this._checkSealed(),this._checkBounds(t,e);for(let n=t;n<e&&r(this.items[n],n);++n);}findLowerBound(t,e,r){return this._checkSealed(),this._checkBounds(t,e),this._binarySearch(this.items,t,e,n=>fo(n,r)<0)}fingerprint(t,e){let r=new Wg;return r.setToZero(),this.iterate(t,e,n=>(r.add(n.id),!0)),r.getFingerprint(e-t)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(t,e){if(t>e||e>this.items.length)throw Error("bad range")}_binarySearch(t,e,r,n){let o=r-e;for(;o>0;){let s=e,i=Math.floor(o/2);s+=i,n(t[s])?(e=++s,o-=i+1):o=i}return e}},ll=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(t,e=6e4){if(e<4096)throw Error("frameSizeLimit too small");this.storage=t,this.frameSizeLimit=e,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(t,e){return{timestamp:t,id:e||new Uint8Array(0)}}initiate(){let t=new Le;return t.extend(new Uint8Array([uo])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),t),M(t.unwrap())}reconcile(t,e,r){let n=new Le(q(t));this.lastTimestampIn=this.lastTimestampOut=0;let o=new Le;o.extend(new Uint8Array([uo]));let s=Gg(n);if(s<96||s>111)throw Error("invalid negentropy protocol version byte");if(s!==uo)throw Error("unsupported negentropy protocol version requested: "+(s-96));let i=this.storage.size(),a=this._bound(0),c=0,l=!1;for(;n.length!==0;){let u=new Le,f=()=>{l&&(l=!1,u.extend(this.encodeBound(a)),u.extend(Te(Ye.Skip)))},d=this.decodeBound(n),h=Br(n),p=c,b=this.storage.findLowerBound(c,i,d);if(h===Ye.Skip)l=!0;else if(h===Ye.Fingerprint){let m=Lr(n,cl),w=this.storage.fingerprint(p,b);ul(m,w)!==0?(f(),this.splitRange(p,b,d,u)):l=!0}else if(h===Ye.IdList){let m=Br(n),w={};for(let v=0;v<m;v++){let P=Lr(n,ht);w[M(P)]=P}if(l=!0,this.storage.iterate(p,b,v=>{let P=v.id,I=M(P);return w[I]?delete w[M(P)]:e?.(I),!0}),r)for(let v of Object.values(w))r(M(v))}else throw Error("unexpected mode");if(this.exceededFrameSizeLimit(o.length+u.length)){let m=this.storage.fingerprint(b,i);o.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),o.extend(Te(Ye.Fingerprint)),o.extend(m);break}else o.extend(u);c=b,a=d}return o.length===1?null:M(o.unwrap())}splitRange(t,e,r,n){let o=e-t,s=16;if(o<s*2)n.extend(this.encodeBound(r)),n.extend(Te(Ye.IdList)),n.extend(Te(o)),this.storage.iterate(t,e,i=>(n.extend(i.id),!0));else{let i=Math.floor(o/s),a=o%s,c=t;for(let l=0;l<s;l++){let u=i+(l<a?1:0),f=this.storage.fingerprint(c,c+u);c+=u;let d;if(c===e)d=r;else{let h,p;this.storage.iterate(c-1,c+1,(b,m)=>(m===c-1?h=b:p=b,!0)),d=this.getMinimalBound(h,p)}n.extend(this.encodeBound(d)),n.extend(Te(Ye.Fingerprint)),n.extend(f)}}}exceededFrameSizeLimit(t){return t>this.frameSizeLimit-200}decodeTimestampIn(t){let e=Br(t);return e=e===0?Number.MAX_VALUE:e-1,this.lastTimestampIn===Number.MAX_VALUE||e===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(e+=this.lastTimestampIn,this.lastTimestampIn=e,e)}decodeBound(t){let e=this.decodeTimestampIn(t),r=Br(t);if(r>ht)throw Error("bound key too long");let n=Lr(t,r);return{timestamp:e,id:n}}encodeTimestampOut(t){if(t===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,Te(0);let e=t;return t-=this.lastTimestampOut,this.lastTimestampOut=e,Te(t+1)}encodeBound(t){let e=new Le;return e.extend(this.encodeTimestampOut(t.timestamp)),e.extend(Te(t.id.length)),e.extend(t.id),e}getMinimalBound(t,e){if(e.timestamp!==t.timestamp)return this._bound(e.timestamp);{let r=0,n=e.id,o=t.id;for(let s=0;s<ht&&n[s]===o[s];s++)r++;return this._bound(e.timestamp,e.id.subarray(0,r+1))}}};function ul(t,e){for(let r=0;r<t.byteLength;r++){if(t[r]<e[r])return-1;if(t[r]>e[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength<e.byteLength?-1:0}function fo(t,e){return t.timestamp===e.timestamp?ul(t.id,e.id):t.timestamp-e.timestamp}var Vg=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(t,e,r,n={}){this.relay=t,this.storage=e,this.neg=new ll(e),this.onhave=n.onhave,this.onneed=n.onneed,this.filter=r,this.subscription=this.relay.prepareSubscription([{}],{label:n.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(),n.onclose?.())}catch(s){console.error("negentropy reconcile error:",s),n?.onclose?.(`reconcile error: ${s}`)}break}case"NEG-CLOSE":{let s=o[2];console.warn("negentropy error:",s),n.onclose?.(s);break}case"NEG-ERR":n.onclose?.()}}}async start(){let t=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${t}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},Kg={};z(Kg,{getToken:()=>Xg,hashPayload:()=>Do,unpackEventFromToken:()=>hl,validateEvent:()=>yl,validateEventKind:()=>pl,validateEventMethodTag:()=>gl,validateEventPayloadTag:()=>bl,validateEventTimestamp:()=>dl,validateEventUrlTag:()=>ml,validateToken:()=>Zg});var fl="Nostr ";async function Xg(t,e,r,n=!1,o){let s={kind:Eo,tags:[["u",t],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};o&&s.tags.push(["payload",Do(o)]);let i=await r(s);return(n?fl:"")+ye.encode(pe.encode(JSON.stringify(i)))}async function Zg(t,e,r){let n=await hl(t).catch(s=>{throw s});return await yl(n,e,r).catch(s=>{throw s})}async function hl(t){if(!t)throw new Error("Missing token");t=t.replace(fl,"");let e=Oe.decode(ye.decode(t));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function dl(t){return t.created_at?Math.round(new Date().getTime()/1e3)-t.created_at<60:!1}function pl(t){return t.kind===Eo}function ml(t,e){let r=t.tags.find(n=>n[0]==="u");return r?r.length>0&&r[1]===e:!1}function gl(t,e){let r=t.tags.find(n=>n[0]==="method");return r?r.length>0&&r[1].toLowerCase()===e.toLowerCase():!1}function Do(t){let e=ee(pe.encode(JSON.stringify(t)));return M(e)}function bl(t,e){let r=t.tags.find(o=>o[0]==="payload");if(!r)return!1;let n=Do(e);return r.length>0&&r[1]===n}async function yl(t,e,r,n){if(!kt(t))throw new Error("Invalid nostr event, signature invalid");if(!pl(t))throw new Error("Invalid nostr event, kind invalid");if(!dl(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!ml(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!gl(t,r))throw new Error("Invalid nostr event, method tag invalid");if(n&&typeof n=="object"&&Object.keys(n).length>0&&!bl(t,n))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}var wl=24242,Yg=60;function $o(t,e,r){if(!t)return Pe("missing authorization");let[n,o]=t.split(" ");if(n!=="Nostr"||!o)return Pe("authorization scheme must be Nostr");let s=Jg(o);if(!s)return Pe("authorization is not a nostr event");if(s.kind!==wl)return Pe(`authorization kind must be ${wl}`);if(!Ho(s,"t").includes(e))return Pe(`authorization t tag must be ${e}`);let i=Number(Ho(s,"expiration")[0]);return Number.isFinite(i)?i<=r?Pe("authorization expired"):s.created_at>r+Yg?Pe("authorization created in the future"):kt(s)?{ok:!0,pubkey:s.pubkey,hashes:Ho(s,"x")}:Pe("authorization signature is invalid"):Pe("authorization has no expiration")}function qo(t,e){return t.ok&&t.hashes.includes(e)}function Pe(t){return{ok:!1,reason:t}}function Jg(t){try{let e=JSON.parse(Buffer.from(t,"base64").toString("utf8"));return e&&typeof e=="object"&&Array.isArray(e.tags)?e:null}catch{return null}}function Ho(t,e){return t.tags.filter(r=>r[0]===e&&typeof r[1]=="string").map(r=>r[1])}var xl="application/octet-stream",Qg=/^([0-9a-f]{64})(?:\.([A-Za-z0-9]{1,10}))?$/,eb={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/svg+xml":"svg","video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","audio/mpeg":"mp3","audio/ogg":"ogg","application/pdf":"pdf","text/plain":"txt"};function El(t){let e=Qg.exec(t);return e?{sha256:e[1],ext:e[2]??null}:null}function tb(t){return eb[t.split(";")[0].trim().toLowerCase()]??null}function vl(t,e){let r=t.get("x-forwarded-host");if(!r)return new URL(e).origin;let n=t.get("x-forwarded-proto")??"https",o=(t.get("x-forwarded-prefix")??"").replace(/\/+$/,"");return`${n}://${r}${o}`}function jo(t,e){let r=tb(t.type);return{url:`${e}/${t.sha256}${r?`.${r}`:""}`,sha256:t.sha256,size:t.size,type:t.type,uploaded:t.uploaded}}var dt="[0-9a-f]{64}",pt={"access-control-allow-origin":"*","access-control-allow-headers":"Authorization, Content-Type, X-SHA-256, X-Content-Length, X-Content-Type","access-control-allow-methods":"GET, HEAD, PUT, DELETE, OPTIONS","access-control-expose-headers":"X-Reason","access-control-max-age":"86400"};function Tl(t){let e=new ne,r=()=>new Response(null,{status:204,headers:pt});e.options("/upload",r),e.options("/list/:pubkey",r),e.options(`/:sha{${dt}}`,r),e.options(`/:file{${dt}\\.[A-Za-z0-9]+}`,r),e.get("/upload",o=>{if(o.req.method!=="HEAD")return we(404,"use PUT /upload");let s=t.admits(Nr(o.req.header("x-content-length")));return s.ok?new Response(null,{status:200,headers:pt}):we(s.status,s.reason)}),e.put("/upload",async o=>{let s=$o(o.req.header("authorization"),"upload",Bl());if(!s.ok)return we(401,s.reason);let i=t.admits(Nr(o.req.header("content-length")));if(!i.ok)return we(i.status,i.reason);let a=await t.upload(o.req.raw.body??new Blob([]).stream(),{type:o.req.header("content-type")||xl,pubkey:s.pubkey,allowed:c=>qo(s,c)});return a.ok?Al(jo(a.entry,Sl(o))):we(a.status,a.reason)}),e.get(`/list/:pubkey{${dt}}`,o=>{let s=t.list(o.req.param("pubkey"),{since:Nr(o.req.query("since"))??void 0,until:Nr(o.req.query("until"))??void 0});return Al(s.map(i=>jo(i,Sl(o))))});let n=async(o,s)=>{let i=El(s);if(!i)return we(404,"not a sha256");if(o.req.method==="HEAD"){let c=t.head(i.sha256);return c?new Response(null,{status:200,headers:Rl(c)}):we(404,"blob not found")}let a=await t.open(i.sha256);return a?new Response(a.read.stream,{status:200,headers:Rl(a.entry)}):we(404,"blob not found")};return e.get(`/:sha{${dt}}`,o=>n(o,o.req.param("sha"))),e.get(`/:file{${dt}\\.[A-Za-z0-9]+}`,o=>n(o,o.req.param("file"))),e.delete(`/:sha{${dt}}`,async o=>{let s=o.req.param("sha"),i=$o(o.req.header("authorization"),"delete",Bl());return i.ok?qo(i,s)?await t.remove(s,i.pubkey)?new Response(null,{status:200,headers:pt}):we(404,"blob not found for this pubkey"):we(401,"authorization x tag does not match the blob"):we(401,i.reason)}),e}function Rl(t){return{...pt,"content-type":t.type,"content-length":String(t.size),"x-content-type-options":"nosniff","cache-control":"public, max-age=31536000, immutable"}}function Sl(t){return vl(t.req.raw.headers,t.req.url)}function Al(t){return new Response(JSON.stringify(t),{status:200,headers:{...pt,"content-type":"application/json"}})}function we(t,e){return new Response(null,{status:t,headers:{...pt,"x-reason":e}})}function Nr(t){if(t===void 0||t==="")return null;let e=Number(t);return Number.isFinite(e)?e:null}function Bl(){return Math.floor(Date.now()/1e3)}var rb="20.88.0";function Ll(t){let e=new ne;e.use("*",Yi());let r=async()=>{let n=await t.retention.status(),{status:o,...s}=n;return{status:o,store:s,service:"blob",version:rb}};return e.get("/blob/healthz",async n=>n.json(await r())),e.get("/health",async n=>n.json(await r())),t.blossom&&e.route("/",Tl(t.blossom)),e.use("*",ea(t.token)),e.route("/",bn({blob:t.usecase,respond:nt,log:n=>console.log(`[planx-blob] ${n}`),getDeadlineMs:t.nxGetDeadlineMs})),e.route("/",ta(t.usecase)),e.route("/",ra(t.usecase)),e.route("/",oa(t.usecase)),e.route("/",sa(t.usecase)),e.route("/",ia(t.usecase)),e}import{join as nb}from"node:path";var ob="blossom.db",sb=`
48
48
  PRAGMA synchronous = NORMAL;
49
49
  CREATE TABLE IF NOT EXISTS blob (
50
50
  sha256 TEXT PRIMARY KEY NOT NULL,