signet-login 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redirect.js CHANGED
@@ -88,7 +88,7 @@ function cleanupCallbackUrl() {
88
88
  if (typeof window === 'undefined')
89
89
  return;
90
90
  const url = new URL(window.location.href);
91
- const removed = ['pubkey', 'npub', 'signature', 'eventId', 'error', 'warnings', 'fromNP', 'display_name', 't', 'bunker'];
91
+ const removed = ['pubkey', 'npub', 'signature', 'eventId', 'error', 'warnings', 'fromNP', 'display_name', 't', 'bunker', 'avatar_hash', 'avatar_url', 'avatar_key'];
92
92
  let touched = false;
93
93
  for (const key of removed) {
94
94
  if (url.searchParams.has(key)) {
@@ -196,16 +196,37 @@ export function consumeCallback() {
196
196
  const lowerPubkey = pubkey.toLowerCase();
197
197
  const lowerSig = signature.toLowerCase();
198
198
  const lowerEventId = eventId.toLowerCase();
199
+ // Reconstruct the tag list signet-app *actually signed with*. Looking at
200
+ // signet-app/src/lib/signet.ts::signAuthChallenge, the kind-21236 event
201
+ // carries `[challenge, origin]` plus optional avatar metadata. Notably it
202
+ // does NOT include an `app` tag (yet). Including extra tags here breaks
203
+ // the event-ID hash check on any strict server-side verifier — they hash
204
+ // a tuple that includes our reconstruction but the signature was
205
+ // generated over a different tuple.
206
+ //
207
+ // Avatar params arrive on the redirect URL when the persona has an
208
+ // avatar set (see signet-app/src/lib/url-auth.ts::appendUrlAuthExtras).
209
+ // Pull them in the same order signet-app emits them so the canonical
210
+ // serialisation matches what was signed.
211
+ const tags = [
212
+ ['challenge', pending.challenge],
213
+ ['origin', pending.origin],
214
+ ];
215
+ const avatarHash = params.get('avatar_hash');
216
+ const avatarUrl = params.get('avatar_url');
217
+ const avatarKey = params.get('avatar_key');
218
+ if (avatarHash && /^[0-9a-f]{64}$/i.test(avatarHash))
219
+ tags.push(['avatar_hash', avatarHash]);
220
+ if (avatarUrl && avatarUrl.length <= 500)
221
+ tags.push(['avatar_url', avatarUrl]);
222
+ if (avatarKey && /^[0-9a-f]{64}$/i.test(avatarKey))
223
+ tags.push(['avatar_key', avatarKey]);
199
224
  const authEvent = {
200
225
  id: lowerEventId,
201
226
  pubkey: lowerPubkey,
202
227
  kind: 21236,
203
228
  created_at: createdAt,
204
- tags: [
205
- ['challenge', pending.challenge],
206
- ['origin', pending.origin],
207
- ['app', pending.appName],
208
- ],
229
+ tags,
209
230
  content: '',
210
231
  sig: lowerSig,
211
232
  };
@@ -1,18 +1,18 @@
1
- "use strict";var __SignetLoginIIFE=(()=>{var tl=Object.create;var Jt=Object.defineProperty;var nl=Object.getOwnPropertyDescriptor;var rl=Object.getOwnPropertyNames;var ol=Object.getPrototypeOf,il=Object.prototype.hasOwnProperty;var sl=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),al=(t,e)=>{for(var n in e)Jt(t,n,{get:e[n],enumerable:!0})},mi=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rl(e))!il.call(t,o)&&o!==n&&Jt(t,o,{get:()=>e[o],enumerable:!(r=nl(e,o))||r.enumerable});return t};var cl=(t,e,n)=>(n=t!=null?tl(ol(t)):{},mi(e||!t||!t.__esModule?Jt(n,"default",{value:t,enumerable:!0}):n,t)),ll=t=>mi(Jt({},"__esModule",{value:!0}),t);var v=(t,e,n)=>sl(t,typeof e!="symbol"?e+"":e,n);var Ya=X((Lg,Wa)=>{Wa.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var nt=X(xt=>{var Go,mu=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];xt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};xt.getSymbolTotalCodewords=function(e){return mu[e]};xt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};xt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Go=e};xt.isKanjiModeEnabled=function(){return typeof Go<"u"};xt.toSJIS=function(e){return Go(e)}});var Er=X(ve=>{ve.L={bit:1};ve.M={bit:0};ve.Q={bit:3};ve.H={bit:2};function wu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ve.L;case"m":case"medium":return ve.M;case"q":case"quartile":return ve.Q;case"h":case"high":return ve.H;default:throw new Error("Unknown EC Level: "+t)}}ve.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ve.from=function(e,n){if(ve.isValid(e))return e;try{return wu(e)}catch{return n}}});var Fa=X((_g,Xa)=>{function Ja(){this.buffer=[],this.length=0}Ja.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Xa.exports=Ja});var ec=X((Ug,Qa)=>{function wn(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}wn.prototype.set=function(t,e,n,r){let o=t*this.size+e;this.data[o]=n,r&&(this.reservedBit[o]=!0)};wn.prototype.get=function(t,e){return this.data[t*this.size+e]};wn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};wn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Qa.exports=wn});var tc=X(vr=>{var xu=nt().getSymbolSize;vr.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=xu(e),o=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let s=1;s<n-1;s++)i[s]=i[s-1]-o;return i.push(6),i.reverse()};vr.getPositions=function(e){let n=[],r=vr.getRowColCoords(e),o=r.length;for(let i=0;i<o;i++)for(let s=0;s<o;s++)i===0&&s===0||i===0&&s===o-1||i===o-1&&s===0||n.push([r[i],r[s]]);return n}});var oc=X(rc=>{var Eu=nt().getSymbolSize,nc=7;rc.getPositions=function(e){let n=Eu(e);return[[0,0],[n-nc,0],[0,n-nc]]}});var ic=X(F=>{F.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Et={N1:3,N2:3,N3:40,N4:10};F.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};F.from=function(e){return F.isValid(e)?parseInt(e,10):void 0};F.getPenaltyN1=function(e){let n=e.size,r=0,o=0,i=0,s=null,a=null;for(let c=0;c<n;c++){o=i=0,s=a=null;for(let l=0;l<n;l++){let d=e.get(c,l);d===s?o++:(o>=5&&(r+=Et.N1+(o-5)),s=d,o=1),d=e.get(l,c),d===a?i++:(i>=5&&(r+=Et.N1+(i-5)),a=d,i=1)}o>=5&&(r+=Et.N1+(o-5)),i>=5&&(r+=Et.N1+(i-5))}return r};F.getPenaltyN2=function(e){let n=e.size,r=0;for(let o=0;o<n-1;o++)for(let i=0;i<n-1;i++){let s=e.get(o,i)+e.get(o,i+1)+e.get(o+1,i)+e.get(o+1,i+1);(s===4||s===0)&&r++}return r*Et.N2};F.getPenaltyN3=function(e){let n=e.size,r=0,o=0,i=0;for(let s=0;s<n;s++){o=i=0;for(let a=0;a<n;a++)o=o<<1&2047|e.get(s,a),a>=10&&(o===1488||o===93)&&r++,i=i<<1&2047|e.get(a,s),a>=10&&(i===1488||i===93)&&r++}return r*Et.N3};F.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*Et.N4};function vu(t,e,n){switch(t){case F.Patterns.PATTERN000:return(e+n)%2===0;case F.Patterns.PATTERN001:return e%2===0;case F.Patterns.PATTERN010:return n%3===0;case F.Patterns.PATTERN011:return(e+n)%3===0;case F.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case F.Patterns.PATTERN101:return e*n%2+e*n%3===0;case F.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case F.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}F.applyMask=function(e,n){let r=n.size;for(let o=0;o<r;o++)for(let i=0;i<r;i++)n.isReserved(i,o)||n.xor(i,o,vu(e,i,o))};F.getBestMask=function(e,n){let r=Object.keys(F.Patterns).length,o=0,i=1/0;for(let s=0;s<r;s++){n(s),F.applyMask(s,e);let a=F.getPenaltyN1(e)+F.getPenaltyN2(e)+F.getPenaltyN3(e)+F.getPenaltyN4(e);F.applyMask(s,e),a<i&&(i=a,o=s)}return o}});var Yo=X(Wo=>{var rt=Er(),Sr=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Br=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Wo.getBlocksCount=function(e,n){switch(n){case rt.L:return Sr[(e-1)*4+0];case rt.M:return Sr[(e-1)*4+1];case rt.Q:return Sr[(e-1)*4+2];case rt.H:return Sr[(e-1)*4+3];default:return}};Wo.getTotalCodewordsCount=function(e,n){switch(n){case rt.L:return Br[(e-1)*4+0];case rt.M:return Br[(e-1)*4+1];case rt.Q:return Br[(e-1)*4+2];case rt.H:return Br[(e-1)*4+3];default:return}}});var sc=X(Ar=>{var xn=new Uint8Array(512),kr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)xn[n]=e,kr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)xn[n]=xn[n-255]})();Ar.log=function(e){if(e<1)throw new Error("log("+e+")");return kr[e]};Ar.exp=function(e){return xn[e]};Ar.mul=function(e,n){return e===0||n===0?0:xn[kr[e]+kr[n]]}});var ac=X(En=>{var Jo=sc();En.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let o=0;o<e.length;o++)for(let i=0;i<n.length;i++)r[o+i]^=Jo.mul(e[o],n[i]);return r};En.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let o=r[0];for(let s=0;s<n.length;s++)r[s]^=Jo.mul(n[s],o);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};En.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=En.mul(n,new Uint8Array([1,Jo.exp(r)]));return n}});var fc=X(($g,lc)=>{var cc=ac();function Xo(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Xo.prototype.initialize=function(e){this.degree=e,this.genPoly=cc.generateECPolynomial(this.degree)};Xo.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=cc.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){let i=new Uint8Array(this.degree);return i.set(r,o),i}return r};lc.exports=Xo});var Fo=X(uc=>{uc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Qo=X(Ke=>{var dc="[0-9]+",Su="[A-Z $%*+\\-./:]+",vn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";vn=vn.replace(/u/g,"\\u");var Bu="(?:(?![A-Z0-9 $%*+\\-./:]|"+vn+`)(?:.|[\r
2
- ]))+`;Ke.KANJI=new RegExp(vn,"g");Ke.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Ke.BYTE=new RegExp(Bu,"g");Ke.NUMERIC=new RegExp(dc,"g");Ke.ALPHANUMERIC=new RegExp(Su,"g");var ku=new RegExp("^"+vn+"$"),Au=new RegExp("^"+dc+"$"),Ru=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Ke.testKanji=function(e){return ku.test(e)};Ke.testNumeric=function(e){return Au.test(e)};Ke.testAlphanumeric=function(e){return Ru.test(e)}});var ot=X(ie=>{var Cu=Fo(),ei=Qo();ie.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};ie.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};ie.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};ie.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};ie.MIXED={bit:-1};ie.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Cu.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};ie.getBestModeForData=function(e){return ei.testNumeric(e)?ie.NUMERIC:ei.testAlphanumeric(e)?ie.ALPHANUMERIC:ei.testKanji(e)?ie.KANJI:ie.BYTE};ie.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};ie.isValid=function(e){return e&&e.bit&&e.ccBits};function Tu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return ie.NUMERIC;case"alphanumeric":return ie.ALPHANUMERIC;case"kanji":return ie.KANJI;case"byte":return ie.BYTE;default:throw new Error("Unknown mode: "+t)}}ie.from=function(e,n){if(ie.isValid(e))return e;try{return Tu(e)}catch{return n}}});var bc=X(vt=>{var Rr=nt(),Lu=Yo(),hc=Er(),it=ot(),ti=Fo(),pc=7973,gc=Rr.getBCHDigit(pc);function Iu(t,e,n){for(let r=1;r<=40;r++)if(e<=vt.getCapacity(r,n,t))return r}function yc(t,e){return it.getCharCountIndicator(t,e)+4}function Nu(t,e){let n=0;return t.forEach(function(r){let o=yc(r.mode,e);n+=o+r.getBitsLength()}),n}function _u(t,e){for(let n=1;n<=40;n++)if(Nu(t,n)<=vt.getCapacity(n,e,it.MIXED))return n}vt.from=function(e,n){return ti.isValid(e)?parseInt(e,10):n};vt.getCapacity=function(e,n,r){if(!ti.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=it.BYTE);let o=Rr.getSymbolTotalCodewords(e),i=Lu.getTotalCodewordsCount(e,n),s=(o-i)*8;if(r===it.MIXED)return s;let a=s-yc(r,e);switch(r){case it.NUMERIC:return Math.floor(a/10*3);case it.ALPHANUMERIC:return Math.floor(a/11*2);case it.KANJI:return Math.floor(a/13);case it.BYTE:default:return Math.floor(a/8)}};vt.getBestVersionForData=function(e,n){let r,o=hc.from(n,hc.M);if(Array.isArray(e)){if(e.length>1)return _u(e,o);if(e.length===0)return 1;r=e[0]}else r=e;return Iu(r.mode,r.getLength(),o)};vt.getEncodedBits=function(e){if(!ti.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Rr.getBCHDigit(n)-gc>=0;)n^=pc<<Rr.getBCHDigit(n)-gc;return e<<12|n}});var Ec=X(xc=>{var ni=nt(),wc=1335,Uu=21522,mc=ni.getBCHDigit(wc);xc.getEncodedBits=function(e,n){let r=e.bit<<3|n,o=r<<10;for(;ni.getBCHDigit(o)-mc>=0;)o^=wc<<ni.getBCHDigit(o)-mc;return(r<<10|o)^Uu}});var Sc=X((Gg,vc)=>{var Ou=ot();function Kt(t){this.mode=Ou.NUMERIC,this.data=t.toString()}Kt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Kt.prototype.getLength=function(){return this.data.length};Kt.prototype.getBitsLength=function(){return Kt.getBitsLength(this.data.length)};Kt.prototype.write=function(e){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),e.put(o,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),o=parseInt(r,10),e.put(o,i*3+1))};vc.exports=Kt});var kc=X((Wg,Bc)=>{var Hu=ot(),ri=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function zt(t){this.mode=Hu.ALPHANUMERIC,this.data=t}zt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};zt.prototype.getLength=function(){return this.data.length};zt.prototype.getBitsLength=function(){return zt.getBitsLength(this.data.length)};zt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ri.indexOf(this.data[n])*45;r+=ri.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(ri.indexOf(this.data[n]),6)};Bc.exports=zt});var Rc=X((Yg,Ac)=>{var Pu=ot();function jt(t){this.mode=Pu.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}jt.getBitsLength=function(e){return e*8};jt.prototype.getLength=function(){return this.data.length};jt.prototype.getBitsLength=function(){return jt.getBitsLength(this.data.length)};jt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Ac.exports=jt});var Tc=X((Jg,Cc)=>{var Mu=ot(),qu=nt();function Zt(t){this.mode=Mu.KANJI,this.data=t}Zt.getBitsLength=function(e){return e*13};Zt.prototype.getLength=function(){return this.data.length};Zt.prototype.getBitsLength=function(){return Zt.getBitsLength(this.data.length)};Zt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=qu.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
3
- Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Cc.exports=Zt});var Lc=X((Xg,oi)=>{"use strict";var Sn={single_source_shortest_paths:function(t,e,n){var r={},o={};o[e]=0;var i=Sn.PriorityQueue.make();i.push(e,0);for(var s,a,c,l,d,h,f,u,y;!i.empty();){s=i.pop(),a=s.value,l=s.cost,d=t[a]||{};for(c in d)d.hasOwnProperty(c)&&(h=d[c],f=l+h,u=o[c],y=typeof o[c]>"u",(y||u>f)&&(o[c]=f,i.push(c,f),r[c]=a))}if(typeof n<"u"&&typeof o[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,o;r;)n.push(r),o=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Sn.single_source_shortest_paths(t,e,n);return Sn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Sn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof oi<"u"&&(oi.exports=Sn)});var Mc=X(Gt=>{var J=ot(),_c=Sc(),Uc=kc(),Oc=Rc(),Hc=Tc(),Bn=Qo(),Cr=nt(),Du=Lc();function Ic(t){return unescape(encodeURIComponent(t)).length}function kn(t,e,n){let r=[],o;for(;(o=t.exec(n))!==null;)r.push({data:o[0],index:o.index,mode:e,length:o[0].length});return r}function Pc(t){let e=kn(Bn.NUMERIC,J.NUMERIC,t),n=kn(Bn.ALPHANUMERIC,J.ALPHANUMERIC,t),r,o;return Cr.isKanjiModeEnabled()?(r=kn(Bn.BYTE,J.BYTE,t),o=kn(Bn.KANJI,J.KANJI,t)):(r=kn(Bn.BYTE_KANJI,J.BYTE,t),o=[]),e.concat(n,r,o).sort(function(s,a){return s.index-a.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function ii(t,e){switch(e){case J.NUMERIC:return _c.getBitsLength(t);case J.ALPHANUMERIC:return Uc.getBitsLength(t);case J.KANJI:return Hc.getBitsLength(t);case J.BYTE:return Oc.getBitsLength(t)}}function $u(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Vu(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case J.NUMERIC:e.push([r,{data:r.data,mode:J.ALPHANUMERIC,length:r.length},{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.ALPHANUMERIC:e.push([r,{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.KANJI:e.push([r,{data:r.data,mode:J.BYTE,length:Ic(r.data)}]);break;case J.BYTE:e.push([{data:r.data,mode:J.BYTE,length:Ic(r.data)}])}}return e}function Ku(t,e){let n={},r={start:{}},o=["start"];for(let i=0;i<t.length;i++){let s=t[i],a=[];for(let c=0;c<s.length;c++){let l=s[c],d=""+i+c;a.push(d),n[d]={node:l,lastCount:0},r[d]={};for(let h=0;h<o.length;h++){let f=o[h];n[f]&&n[f].node.mode===l.mode?(r[f][d]=ii(n[f].lastCount+l.length,l.mode)-ii(n[f].lastCount,l.mode),n[f].lastCount+=l.length):(n[f]&&(n[f].lastCount=l.length),r[f][d]=ii(l.length,l.mode)+4+J.getCharCountIndicator(l.mode,e))}}o=a}for(let i=0;i<o.length;i++)r[o[i]].end=0;return{map:r,table:n}}function Nc(t,e){let n,r=J.getBestModeForData(t);if(n=J.from(e,r),n!==J.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+J.toString(n)+`.
4
- Suggested mode is: `+J.toString(r));switch(n===J.KANJI&&!Cr.isKanjiModeEnabled()&&(n=J.BYTE),n){case J.NUMERIC:return new _c(t);case J.ALPHANUMERIC:return new Uc(t);case J.KANJI:return new Hc(t);case J.BYTE:return new Oc(t)}}Gt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Nc(r,null)):r.data&&n.push(Nc(r.data,r.mode)),n},[])};Gt.fromString=function(e,n){let r=Pc(e,Cr.isKanjiModeEnabled()),o=Vu(r),i=Ku(o,n),s=Du.find_path(i.map,"start","end"),a=[];for(let c=1;c<s.length-1;c++)a.push(i.table[s[c]].node);return Gt.fromArray($u(a))};Gt.rawSplit=function(e){return Gt.fromArray(Pc(e,Cr.isKanjiModeEnabled()))}});var Dc=X(qc=>{var Lr=nt(),si=Er(),zu=Fa(),ju=ec(),Zu=tc(),Gu=oc(),li=ic(),fi=Yo(),Wu=fc(),Tr=bc(),Yu=Ec(),Ju=ot(),ai=Mc();function Xu(t,e){let n=t.size,r=Gu.getPositions(e);for(let o=0;o<r.length;o++){let i=r[o][0],s=r[o][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let c=-1;c<=7;c++)s+c<=-1||n<=s+c||(a>=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?t.set(i+a,s+c,!0,!0):t.set(i+a,s+c,!1,!0))}}function Fu(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function Qu(t,e){let n=Zu.getPositions(e);for(let r=0;r<n.length;r++){let o=n[r][0],i=n[r][1];for(let s=-2;s<=2;s++)for(let a=-2;a<=2;a++)s===-2||s===2||a===-2||a===2||s===0&&a===0?t.set(o+s,i+a,!0,!0):t.set(o+s,i+a,!1,!0)}}function ed(t,e){let n=t.size,r=Tr.getEncodedBits(e),o,i,s;for(let a=0;a<18;a++)o=Math.floor(a/3),i=a%3+n-8-3,s=(r>>a&1)===1,t.set(o,i,s,!0),t.set(i,o,s,!0)}function ci(t,e,n){let r=t.size,o=Yu.getEncodedBits(e,n),i,s;for(i=0;i<15;i++)s=(o>>i&1)===1,i<6?t.set(i,8,s,!0):i<8?t.set(i+1,8,s,!0):t.set(r-15+i,8,s,!0),i<8?t.set(8,r-i-1,s,!0):i<9?t.set(8,15-i-1+1,s,!0):t.set(8,15-i-1,s,!0);t.set(r-8,8,1,!0)}function td(t,e){let n=t.size,r=-1,o=n-1,i=7,s=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!t.isReserved(o,a-c)){let l=!1;s<e.length&&(l=(e[s]>>>i&1)===1),t.set(o,a-c,l),i--,i===-1&&(s++,i=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function nd(t,e,n){let r=new zu;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),Ju.getCharCountIndicator(c.mode,t)),c.write(r)});let o=Lr.getSymbolTotalCodewords(t),i=fi.getTotalCodewordsCount(t,e),s=(o-i)*8;for(r.getLengthInBits()+4<=s&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(s-r.getLengthInBits())/8;for(let c=0;c<a;c++)r.put(c%2?17:236,8);return rd(r,t,e)}function rd(t,e,n){let r=Lr.getSymbolTotalCodewords(e),o=fi.getTotalCodewordsCount(e,n),i=r-o,s=fi.getBlocksCount(e,n),a=r%s,c=s-a,l=Math.floor(r/s),d=Math.floor(i/s),h=d+1,f=l-d,u=new Wu(f),y=0,m=new Array(s),S=new Array(s),R=0,N=new Uint8Array(t.buffer);for(let j=0;j<s;j++){let Z=j<c?d:h;m[j]=N.slice(y,y+Z),S[j]=u.encode(m[j]),y+=Z,R=Math.max(R,Z)}let _=new Uint8Array(r),M=0,U,D;for(U=0;U<R;U++)for(D=0;D<s;D++)U<m[D].length&&(_[M++]=m[D][U]);for(U=0;U<f;U++)for(D=0;D<s;D++)_[M++]=S[D][U];return _}function od(t,e,n,r){let o;if(Array.isArray(t))o=ai.fromArray(t);else if(typeof t=="string"){let l=e;if(!l){let d=ai.rawSplit(t);l=Tr.getBestVersionForData(d,n)}o=ai.fromString(t,l||40)}else throw new Error("Invalid data");let i=Tr.getBestVersionForData(o,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
1
+ "use strict";var __SignetLoginIIFE=(()=>{var rl=Object.create;var Jt=Object.defineProperty;var ol=Object.getOwnPropertyDescriptor;var il=Object.getOwnPropertyNames;var sl=Object.getPrototypeOf,al=Object.prototype.hasOwnProperty;var cl=(t,e,n)=>e in t?Jt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ll=(t,e)=>{for(var n in e)Jt(t,n,{get:e[n],enumerable:!0})},ki=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of il(e))!al.call(t,o)&&o!==n&&Jt(t,o,{get:()=>e[o],enumerable:!(r=ol(e,o))||r.enumerable});return t};var fl=(t,e,n)=>(n=t!=null?rl(sl(t)):{},ki(e||!t||!t.__esModule?Jt(n,"default",{value:t,enumerable:!0}):n,t)),ul=t=>ki(Jt({},"__esModule",{value:!0}),t);var v=(t,e,n)=>cl(t,typeof e!="symbol"?e+"":e,n);var Xa=X((Ug,Ja)=>{Ja.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var nt=X(xt=>{var ei,vu=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];xt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};xt.getSymbolTotalCodewords=function(e){return vu[e]};xt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};xt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ei=e};xt.isKanjiModeEnabled=function(){return typeof ei<"u"};xt.toSJIS=function(e){return ei(e)}});var Er=X(ve=>{ve.L={bit:1};ve.M={bit:0};ve.Q={bit:3};ve.H={bit:2};function Su(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ve.L;case"m":case"medium":return ve.M;case"q":case"quartile":return ve.Q;case"h":case"high":return ve.H;default:throw new Error("Unknown EC Level: "+t)}}ve.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ve.from=function(e,n){if(ve.isValid(e))return e;try{return Su(e)}catch{return n}}});var ec=X((Pg,Qa)=>{function Fa(){this.buffer=[],this.length=0}Fa.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Qa.exports=Fa});var nc=X((Mg,tc)=>{function wn(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}wn.prototype.set=function(t,e,n,r){let o=t*this.size+e;this.data[o]=n,r&&(this.reservedBit[o]=!0)};wn.prototype.get=function(t,e){return this.data[t*this.size+e]};wn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};wn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};tc.exports=wn});var rc=X(vr=>{var Bu=nt().getSymbolSize;vr.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Bu(e),o=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let s=1;s<n-1;s++)i[s]=i[s-1]-o;return i.push(6),i.reverse()};vr.getPositions=function(e){let n=[],r=vr.getRowColCoords(e),o=r.length;for(let i=0;i<o;i++)for(let s=0;s<o;s++)i===0&&s===0||i===0&&s===o-1||i===o-1&&s===0||n.push([r[i],r[s]]);return n}});var sc=X(ic=>{var ku=nt().getSymbolSize,oc=7;ic.getPositions=function(e){let n=ku(e);return[[0,0],[n-oc,0],[0,n-oc]]}});var ac=X(F=>{F.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Et={N1:3,N2:3,N3:40,N4:10};F.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};F.from=function(e){return F.isValid(e)?parseInt(e,10):void 0};F.getPenaltyN1=function(e){let n=e.size,r=0,o=0,i=0,s=null,a=null;for(let c=0;c<n;c++){o=i=0,s=a=null;for(let l=0;l<n;l++){let d=e.get(c,l);d===s?o++:(o>=5&&(r+=Et.N1+(o-5)),s=d,o=1),d=e.get(l,c),d===a?i++:(i>=5&&(r+=Et.N1+(i-5)),a=d,i=1)}o>=5&&(r+=Et.N1+(o-5)),i>=5&&(r+=Et.N1+(i-5))}return r};F.getPenaltyN2=function(e){let n=e.size,r=0;for(let o=0;o<n-1;o++)for(let i=0;i<n-1;i++){let s=e.get(o,i)+e.get(o,i+1)+e.get(o+1,i)+e.get(o+1,i+1);(s===4||s===0)&&r++}return r*Et.N2};F.getPenaltyN3=function(e){let n=e.size,r=0,o=0,i=0;for(let s=0;s<n;s++){o=i=0;for(let a=0;a<n;a++)o=o<<1&2047|e.get(s,a),a>=10&&(o===1488||o===93)&&r++,i=i<<1&2047|e.get(a,s),a>=10&&(i===1488||i===93)&&r++}return r*Et.N3};F.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*Et.N4};function Au(t,e,n){switch(t){case F.Patterns.PATTERN000:return(e+n)%2===0;case F.Patterns.PATTERN001:return e%2===0;case F.Patterns.PATTERN010:return n%3===0;case F.Patterns.PATTERN011:return(e+n)%3===0;case F.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case F.Patterns.PATTERN101:return e*n%2+e*n%3===0;case F.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case F.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}F.applyMask=function(e,n){let r=n.size;for(let o=0;o<r;o++)for(let i=0;i<r;i++)n.isReserved(i,o)||n.xor(i,o,Au(e,i,o))};F.getBestMask=function(e,n){let r=Object.keys(F.Patterns).length,o=0,i=1/0;for(let s=0;s<r;s++){n(s),F.applyMask(s,e);let a=F.getPenaltyN1(e)+F.getPenaltyN2(e)+F.getPenaltyN3(e)+F.getPenaltyN4(e);F.applyMask(s,e),a<i&&(i=a,o=s)}return o}});var ni=X(ti=>{var rt=Er(),Sr=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Br=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];ti.getBlocksCount=function(e,n){switch(n){case rt.L:return Sr[(e-1)*4+0];case rt.M:return Sr[(e-1)*4+1];case rt.Q:return Sr[(e-1)*4+2];case rt.H:return Sr[(e-1)*4+3];default:return}};ti.getTotalCodewordsCount=function(e,n){switch(n){case rt.L:return Br[(e-1)*4+0];case rt.M:return Br[(e-1)*4+1];case rt.Q:return Br[(e-1)*4+2];case rt.H:return Br[(e-1)*4+3];default:return}}});var cc=X(Ar=>{var xn=new Uint8Array(512),kr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)xn[n]=e,kr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)xn[n]=xn[n-255]})();Ar.log=function(e){if(e<1)throw new Error("log("+e+")");return kr[e]};Ar.exp=function(e){return xn[e]};Ar.mul=function(e,n){return e===0||n===0?0:xn[kr[e]+kr[n]]}});var lc=X(En=>{var ri=cc();En.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let o=0;o<e.length;o++)for(let i=0;i<n.length;i++)r[o+i]^=ri.mul(e[o],n[i]);return r};En.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let o=r[0];for(let s=0;s<n.length;s++)r[s]^=ri.mul(n[s],o);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};En.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=En.mul(n,new Uint8Array([1,ri.exp(r)]));return n}});var dc=X((jg,uc)=>{var fc=lc();function oi(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}oi.prototype.initialize=function(e){this.degree=e,this.genPoly=fc.generateECPolynomial(this.degree)};oi.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=fc.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){let i=new Uint8Array(this.degree);return i.set(r,o),i}return r};uc.exports=oi});var ii=X(hc=>{hc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var si=X(Ke=>{var gc="[0-9]+",Ru="[A-Z $%*+\\-./:]+",vn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";vn=vn.replace(/u/g,"\\u");var Cu="(?:(?![A-Z0-9 $%*+\\-./:]|"+vn+`)(?:.|[\r
2
+ ]))+`;Ke.KANJI=new RegExp(vn,"g");Ke.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Ke.BYTE=new RegExp(Cu,"g");Ke.NUMERIC=new RegExp(gc,"g");Ke.ALPHANUMERIC=new RegExp(Ru,"g");var Tu=new RegExp("^"+vn+"$"),Lu=new RegExp("^"+gc+"$"),Iu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Ke.testKanji=function(e){return Tu.test(e)};Ke.testNumeric=function(e){return Lu.test(e)};Ke.testAlphanumeric=function(e){return Iu.test(e)}});var ot=X(ie=>{var Nu=ii(),ai=si();ie.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};ie.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};ie.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};ie.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};ie.MIXED={bit:-1};ie.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Nu.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};ie.getBestModeForData=function(e){return ai.testNumeric(e)?ie.NUMERIC:ai.testAlphanumeric(e)?ie.ALPHANUMERIC:ai.testKanji(e)?ie.KANJI:ie.BYTE};ie.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};ie.isValid=function(e){return e&&e.bit&&e.ccBits};function _u(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return ie.NUMERIC;case"alphanumeric":return ie.ALPHANUMERIC;case"kanji":return ie.KANJI;case"byte":return ie.BYTE;default:throw new Error("Unknown mode: "+t)}}ie.from=function(e,n){if(ie.isValid(e))return e;try{return _u(e)}catch{return n}}});var wc=X(vt=>{var Rr=nt(),Uu=ni(),pc=Er(),it=ot(),ci=ii(),bc=7973,yc=Rr.getBCHDigit(bc);function Ou(t,e,n){for(let r=1;r<=40;r++)if(e<=vt.getCapacity(r,n,t))return r}function mc(t,e){return it.getCharCountIndicator(t,e)+4}function Hu(t,e){let n=0;return t.forEach(function(r){let o=mc(r.mode,e);n+=o+r.getBitsLength()}),n}function Pu(t,e){for(let n=1;n<=40;n++)if(Hu(t,n)<=vt.getCapacity(n,e,it.MIXED))return n}vt.from=function(e,n){return ci.isValid(e)?parseInt(e,10):n};vt.getCapacity=function(e,n,r){if(!ci.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=it.BYTE);let o=Rr.getSymbolTotalCodewords(e),i=Uu.getTotalCodewordsCount(e,n),s=(o-i)*8;if(r===it.MIXED)return s;let a=s-mc(r,e);switch(r){case it.NUMERIC:return Math.floor(a/10*3);case it.ALPHANUMERIC:return Math.floor(a/11*2);case it.KANJI:return Math.floor(a/13);case it.BYTE:default:return Math.floor(a/8)}};vt.getBestVersionForData=function(e,n){let r,o=pc.from(n,pc.M);if(Array.isArray(e)){if(e.length>1)return Pu(e,o);if(e.length===0)return 1;r=e[0]}else r=e;return Ou(r.mode,r.getLength(),o)};vt.getEncodedBits=function(e){if(!ci.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Rr.getBCHDigit(n)-yc>=0;)n^=bc<<Rr.getBCHDigit(n)-yc;return e<<12|n}});var Sc=X(vc=>{var li=nt(),Ec=1335,Mu=21522,xc=li.getBCHDigit(Ec);vc.getEncodedBits=function(e,n){let r=e.bit<<3|n,o=r<<10;for(;li.getBCHDigit(o)-xc>=0;)o^=Ec<<li.getBCHDigit(o)-xc;return(r<<10|o)^Mu}});var kc=X((Xg,Bc)=>{var qu=ot();function Kt(t){this.mode=qu.NUMERIC,this.data=t.toString()}Kt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Kt.prototype.getLength=function(){return this.data.length};Kt.prototype.getBitsLength=function(){return Kt.getBitsLength(this.data.length)};Kt.prototype.write=function(e){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),e.put(o,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),o=parseInt(r,10),e.put(o,i*3+1))};Bc.exports=Kt});var Rc=X((Fg,Ac)=>{var Du=ot(),fi=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function zt(t){this.mode=Du.ALPHANUMERIC,this.data=t}zt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};zt.prototype.getLength=function(){return this.data.length};zt.prototype.getBitsLength=function(){return zt.getBitsLength(this.data.length)};zt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=fi.indexOf(this.data[n])*45;r+=fi.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(fi.indexOf(this.data[n]),6)};Ac.exports=zt});var Tc=X((Qg,Cc)=>{var $u=ot();function jt(t){this.mode=$u.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}jt.getBitsLength=function(e){return e*8};jt.prototype.getLength=function(){return this.data.length};jt.prototype.getBitsLength=function(){return jt.getBitsLength(this.data.length)};jt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Cc.exports=jt});var Ic=X((ep,Lc)=>{var Vu=ot(),Ku=nt();function Zt(t){this.mode=Vu.KANJI,this.data=t}Zt.getBitsLength=function(e){return e*13};Zt.prototype.getLength=function(){return this.data.length};Zt.prototype.getBitsLength=function(){return Zt.getBitsLength(this.data.length)};Zt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Ku.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
3
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Lc.exports=Zt});var Nc=X((tp,ui)=>{"use strict";var Sn={single_source_shortest_paths:function(t,e,n){var r={},o={};o[e]=0;var i=Sn.PriorityQueue.make();i.push(e,0);for(var s,a,c,l,d,h,f,u,y;!i.empty();){s=i.pop(),a=s.value,l=s.cost,d=t[a]||{};for(c in d)d.hasOwnProperty(c)&&(h=d[c],f=l+h,u=o[c],y=typeof o[c]>"u",(y||u>f)&&(o[c]=f,i.push(c,f),r[c]=a))}if(typeof n<"u"&&typeof o[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,o;r;)n.push(r),o=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Sn.single_source_shortest_paths(t,e,n);return Sn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Sn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof ui<"u"&&(ui.exports=Sn)});var Dc=X(Gt=>{var J=ot(),Oc=kc(),Hc=Rc(),Pc=Tc(),Mc=Ic(),Bn=si(),Cr=nt(),zu=Nc();function _c(t){return unescape(encodeURIComponent(t)).length}function kn(t,e,n){let r=[],o;for(;(o=t.exec(n))!==null;)r.push({data:o[0],index:o.index,mode:e,length:o[0].length});return r}function qc(t){let e=kn(Bn.NUMERIC,J.NUMERIC,t),n=kn(Bn.ALPHANUMERIC,J.ALPHANUMERIC,t),r,o;return Cr.isKanjiModeEnabled()?(r=kn(Bn.BYTE,J.BYTE,t),o=kn(Bn.KANJI,J.KANJI,t)):(r=kn(Bn.BYTE_KANJI,J.BYTE,t),o=[]),e.concat(n,r,o).sort(function(s,a){return s.index-a.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function di(t,e){switch(e){case J.NUMERIC:return Oc.getBitsLength(t);case J.ALPHANUMERIC:return Hc.getBitsLength(t);case J.KANJI:return Mc.getBitsLength(t);case J.BYTE:return Pc.getBitsLength(t)}}function ju(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Zu(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case J.NUMERIC:e.push([r,{data:r.data,mode:J.ALPHANUMERIC,length:r.length},{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.ALPHANUMERIC:e.push([r,{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.KANJI:e.push([r,{data:r.data,mode:J.BYTE,length:_c(r.data)}]);break;case J.BYTE:e.push([{data:r.data,mode:J.BYTE,length:_c(r.data)}])}}return e}function Gu(t,e){let n={},r={start:{}},o=["start"];for(let i=0;i<t.length;i++){let s=t[i],a=[];for(let c=0;c<s.length;c++){let l=s[c],d=""+i+c;a.push(d),n[d]={node:l,lastCount:0},r[d]={};for(let h=0;h<o.length;h++){let f=o[h];n[f]&&n[f].node.mode===l.mode?(r[f][d]=di(n[f].lastCount+l.length,l.mode)-di(n[f].lastCount,l.mode),n[f].lastCount+=l.length):(n[f]&&(n[f].lastCount=l.length),r[f][d]=di(l.length,l.mode)+4+J.getCharCountIndicator(l.mode,e))}}o=a}for(let i=0;i<o.length;i++)r[o[i]].end=0;return{map:r,table:n}}function Uc(t,e){let n,r=J.getBestModeForData(t);if(n=J.from(e,r),n!==J.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+J.toString(n)+`.
4
+ Suggested mode is: `+J.toString(r));switch(n===J.KANJI&&!Cr.isKanjiModeEnabled()&&(n=J.BYTE),n){case J.NUMERIC:return new Oc(t);case J.ALPHANUMERIC:return new Hc(t);case J.KANJI:return new Mc(t);case J.BYTE:return new Pc(t)}}Gt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Uc(r,null)):r.data&&n.push(Uc(r.data,r.mode)),n},[])};Gt.fromString=function(e,n){let r=qc(e,Cr.isKanjiModeEnabled()),o=Zu(r),i=Gu(o,n),s=zu.find_path(i.map,"start","end"),a=[];for(let c=1;c<s.length-1;c++)a.push(i.table[s[c]].node);return Gt.fromArray(ju(a))};Gt.rawSplit=function(e){return Gt.fromArray(qc(e,Cr.isKanjiModeEnabled()))}});var Vc=X($c=>{var Lr=nt(),hi=Er(),Wu=ec(),Yu=nc(),Ju=rc(),Xu=sc(),yi=ac(),bi=ni(),Fu=dc(),Tr=wc(),Qu=Sc(),ed=ot(),gi=Dc();function td(t,e){let n=t.size,r=Xu.getPositions(e);for(let o=0;o<r.length;o++){let i=r[o][0],s=r[o][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let c=-1;c<=7;c++)s+c<=-1||n<=s+c||(a>=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?t.set(i+a,s+c,!0,!0):t.set(i+a,s+c,!1,!0))}}function nd(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function rd(t,e){let n=Ju.getPositions(e);for(let r=0;r<n.length;r++){let o=n[r][0],i=n[r][1];for(let s=-2;s<=2;s++)for(let a=-2;a<=2;a++)s===-2||s===2||a===-2||a===2||s===0&&a===0?t.set(o+s,i+a,!0,!0):t.set(o+s,i+a,!1,!0)}}function od(t,e){let n=t.size,r=Tr.getEncodedBits(e),o,i,s;for(let a=0;a<18;a++)o=Math.floor(a/3),i=a%3+n-8-3,s=(r>>a&1)===1,t.set(o,i,s,!0),t.set(i,o,s,!0)}function pi(t,e,n){let r=t.size,o=Qu.getEncodedBits(e,n),i,s;for(i=0;i<15;i++)s=(o>>i&1)===1,i<6?t.set(i,8,s,!0):i<8?t.set(i+1,8,s,!0):t.set(r-15+i,8,s,!0),i<8?t.set(8,r-i-1,s,!0):i<9?t.set(8,15-i-1+1,s,!0):t.set(8,15-i-1,s,!0);t.set(r-8,8,1,!0)}function id(t,e){let n=t.size,r=-1,o=n-1,i=7,s=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!t.isReserved(o,a-c)){let l=!1;s<e.length&&(l=(e[s]>>>i&1)===1),t.set(o,a-c,l),i--,i===-1&&(s++,i=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function sd(t,e,n){let r=new Wu;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),ed.getCharCountIndicator(c.mode,t)),c.write(r)});let o=Lr.getSymbolTotalCodewords(t),i=bi.getTotalCodewordsCount(t,e),s=(o-i)*8;for(r.getLengthInBits()+4<=s&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(s-r.getLengthInBits())/8;for(let c=0;c<a;c++)r.put(c%2?17:236,8);return ad(r,t,e)}function ad(t,e,n){let r=Lr.getSymbolTotalCodewords(e),o=bi.getTotalCodewordsCount(e,n),i=r-o,s=bi.getBlocksCount(e,n),a=r%s,c=s-a,l=Math.floor(r/s),d=Math.floor(i/s),h=d+1,f=l-d,u=new Fu(f),y=0,m=new Array(s),S=new Array(s),R=0,M=new Uint8Array(t.buffer);for(let j=0;j<s;j++){let Z=j<c?d:h;m[j]=M.slice(y,y+Z),S[j]=u.encode(m[j]),y+=Z,R=Math.max(R,Z)}let I=new Uint8Array(r),_=0,N,q;for(N=0;N<R;N++)for(q=0;q<s;q++)N<m[q].length&&(I[_++]=m[q][N]);for(N=0;N<f;N++)for(q=0;q<s;q++)I[_++]=S[q][N];return I}function cd(t,e,n,r){let o;if(Array.isArray(t))o=gi.fromArray(t);else if(typeof t=="string"){let l=e;if(!l){let d=gi.rawSplit(t);l=Tr.getBestVersionForData(d,n)}o=gi.fromString(t,l||40)}else throw new Error("Invalid data");let i=Tr.getBestVersionForData(o,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
5
5
  The chosen QR Code version cannot contain this amount of data.
6
6
  Minimum version required to store current data is: `+i+`.
7
- `);let s=nd(e,n,o),a=Lr.getSymbolSize(e),c=new ju(a);return Xu(c,e),Fu(c),Qu(c,e),ci(c,n,0),e>=7&&ed(c,e),td(c,s),isNaN(r)&&(r=li.getBestMask(c,ci.bind(null,c,n))),li.applyMask(r,c),ci(c,n,r),{modules:c,version:e,errorCorrectionLevel:n,maskPattern:r,segments:o}}qc.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=si.M,o,i;return typeof n<"u"&&(r=si.from(n.errorCorrectionLevel,si.M),o=Tr.from(n.version),i=li.from(n.maskPattern),n.toSJISFunc&&Lr.setToSJISFunction(n.toSJISFunc)),od(e,o,r,i)}});var ui=X(St=>{function $c(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}St.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,o=e.scale||4;return{width:r,scale:r?4:o,margin:n,color:{dark:$c(e.color.dark||"#000000ff"),light:$c(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};St.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};St.getImageWidth=function(e,n){let r=St.getScale(e,n);return Math.floor((e+n.margin*2)*r)};St.qrToImageData=function(e,n,r){let o=n.modules.size,i=n.modules.data,s=St.getScale(o,r),a=Math.floor((o+r.margin*2)*s),c=r.margin*s,l=[r.color.light,r.color.dark];for(let d=0;d<a;d++)for(let h=0;h<a;h++){let f=(d*a+h)*4,u=r.color.light;if(d>=c&&h>=c&&d<a-c&&h<a-c){let y=Math.floor((d-c)/s),m=Math.floor((h-c)/s);u=l[i[y*o+m]?1:0]}e[f++]=u.r,e[f++]=u.g,e[f++]=u.b,e[f]=u.a}}});var Vc=X(Ir=>{var di=ui();function id(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function sd(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ir.render=function(e,n,r){let o=r,i=n;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),n||(i=sd()),o=di.getOptions(o);let s=di.getImageWidth(e.modules.size,o),a=i.getContext("2d"),c=a.createImageData(s,s);return di.qrToImageData(c.data,e,o),id(a,i,s),a.putImageData(c,0,0),i};Ir.renderToDataURL=function(e,n,r){let o=r;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),o||(o={});let i=Ir.render(e,n,o),s=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(s,a.quality)}});var jc=X(zc=>{var ad=ui();function Kc(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function hi(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function cd(t,e,n){let r="",o=0,i=!1,s=0;for(let a=0;a<t.length;a++){let c=Math.floor(a%e),l=Math.floor(a/e);!c&&!i&&(i=!0),t[a]?(s++,a>0&&c>0&&t[a-1]||(r+=i?hi("M",c+n,.5+l+n):hi("m",o,0),o=0,i=!1),c+1<e&&t[a+1]||(r+=hi("h",s),s=0)):o++}return r}zc.render=function(e,n,r){let o=ad.getOptions(n),i=e.modules.size,s=e.modules.data,a=i+o.margin*2,c=o.color.light.a?"<path "+Kc(o.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+Kc(o.color.dark,"stroke")+' d="'+cd(s,i,o.margin)+'"/>',d='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+d+' shape-rendering="crispEdges">'+c+l+`</svg>
8
- `;return typeof r=="function"&&r(null,f),f}});var Gc=X(An=>{var ld=Ya(),gi=Dc(),Zc=Vc(),fd=jc();function pi(t,e,n,r,o){let i=[].slice.call(arguments,1),s=i.length,a=typeof i[s-1]=="function";if(!a&&!ld())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(o=n,n=e,e=r=void 0):s===3&&(e.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(n=e,e=r=void 0):s===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(c,l){try{let d=gi.create(n,r);c(t(d,e,r))}catch(d){l(d)}})}try{let c=gi.create(n,r);o(null,t(c,e,r))}catch(c){o(c)}}An.create=gi.create;An.toCanvas=pi.bind(null,Zc.render);An.toDataURL=pi.bind(null,Zc.renderToDataURL);An.toString=pi.bind(null,function(t,e,n){return fd.render(t,n)})});var vd={};al(vd,{handleCallback:()=>Fc,handleRedirectCallback:()=>Qc,isAndroid:()=>rr,login:()=>Jc,logout:()=>el,restoreSession:()=>Xc});var ze={relayUrl:"wss://relay.damus.io",signetAppOrigin:"https://mysignet.app",timeout:12e4,theme:"auto",persist:!0,mode:"relay"},Rn=300*1e3,Q={pubkey:"signet:login.pubkey",method:"signet:login.method",authEvent:"signet:login.authEvent",bunkerUri:"signet:login.bunkerUri",bunkerClientSk:"signet:login.bunkerClientSk",expiresAt:"signet:login.expiresAt",displayName:"signet:login.displayName",pendingRedirect:"signet:login.pendingRedirect"};function Xt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function we(t,e=""){if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function Y(t,e,n=""){let r=Xt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function st(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(t.outputLen),we(t.blockLen)}function kt(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 xi(t,e){Y(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ie(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Cn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Se(t,e){return t<<32-e|t>>>e}var Ei=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fl=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ee(t){if(Y(t),Ei)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=fl[t[n]];return e}var Le={_0:48,_9:57,A:65,F:70,a:97,f:102};function wi(t){if(t>=Le._0&&t<=Le._9)return t-Le._0;if(t>=Le.A&&t<=Le.F)return t-(Le.A-10);if(t>=Le.a&&t<=Le.f)return t-(Le.a-10)}function ne(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ei)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=wi(t.charCodeAt(i)),a=wi(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function te(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Y(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}function vi(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Be(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 Si=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Bi(t,e,n){return t&e^~t&n}function ki(t,e,n){return t&e^t&n^e&n}var Tn=class{constructor(e,n,r,o){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){kt(this),Y(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Cn(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kt(this),xi(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Ie(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let h=s;h<o;h++)n[h]=0;r.setBigUint64(o-8,BigInt(this.length*8),i),this.process(r,0);let a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ul=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]),je=new Uint32Array(64),_r=class extends Tn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)je[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){let f=je[h-15],u=je[h-2],y=Se(f,7)^Se(f,18)^f>>>3,m=Se(u,17)^Se(u,19)^u>>>10;je[h]=m+je[h-7]+y+je[h-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){let f=Se(a,6)^Se(a,11)^Se(a,25),u=d+f+Bi(a,c,l)+ul[h]+je[h]|0,m=(Se(r,2)^Se(r,13)^Se(r,22))+ki(r,o,i)|0;d=l,l=c,c=a,a=s+u|0,s=i,i=o,o=r,r=u+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Ie(je)}destroy(){this.set(0,0,0,0,0,0,0,0),Ie(this.buffer)}},Ur=class extends _r{constructor(){super(32);v(this,"A",Ne[0]|0);v(this,"B",Ne[1]|0);v(this,"C",Ne[2]|0);v(this,"D",Ne[3]|0);v(this,"E",Ne[4]|0);v(this,"F",Ne[5]|0);v(this,"G",Ne[6]|0);v(this,"H",Ne[7]|0)}};var fe=vi(()=>new Ur,Si(1));var Hr=BigInt(0),Or=BigInt(1);function Ft(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Ai(t){if(typeof t=="bigint"){if(!Ln(t))throw new Error("positive bigint expected, got "+t)}else we(t);return t}function Qt(t){let e=Ai(t).toString(16);return e.length&1?"0"+e:e}function Ri(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Hr:BigInt("0x"+t)}function Ze(t){return Ri(ee(t))}function Pr(t){return Ri(ee(dl(Y(t)).reverse()))}function In(t,e){we(e),t=Ai(t);let n=ne(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function Mr(t,e){return In(t,e).reverse()}function dl(t){return Uint8Array.from(t)}function Ci(t){return Uint8Array.from(t,(e,n)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}var Ln=t=>typeof t=="bigint"&&Hr<=t;function hl(t,e,n){return Ln(t)&&Ln(e)&&Ln(n)&&e<=t&&t<n}function Ti(t,e,n,r){if(!hl(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function qr(t){let e;for(e=0;t>Hr;t>>=Or,e+=1);return e}var en=t=>(Or<<BigInt(t))-Or;function Li(t,e,n){if(we(t,"hashLen"),we(e,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");let r=S=>new Uint8Array(S),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(t),l=r(t),d=0,h=()=>{c.fill(1),l.fill(0),d=0},f=(...S)=>n(l,te(c,...S)),u=(S=o)=>{l=f(i,S),c=f(),S.length!==0&&(l=f(s,S),c=f())},y=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let S=0,R=[];for(;S<e;){c=f();let N=c.slice();R.push(N),S+=c.length}return te(...R)};return(S,R)=>{h(),u(S);let N;for(;!(N=R(y()));)u();return h(),N}}function tn(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,a){let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>r(a,c,s));o(e,!1),o(n,!0)}function Dr(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var he=BigInt(0),ue=BigInt(1),at=BigInt(2),_i=BigInt(3),Ui=BigInt(4),Oi=BigInt(5),gl=BigInt(7),Hi=BigInt(8),pl=BigInt(9),Pi=BigInt(16);function ke(t,e){let n=t%e;return n>=he?n:e+n}function ye(t,e,n){let r=t;for(;e-- >he;)r*=r,r%=n;return r}function Ii(t,e){if(t===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let n=ke(t,e),r=e,o=he,i=ue,s=ue,a=he;for(;n!==he;){let l=r/n,d=r%n,h=o-s*l,f=i-a*l;r=n,n=d,o=s,i=a,s=h,a=f}if(r!==ue)throw new Error("invert: does not exist");return ke(o,e)}function Vr(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Mi(t,e){let n=(t.ORDER+ue)/Ui,r=t.pow(e,n);return Vr(t,r,e),r}function yl(t,e){let n=(t.ORDER-Oi)/Hi,r=t.mul(e,at),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,at),o),a=t.mul(i,t.sub(s,t.ONE));return Vr(t,a,e),a}function bl(t){let e=At(t),n=qi(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+gl)/Pi;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),h=a.mul(l,o),f=a.mul(l,i),u=a.eql(a.sqr(d),c),y=a.eql(a.sqr(h),c);l=a.cmov(l,d,u),d=a.cmov(f,h,y);let m=a.eql(a.sqr(d),c),S=a.cmov(l,d,m);return Vr(a,S,c),S}}function qi(t){if(t<_i)throw new Error("sqrt is not defined for small field");let e=t-ue,n=0;for(;e%at===he;)e/=at,n++;let r=at,o=At(t);for(;Ni(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Mi;let i=o.pow(r,e),s=(e+ue)/at;return function(c,l){if(c.is0(l))return l;if(Ni(c,l)!==1)throw new Error("Cannot find square root");let d=n,h=c.mul(c.ONE,i),f=c.pow(l,e),u=c.pow(l,s);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let y=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let S=ue<<BigInt(d-y-1),R=c.pow(h,S);d=y,h=c.sqr(R),f=c.mul(f,h),u=c.mul(u,R)}return u}}function ml(t){return t%Ui===_i?Mi:t%Hi===Oi?yl:t%Pi===pl?bl(t):qi(t)}var wl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=wl.reduce((r,o)=>(r[o]="function",r),e);return tn(t,n),t}function xl(t,e,n){if(n<he)throw new Error("invalid exponent, negatives unsupported");if(n===he)return t.ONE;if(n===ue)return e;let r=t.ONE,o=e;for(;n>he;)n&ue&&(r=t.mul(r,o)),o=t.sqr(o),n>>=ue;return r}function Nn(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function Ni(t,e){let n=(t.ORDER-ue)/at,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function El(t,e){e!==void 0&&we(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var $r=class{constructor(e,n={}){v(this,"ORDER");v(this,"BITS");v(this,"BYTES");v(this,"isLE");v(this,"ZERO",he);v(this,"ONE",ue);v(this,"_lengths");v(this,"_sqrt");v(this,"_mod");if(e<=he)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=n.allowedLengths?.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=El(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ke(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ue)===ue}neg(e){return ke(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return ke(e*e,this.ORDER)}add(e,n){return ke(e+n,this.ORDER)}sub(e,n){return ke(e-n,this.ORDER)}mul(e,n){return ke(e*n,this.ORDER)}pow(e,n){return xl(this,e,n)}div(e,n){return ke(e*Ii(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Ii(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ml(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Mr(e,this.BYTES):In(e,this.BYTES)}fromBytes(e,n=!1){Y(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Pr(e):Ze(e);if(a&&(c=ke(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e)}cmov(e,n,r){return r?n:e}};function At(t,e={}){return new $r(t,e)}function Di(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 zr(t){let e=Di(t);return e+Math.ceil(e/2)}function _n(t,e,n=!1){Y(t);let r=t.length,o=Di(e),i=zr(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Pr(t):Ze(t),a=ke(s,e-ue)+ue;return n?Mr(a,o):In(a,o)}var Rt=BigInt(0),ct=BigInt(1);function nn(t,e){let n=e.negate();return t?n:e}function Wr(t,e){let n=Nn(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function zi(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jr(t,e){zi(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=en(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function $i(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=ct);let l=e*r,d=l+Math.abs(a)-1,h=a===0,f=a<0,u=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:f,isNegF:u,offsetF:l}}var Zr=new WeakMap,ji=new WeakMap;function Gr(t){return ji.get(t)||1}function Vi(t){if(t!==Rt)throw new Error("invalid wNAF")}var Un=class{constructor(e,n){v(this,"BASE");v(this,"ZERO");v(this,"Fn");v(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Rt;)n&ct&&(r=r.add(o)),o=o.double(),n>>=ct;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=jr(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=jr(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}=$i(r,a,s);r=c,d?i=i.add(nn(f,n[u])):o=o.add(nn(h,n[l]))}return Vi(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=jr(e,this.bits);for(let s=0;s<i.windows&&r!==Rt;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=$i(r,s,i);if(r=a,!l){let h=n[c];o=o.add(d?h.negate():h)}}return Vi(r),o}getPrecomputes(e,n,r){let o=Zr.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Zr.set(n,o))),o}cached(e,n,r){let o=Gr(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Gr(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){zi(n,this.bits),ji.set(e,n),Zr.delete(e)}hasCache(e){return Gr(e)!==1}};function Zi(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>Rt||r>Rt;)n&ct&&(i=i.add(o)),r&ct&&(s=s.add(o)),o=o.double(),n>>=ct,r>>=ct;return{p1:i,p2:s}}function Ki(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Kr(e),e}else return At(t,{isLE:n})}function Gi(t,e,n={},r){if(r===void 0&&(r=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>Rt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ki(e.p,n.Fp,r),i=Ki(e.n,n.Fn,r),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:i}}function On(t,e){return function(r){let o=t(r);return{secretKey:o,publicKey:e(o)}}}var Hn=class{constructor(e,n){v(this,"oHash");v(this,"iHash");v(this,"blockLen");v(this,"outputLen");v(this,"finished",!1);v(this,"destroyed",!1);if(st(e),Y(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ie(o)}update(e){return kt(this),this.iHash.update(e),this}digestInto(e){kt(this),Y(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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Te=(t,e,n)=>new Hn(t,e).update(n).digest();Te.create=(t,e)=>new Hn(t,e);var Wi=(t,e)=>(t+(t>=0?e:-e)/Yi)/e;function vl(t,e,n){let[[r,o],[i,s]]=e,a=Wi(s*t,n),c=Wi(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,h=l<_e,f=d<_e;h&&(l=-l),f&&(d=-d);let u=en(Math.ceil(qr(n)/2))+Ct;if(l<_e||l>=u||d<_e||d>=u)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:d}}function Jr(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Yr(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Ft(n.lowS,"lowS"),Ft(n.prehash,"prehash"),n.format!==void 0&&Jr(n.format),n}var Xr=class extends Error{constructor(e=""){super(e)}},Ge={Err:Xr,_tlv:{encode:(t,e)=>{let{Err:n}=Ge;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=Qt(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?Qt(o.length/2|128):"";return Qt(t)+i+o+e},decode(t,e){let{Err:n}=Ge,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=Ge;if(t<_e)throw new e("integer: negative integers are not allowed");let n=Qt(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=Ge;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 Ze(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=Ge,o=Y(t,void 0,"signature"),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=Ge,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},_e=BigInt(0),Ct=BigInt(1),Yi=BigInt(2),Pn=BigInt(3),Sl=BigInt(4);function Ji(t,e={}){let n=Gi("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;tn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Fi(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(x,g,p){let{x:b,y:E}=g.toAffine(),k=r.toBytes(b);if(Ft(p,"isCompressed"),p){d();let w=!r.isOdd(E);return te(Xi(w),k)}else return te(Uint8Array.of(4),k,r.toBytes(E))}function f(x){Y(x,void 0,"Point");let{publicKey:g,publicKeyUncompressed:p}=l,b=x.length,E=x[0],k=x.subarray(1);if(b===g&&(E===2||E===3)){let w=r.fromBytes(k);if(!r.isValid(w))throw new Error("bad point: is not on curve, wrong x");let A=m(w),B;try{B=r.sqrt(A)}catch(q){let P=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+P)}d();let C=r.isOdd(B);return(E&1)===1!==C&&(B=r.neg(B)),{x:w,y:B}}else if(b===p&&E===4){let w=r.BYTES,A=r.fromBytes(k.subarray(0,w)),B=r.fromBytes(k.subarray(w,w*2));if(!S(A,B))throw new Error("bad point: is not on curve");return{x:A,y:B}}else throw new Error(`bad point: got length ${b}, expected compressed=${g} or uncompressed=${p}`)}let u=e.toBytes||h,y=e.fromBytes||f;function m(x){let g=r.sqr(x),p=r.mul(g,x);return r.add(r.add(p,r.mul(x,i.a)),i.b)}function S(x,g){let p=r.sqr(g),b=m(x);return r.eql(p,b)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,Pn),Sl),N=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,N)))throw new Error("bad curve params: a or b");function _(x,g,p=!1){if(!r.isValid(g)||p&&r.is0(g))throw new Error(`bad point coordinate ${x}`);return g}function M(x){if(!(x instanceof L))throw new Error("Weierstrass Point expected")}function U(x){if(!c||!c.basises)throw new Error("no endo");return vl(x,c.basises,o.ORDER)}let D=Dr((x,g)=>{let{X:p,Y:b,Z:E}=x;if(r.eql(E,r.ONE))return{x:p,y:b};let k=x.is0();g==null&&(g=k?r.ONE:r.inv(E));let w=r.mul(p,g),A=r.mul(b,g),B=r.mul(E,g);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:w,y:A}}),j=Dr(x=>{if(x.is0()){if(e.allowInfinityPoint&&!r.is0(x.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:p}=x.toAffine();if(!r.isValid(g)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!S(g,p))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(x,g,p,b,E){return p=new L(r.mul(p.X,x),p.Y,p.Z),g=nn(b,g),p=nn(E,p),g.add(p)}let T=class T{constructor(g,p,b){v(this,"X");v(this,"Y");v(this,"Z");this.X=_("x",g),this.Y=_("y",p,!0),this.Z=_("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){let{x:p,y:b}=g||{};if(!g||!r.isValid(p)||!r.isValid(b))throw new Error("invalid affine point");if(g instanceof T)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(b)?T.ZERO:new T(p,b,r.ONE)}static fromBytes(g){let p=T.fromAffine(y(Y(g,void 0,"point")));return p.assertValidity(),p}static fromHex(g){return T.fromBytes(ne(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,p=!0){return $.createCache(this,g),p||this.multiply(Pn),this}assertValidity(){j(this)}hasEvenY(){let{y:g}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(g)}equals(g){M(g);let{X:p,Y:b,Z:E}=this,{X:k,Y:w,Z:A}=g,B=r.eql(r.mul(p,A),r.mul(k,E)),C=r.eql(r.mul(b,A),r.mul(w,E));return B&&C}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:g,b:p}=i,b=r.mul(p,Pn),{X:E,Y:k,Z:w}=this,A=r.ZERO,B=r.ZERO,C=r.ZERO,O=r.mul(E,E),q=r.mul(k,k),P=r.mul(w,w),I=r.mul(E,k);return I=r.add(I,I),C=r.mul(E,w),C=r.add(C,C),A=r.mul(g,C),B=r.mul(b,P),B=r.add(A,B),A=r.sub(q,B),B=r.add(q,B),B=r.mul(A,B),A=r.mul(I,A),C=r.mul(b,C),P=r.mul(g,P),I=r.sub(O,P),I=r.mul(g,I),I=r.add(I,C),C=r.add(O,O),O=r.add(C,O),O=r.add(O,P),O=r.mul(O,I),B=r.add(B,O),P=r.mul(k,w),P=r.add(P,P),O=r.mul(P,I),A=r.sub(A,O),C=r.mul(P,q),C=r.add(C,C),C=r.add(C,C),new T(A,B,C)}add(g){M(g);let{X:p,Y:b,Z:E}=this,{X:k,Y:w,Z:A}=g,B=r.ZERO,C=r.ZERO,O=r.ZERO,q=i.a,P=r.mul(i.b,Pn),I=r.mul(p,k),V=r.mul(b,w),W=r.mul(E,A),K=r.add(p,b),G=r.add(k,w);K=r.mul(K,G),G=r.add(I,V),K=r.sub(K,G),G=r.add(p,E);let oe=r.add(k,A);return G=r.mul(G,oe),oe=r.add(I,W),G=r.sub(G,oe),oe=r.add(b,E),B=r.add(w,A),oe=r.mul(oe,B),B=r.add(V,W),oe=r.sub(oe,B),O=r.mul(q,G),B=r.mul(P,W),O=r.add(B,O),B=r.sub(V,O),O=r.add(V,O),C=r.mul(B,O),V=r.add(I,I),V=r.add(V,I),W=r.mul(q,W),G=r.mul(P,G),V=r.add(V,W),W=r.sub(I,W),W=r.mul(q,W),G=r.add(G,W),I=r.mul(V,G),C=r.add(C,I),I=r.mul(oe,G),B=r.mul(K,B),B=r.sub(B,I),I=r.mul(K,V),O=r.mul(oe,O),O=r.add(O,I),new T(B,C,O)}subtract(g){return this.add(g.negate())}is0(){return this.equals(T.ZERO)}multiply(g){let{endo:p}=e;if(!o.isValidNot0(g))throw new Error("invalid scalar: out of range");let b,E,k=w=>$.cached(this,w,A=>Wr(T,A));if(p){let{k1neg:w,k1:A,k2neg:B,k2:C}=U(g),{p:O,f:q}=k(A),{p:P,f:I}=k(C);E=q.add(I),b=Z(p.beta,O,P,w,B)}else{let{p:w,f:A}=k(g);b=w,E=A}return Wr(T,[b,E])[0]}multiplyUnsafe(g){let{endo:p}=e,b=this;if(!o.isValid(g))throw new Error("invalid scalar: out of range");if(g===_e||b.is0())return T.ZERO;if(g===Ct)return b;if($.hasCache(this))return this.multiply(g);if(p){let{k1neg:E,k1:k,k2neg:w,k2:A}=U(g),{p1:B,p2:C}=Zi(T,b,k,A);return Z(p.beta,B,C,E,w)}else return $.unsafe(b,g)}toAffine(g){return D(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return s===Ct?!0:g?g(T,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return s===Ct?this:g?g(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(g=!0){return Ft(g,"isCompressed"),this.assertValidity(),u(T,this,g)}toHex(g=!0){return ee(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(T,"BASE",new T(i.Gx,i.Gy,r.ONE)),v(T,"ZERO",new T(r.ZERO,r.ONE,r.ZERO)),v(T,"Fp",r),v(T,"Fn",o);let L=T,z=o.BITS,$=new Un(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function Xi(t){return Uint8Array.of(t?2:3)}function Fi(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Bl(t,e={}){let{Fn:n}=t,r=e.randomBytes||Be,o=Object.assign(Fi(t.Fp,n),{seed:zr(n.ORDER)});function i(u){try{let y=n.fromBytes(u);return n.isValidNot0(y)}catch{return!1}}function s(u,y){let{publicKey:m,publicKeyUncompressed:S}=o;try{let R=u.length;return y===!0&&R!==m||y===!1&&R!==S?!1:!!t.fromBytes(u)}catch{return!1}}function a(u=r(o.seed)){return _n(Y(u,o.seed,"seed"),n.ORDER)}function c(u,y=!0){return t.BASE.multiply(n.fromBytes(u)).toBytes(y)}function l(u){let{secretKey:y,publicKey:m,publicKeyUncompressed:S}=o;if(!Xt(u)||"_lengths"in n&&n._lengths||y===m)return;let R=Y(u,void 0,"key").length;return R===m||R===S}function d(u,y,m=!0){if(l(u)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");let S=n.fromBytes(u);return t.fromBytes(y).multiply(S).toBytes(m)}let h={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=On(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:f,Point:t,utils:h,lengths:o})}function Qi(t,e,n={}){st(e),tn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);let r=n.randomBytes||Be,o=n.hmac||((g,p)=>Te(e,g,p)),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u}=Bl(t,n),y={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},m=a*Yi<i.ORDER;function S(g){let p=a>>Ct;return g>p}function R(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function N(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function _(g,p){Jr(p);let b=u.signature,E=p==="compact"?b:p==="recovered"?b+1:void 0;return Y(g,E)}class M{constructor(p,b,E){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=R("r",p),this.s=R("s",b),E!=null){if(N(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(p,b=y.format){_(p,b);let E;if(b==="der"){let{r:B,s:C}=Ge.toSig(Y(p));return new M(B,C)}b==="recovered"&&(E=p[0],b="compact",p=p.subarray(1));let k=u.signature/2,w=p.subarray(0,k),A=p.subarray(k,k*2);return new M(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(p,b){return this.fromBytes(ne(p),b)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new M(this.r,this.s,p)}recoverPublicKey(p){let{r:b,s:E}=this,k=this.assertRecovery(),w=k===2||k===3?b+a:b;if(!i.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let A=i.toBytes(w),B=t.fromBytes(te(Xi((k&1)===0),A)),C=s.inv(w),O=D(Y(p,void 0,"msgHash")),q=s.create(-O*C),P=s.create(E*C),I=t.BASE.multiplyUnsafe(q).add(B.multiplyUnsafe(P));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return S(this.s)}toBytes(p=y.format){if(Jr(p),p==="der")return ne(Ge.hexFromSig(this));let{r:b,s:E}=this,k=s.toBytes(b),w=s.toBytes(E);return p==="recovered"?(N(),te(Uint8Array.of(this.assertRecovery()),k,w)):te(k,w)}toHex(p){return ee(this.toBytes(p))}}let U=n.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let b=Ze(p),E=p.length*8-c;return E>0?b>>BigInt(E):b},D=n.bits2int_modN||function(p){return s.create(U(p))},j=en(c);function Z(g){return Ti("num < 2^"+c,g,_e,j),s.toBytes(g)}function L(g,p){return Y(g,void 0,"message"),p?Y(e(g),void 0,"prehashed message"):g}function z(g,p,b){let{lowS:E,prehash:k,extraEntropy:w}=Yr(b,y);g=L(g,k);let A=D(g),B=s.fromBytes(p);if(!s.isValidNot0(B))throw new Error("invalid private key");let C=[Z(B),Z(A)];if(w!=null&&w!==!1){let I=w===!0?r(u.secretKey):w;C.push(Y(I,void 0,"extraEntropy"))}let O=te(...C),q=A;function P(I){let V=U(I);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===_e)return;let oe=s.create(W*s.create(q+G*B));if(oe===_e)return;let Wt=(K.x===G?0:2)|Number(K.y&Ct),Yt=oe;return E&&S(oe)&&(Yt=s.neg(oe),Wt^=1),new M(G,Yt,m?void 0:Wt)}return{seed:O,k2sig:P}}function $(g,p,b={}){let{seed:E,k2sig:k}=z(g,p,b);return Li(e.outputLen,s.BYTES,o)(E,k).toBytes(b.format)}function T(g,p,b,E={}){let{lowS:k,prehash:w,format:A}=Yr(E,y);if(b=Y(b,void 0,"publicKey"),p=L(p,w),!Xt(g)){let B=g instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+B)}_(g,A);try{let B=M.fromBytes(g,A),C=t.fromBytes(b);if(k&&B.hasHighS())return!1;let{r:O,s:q}=B,P=D(p),I=s.inv(q),V=s.create(P*I),W=s.create(O*I),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===O}catch{return!1}}function x(g,p,b={}){let{prehash:E}=Yr(b,y);return p=L(p,E),M.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u,Point:t,sign:$,verify:T,recoverPublicKey:x,Signature:M,hash:e})}var Dn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},kl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Al=BigInt(0),Fr=BigInt(2);function Rl(t){let e=Dn.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,h=ye(d,n,e)*d%e,f=ye(h,n,e)*d%e,u=ye(f,Fr,e)*l%e,y=ye(u,o,e)*u%e,m=ye(y,i,e)*y%e,S=ye(m,a,e)*m%e,R=ye(S,c,e)*S%e,N=ye(R,a,e)*m%e,_=ye(N,n,e)*d%e,M=ye(_,s,e)*y%e,U=ye(M,r,e)*l%e,D=ye(U,Fr,e);if(!Mn.eql(Mn.sqr(D),t))throw new Error("Cannot find square root");return D}var Mn=At(Dn.p,{sqrt:Rl}),lt=Ji(Dn,{Fp:Mn,endo:kl}),$n=Qi(lt,fe),es={};function qn(t,...e){let n=es[t];if(n===void 0){let r=fe(Ci(t));n=te(r,r),es[t]=n}return fe(te(n,...e))}var eo=t=>t.toBytes(!0).slice(1),to=t=>t%Fr===Al;function Qr(t){let{Fn:e,BASE:n}=lt,r=e.fromBytes(t),o=n.multiply(r);return{scalar:to(o.y)?r:e.neg(r),bytes:eo(o)}}function ns(t){let e=Mn;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);to(o)||(o=e.neg(o));let i=lt.fromAffine({x:t,y:o});return i.assertValidity(),i}var rn=Ze;function rs(...t){return lt.Fn.create(rn(qn("BIP0340/challenge",...t)))}function ts(t){return Qr(t).bytes}function Cl(t,e,n=Be(32)){let{Fn:r}=lt,o=Y(t,void 0,"message"),{bytes:i,scalar:s}=Qr(e),a=Y(n,32,"auxRand"),c=r.toBytes(s^rn(qn("BIP0340/aux",a))),l=qn("BIP0340/nonce",c,i,o),{bytes:d,scalar:h}=Qr(l),f=rs(d,i,o),u=new Uint8Array(64);if(u.set(d,0),u.set(r.toBytes(r.create(h+f*s)),32),!os(u,o,i))throw new Error("sign: Invalid signature produced");return u}function os(t,e,n){let{Fp:r,Fn:o,BASE:i}=lt,s=Y(t,64,"signature"),a=Y(e,void 0,"message"),c=Y(n,32,"publicKey");try{let l=ns(rn(c)),d=rn(s.subarray(0,32));if(!r.isValidNot0(d))return!1;let h=rn(s.subarray(32,64));if(!o.isValidNot0(h))return!1;let f=rs(o.toBytes(d),eo(l),a),u=i.multiplyUnsafe(h).add(l.multiplyUnsafe(o.neg(f))),{x:y,y:m}=u.toAffine();return!(u.is0()||!to(m)||y!==d)}catch{return!1}}var xe=(()=>{let n=(r=Be(48))=>_n(r,Dn.n);return{keygen:On(n,ts),getPublicKey:ts,sign:Cl,verify:os,Point:lt,utils:{randomSecretKey:n,taggedHash:qn,lift_x:ns,pointToBytes:eo},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Tl(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Vn(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Kn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function se(t,e,n=""){let r=Tl(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function no(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 is(t,e){se(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Ue(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 Ll(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Il=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ss(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Tt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}var ro=(t,e)=>{function n(r,...o){if(se(r,void 0,"key"),!Il)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let d=o[0];se(d,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let i=t.tagLength;i&&o[1]!==void 0&&se(o[1],void 0,"AAD");let s=e(r,...o),a=(d,h)=>{if(h!==void 0){if(d!==2)throw new Error("cipher output not supported");se(h,void 0,"output")}},c=!1;return{encrypt(d,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,se(d),a(s.encrypt.length,h),s.encrypt(d,h)},decrypt(d,h){if(se(d),i&&d.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,h),s.decrypt(d,h)}}}return Object.assign(n,t),n};function oo(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(n&&!Nl(e))throw new Error("invalid output, must be aligned");return e}function as(t,e,n){Vn(n);let r=new Uint8Array(16),o=Ll(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Nl(t){return t.byteOffset%4===0}function Lt(t){return Uint8Array.from(t)}var ls=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),_l=ls("expand 16-byte k"),Ul=ls("expand 32-byte k"),Ol=Ue(_l),Hl=Ue(Ul);function H(t,e){return t<<e|t>>>32-e}function io(t){return t.byteOffset%4===0}var zn=64,Pl=16,fs=2**32-1,cs=Uint32Array.of();function Ml(t,e,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(zn),d=Ue(l),h=io(o)&&io(i),f=h?Ue(o):cs,u=h?Ue(i):cs;for(let y=0;y<c;s++){if(t(e,n,r,d,s,a),s>=fs)throw new Error("arx: counter overflow");let m=Math.min(zn,c-y);if(h&&m===zn){let S=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let R=0,N;R<Pl;R++)N=S+R,u[N]=f[N]^d[R];y+=zn;continue}for(let S=0,R;S<m;S++)R=y+S,i[R]=o[R]^l[S];y+=m}}function so(t,e){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=ss({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Kn(o),Kn(s),Vn(i),Vn(n),(a,c,l,d,h=0)=>{se(a,void 0,"key"),se(c,void 0,"nonce"),se(l,void 0,"data");let f=l.length;if(d===void 0&&(d=new Uint8Array(f)),se(d,void 0,"output"),Kn(h),h<0||h>=fs)throw new Error("arx: counter overflow");if(d.length<f)throw new Error(`arx: output (${d.length}) is shorter than data (${f})`);let u=[],y=a.length,m,S;if(y===32)u.push(m=Lt(a)),S=Hl;else if(y===16&&n)m=new Uint8Array(32),m.set(a),m.set(a,16),S=Ol,u.push(m);else throw se(a,32,"arx key"),new Error("invalid key size");io(c)||u.push(c=Lt(c));let R=Ue(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(S,R,Ue(c.subarray(0,16)),R),c=c.subarray(16)}let N=16-o;if(N!==c.length)throw new Error(`arx: nonce must be ${N} or 16 bytes`);if(N!==12){let M=new Uint8Array(12);M.set(c,i?0:12-c.length),c=M,u.push(c)}let _=Ue(c);return Ml(t,S,R,_,l,d,h,s),Oe(...u),d}}function ce(t,e){return t[e++]&255|(t[e++]&255)<<8}var ao=class{constructor(e){v(this,"blockLen",16);v(this,"outputLen",16);v(this,"buffer",new Uint8Array(16));v(this,"r",new Uint16Array(10));v(this,"h",new Uint16Array(10));v(this,"pad",new Uint16Array(8));v(this,"pos",0);v(this,"finished",!1);e=Lt(se(e,32,"key"));let n=ce(e,0),r=ce(e,2),o=ce(e,4),i=ce(e,6),s=ce(e,8),a=ce(e,10),c=ce(e,12),l=ce(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>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 d=0;d<8;d++)this.pad[d]=ce(e,16+2*d)}process(e,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],h=s[4],f=s[5],u=s[6],y=s[7],m=s[8],S=s[9],R=ce(e,n+0),N=ce(e,n+2),_=ce(e,n+4),M=ce(e,n+6),U=ce(e,n+8),D=ce(e,n+10),j=ce(e,n+12),Z=ce(e,n+14),L=i[0]+(R&8191),z=i[1]+((R>>>13|N<<3)&8191),$=i[2]+((N>>>10|_<<6)&8191),T=i[3]+((_>>>7|M<<9)&8191),x=i[4]+((M>>>4|U<<12)&8191),g=i[5]+(U>>>1&8191),p=i[6]+((U>>>14|D<<2)&8191),b=i[7]+((D>>>11|j<<5)&8191),E=i[8]+((j>>>8|Z<<8)&8191),k=i[9]+(Z>>>5|o),w=0,A=w+L*a+z*(5*S)+$*(5*m)+T*(5*y)+x*(5*u);w=A>>>13,A&=8191,A+=g*(5*f)+p*(5*h)+b*(5*d)+E*(5*l)+k*(5*c),w+=A>>>13,A&=8191;let B=w+L*c+z*a+$*(5*S)+T*(5*m)+x*(5*y);w=B>>>13,B&=8191,B+=g*(5*u)+p*(5*f)+b*(5*h)+E*(5*d)+k*(5*l),w+=B>>>13,B&=8191;let C=w+L*l+z*c+$*a+T*(5*S)+x*(5*m);w=C>>>13,C&=8191,C+=g*(5*y)+p*(5*u)+b*(5*f)+E*(5*h)+k*(5*d),w+=C>>>13,C&=8191;let O=w+L*d+z*l+$*c+T*a+x*(5*S);w=O>>>13,O&=8191,O+=g*(5*m)+p*(5*y)+b*(5*u)+E*(5*f)+k*(5*h),w+=O>>>13,O&=8191;let q=w+L*h+z*d+$*l+T*c+x*a;w=q>>>13,q&=8191,q+=g*(5*S)+p*(5*m)+b*(5*y)+E*(5*u)+k*(5*f),w+=q>>>13,q&=8191;let P=w+L*f+z*h+$*d+T*l+x*c;w=P>>>13,P&=8191,P+=g*a+p*(5*S)+b*(5*m)+E*(5*y)+k*(5*u),w+=P>>>13,P&=8191;let I=w+L*u+z*f+$*h+T*d+x*l;w=I>>>13,I&=8191,I+=g*c+p*a+b*(5*S)+E*(5*m)+k*(5*y),w+=I>>>13,I&=8191;let V=w+L*y+z*u+$*f+T*h+x*d;w=V>>>13,V&=8191,V+=g*l+p*c+b*a+E*(5*S)+k*(5*m),w+=V>>>13,V&=8191;let W=w+L*m+z*y+$*u+T*f+x*h;w=W>>>13,W&=8191,W+=g*d+p*l+b*c+E*a+k*(5*S),w+=W>>>13,W&=8191;let K=w+L*S+z*m+$*y+T*u+x*f;w=K>>>13,K&=8191,K+=g*h+p*d+b*l+E*c+k*a,w+=K>>>13,K&=8191,w=(w<<2)+w|0,w=w+A|0,A=w&8191,w=w>>>13,B+=w,i[0]=A,i[1]=B,i[2]=C,i[3]=O,i[4]=q,i[5]=P,i[6]=I,i[7]=V,i[8]=W,i[9]=K}finalize(){let{h:e,pad:n}=this,r=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,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[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 s=e[0]+n[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+n[a]|0)+(s>>>16)|0,e[a]=s&65535;Oe(r)}update(e){no(this),se(e),e=Lt(e);let{buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){no(this),is(e,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=r[s]>>>0,e[i++]=r[s]>>>8;return e}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}};function ql(t){let e=(r,o)=>t(o).update(r).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}var us=ql(t=>new ao(t));function gs(t,e,n,r,o,i=20){let s=t[0],a=t[1],c=t[2],l=t[3],d=e[0],h=e[1],f=e[2],u=e[3],y=e[4],m=e[5],S=e[6],R=e[7],N=o,_=n[0],M=n[1],U=n[2],D=s,j=a,Z=c,L=l,z=d,$=h,T=f,x=u,g=y,p=m,b=S,E=R,k=N,w=_,A=M,B=U;for(let O=0;O<i;O+=2)D=D+z|0,k=H(k^D,16),g=g+k|0,z=H(z^g,12),D=D+z|0,k=H(k^D,8),g=g+k|0,z=H(z^g,7),j=j+$|0,w=H(w^j,16),p=p+w|0,$=H($^p,12),j=j+$|0,w=H(w^j,8),p=p+w|0,$=H($^p,7),Z=Z+T|0,A=H(A^Z,16),b=b+A|0,T=H(T^b,12),Z=Z+T|0,A=H(A^Z,8),b=b+A|0,T=H(T^b,7),L=L+x|0,B=H(B^L,16),E=E+B|0,x=H(x^E,12),L=L+x|0,B=H(B^L,8),E=E+B|0,x=H(x^E,7),D=D+$|0,B=H(B^D,16),b=b+B|0,$=H($^b,12),D=D+$|0,B=H(B^D,8),b=b+B|0,$=H($^b,7),j=j+T|0,k=H(k^j,16),E=E+k|0,T=H(T^E,12),j=j+T|0,k=H(k^j,8),E=E+k|0,T=H(T^E,7),Z=Z+x|0,w=H(w^Z,16),g=g+w|0,x=H(x^g,12),Z=Z+x|0,w=H(w^Z,8),g=g+w|0,x=H(x^g,7),L=L+z|0,A=H(A^L,16),p=p+A|0,z=H(z^p,12),L=L+z|0,A=H(A^L,8),p=p+A|0,z=H(z^p,7);let C=0;r[C++]=s+D|0,r[C++]=a+j|0,r[C++]=c+Z|0,r[C++]=l+L|0,r[C++]=d+z|0,r[C++]=h+$|0,r[C++]=f+T|0,r[C++]=u+x|0,r[C++]=y+g|0,r[C++]=m+p|0,r[C++]=S+b|0,r[C++]=R+E|0,r[C++]=N+k|0,r[C++]=_+w|0,r[C++]=M+A|0,r[C++]=U+B|0}function Dl(t,e,n,r){let o=t[0],i=t[1],s=t[2],a=t[3],c=e[0],l=e[1],d=e[2],h=e[3],f=e[4],u=e[5],y=e[6],m=e[7],S=n[0],R=n[1],N=n[2],_=n[3];for(let U=0;U<20;U+=2)o=o+c|0,S=H(S^o,16),f=f+S|0,c=H(c^f,12),o=o+c|0,S=H(S^o,8),f=f+S|0,c=H(c^f,7),i=i+l|0,R=H(R^i,16),u=u+R|0,l=H(l^u,12),i=i+l|0,R=H(R^i,8),u=u+R|0,l=H(l^u,7),s=s+d|0,N=H(N^s,16),y=y+N|0,d=H(d^y,12),s=s+d|0,N=H(N^s,8),y=y+N|0,d=H(d^y,7),a=a+h|0,_=H(_^a,16),m=m+_|0,h=H(h^m,12),a=a+h|0,_=H(_^a,8),m=m+_|0,h=H(h^m,7),o=o+l|0,_=H(_^o,16),y=y+_|0,l=H(l^y,12),o=o+l|0,_=H(_^o,8),y=y+_|0,l=H(l^y,7),i=i+d|0,S=H(S^i,16),m=m+S|0,d=H(d^m,12),i=i+d|0,S=H(S^i,8),m=m+S|0,d=H(d^m,7),s=s+h|0,R=H(R^s,16),f=f+R|0,h=H(h^f,12),s=s+h|0,R=H(R^s,8),f=f+R|0,h=H(h^f,7),a=a+c|0,N=H(N^a,16),u=u+N|0,c=H(c^u,12),a=a+c|0,N=H(N^a,8),u=u+N|0,c=H(c^u,7);let M=0;r[M++]=o,r[M++]=i,r[M++]=s,r[M++]=a,r[M++]=S,r[M++]=R,r[M++]=N,r[M++]=_}var ft=so(gs,{counterRight:!1,counterLength:4,allowShortKeys:!1}),$l=so(gs,{counterRight:!1,counterLength:8,extendNonceFn:Dl,allowShortKeys:!1});var Vl=new Uint8Array(16),ds=(t,e)=>{t.update(e);let n=e.length%16;n&&t.update(Vl.subarray(n))},Kl=new Uint8Array(32);function hs(t,e,n,r,o){o!==void 0&&se(o,void 0,"AAD");let i=t(e,n,Kl),s=as(r.length,o?o.length:0,!0),a=us.create(i);o&&ds(a,o),ds(a,r),a.update(s);let c=a.digest();return Oe(i,s),c}var ps=t=>(e,n,r)=>({encrypt(i,s){let a=i.length;s=oo(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);t(e,n,c,c,1);let l=hs(t,e,n,c,r);return s.set(l,a),Oe(l),s},decrypt(i,s){s=oo(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=hs(t,e,n,a,r);if(!Tt(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Oe(l),s}}),Ah=ro({blockSize:64,nonceLength:12,tagLength:16},ps(ft)),Rh=ro({blockSize:64,nonceLength:24,tagLength:16},ps($l));function jn(t,e,n){return st(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Te(t,n,e)}var co=Uint8Array.of(0),ys=Uint8Array.of();function Zn(t,e,n,r=32){st(t),we(r,"length");let o=t.outputLen;if(r>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/o);n===void 0?n=ys:Y(n,void 0,"info");let s=new Uint8Array(i*o),a=Te.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)co[0]=d+1,c.update(d===0?ys:l).update(n).update(co).digestInto(l),s.set(l,o*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ie(l,co),s.slice(0,r)}function ho(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zl(t){if(!ho(t))throw new Error("Uint8Array expected")}function xs(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function jl(t){if(typeof t!="function")throw new Error("function expected");return!0}function ut(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function go(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function lo(t){if(!Array.isArray(t))throw new Error("array expected")}function Wn(t,e){if(!xs(!0,e))throw new Error(`${t}: array of strings expected`)}function Es(t,e){if(!xs(!1,e))throw new Error(`${t}: array of numbers expected`)}function vs(...t){let e=i=>i,n=(i,s)=>a=>i(s(a)),r=t.map(i=>i.encode).reduceRight(n,e),o=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:o}}function Ss(t){let e=typeof t=="string"?t.split(""):t,n=e.length;Wn("alphabet",e);let r=new Map(e.map((o,i)=>[o,i]));return{encode:o=>(lo(o),o.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:o=>(lo(o),o.map(i=>{ut("alphabet.decode",i);let s=r.get(i);if(s===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return s}))}}function Bs(t=""){return ut("join",t),{encode:e=>(Wn("join.decode",e),e.join(t)),decode:e=>(ut("join.decode",e),e.split(t))}}function Zl(t,e="="){return go(t),ut("padding",e),{encode(n){for(Wn("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Wn("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}var ks=(t,e)=>e===0?t:ks(e,t%e),Yn=(t,e)=>t+(e-ks(t,e)),Gn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function fo(t,e,n,r){if(lo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Yn(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Yn(e,n)}`);let o=0,i=0,s=Gn[e],a=Gn[n]-1,c=[];for(let l of t){if(go(l),l>=s)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((o>>i-n&a)>>>0);let d=Gn[i];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function As(t,e=!1){if(go(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Yn(8,t)>32||Yn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!ho(n))throw new Error("radix2.encode input should be Uint8Array");return fo(Array.from(n),8,t,!e)},decode:n=>(Es("radix2.decode",n),Uint8Array.from(fo(n,t,8,e)))}}function bs(t){return jl(t),function(...e){try{return t.apply(null,e)}catch{}}}var Gl=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Wl=(t,e)=>{ut("base64",t);let n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},It=Gl?{encode(t){return zl(t),t.toBase64()},decode(t){return Wl(t,!1)}}:vs(As(6),Ss("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Zl(6),Bs(""));var uo=vs(Ss("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Bs("")),ms=[996825010,642813549,513874426,1027748829,705979059];function on(t){let e=t>>25,n=(t&33554431)<<5;for(let r=0;r<ms.length;r++)(e>>r&1)===1&&(n^=ms[r]);return n}function ws(t,e,n=1){let r=t.length,o=1;for(let i=0;i<r;i++){let s=t.charCodeAt(i);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);o=on(o)^s>>5}o=on(o);for(let i=0;i<r;i++)o=on(o)^t.charCodeAt(i)&31;for(let i of e)o=on(o)^i;for(let i=0;i<6;i++)o=on(o);return o^=n,uo.encode(fo([o%Gn[30]],30,5,!1))}function Yl(t){let e=t==="bech32"?1:734539939,n=As(5),r=n.decode,o=n.encode,i=bs(r);function s(h,f,u=90){ut("bech32.encode prefix",h),ho(f)&&(f=Array.from(f)),Es("bech32.encode",f);let y=h.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);let m=y+7+f.length;if(u!==!1&&m>u)throw new TypeError(`Length ${m} exceeds limit ${u}`);let S=h.toLowerCase(),R=ws(S,f,e);return`${S}1${uo.encode(f)}${R}`}function a(h,f=90){ut("bech32.decode input",h);let u=h.length;if(u<8||f!==!1&&u>f)throw new TypeError(`invalid string length: ${u} (${h}). Expected (8..${f})`);let y=h.toLowerCase();if(h!==y&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");let m=y.lastIndexOf("1");if(m===0||m===-1)throw new Error('Letter "1" must be present between prefix and data only');let S=y.slice(0,m),R=y.slice(m+1);if(R.length<6)throw new Error("Data must be at least 6 characters long");let N=uo.decode(R).slice(0,-6),_=ws(S,N,e);if(!R.endsWith(_))throw new Error(`Invalid checksum in ${h}: expected "${_}"`);return{prefix:S,words:N}}let c=bs(a);function l(h){let{prefix:f,words:u}=a(h,!1);return{prefix:f,words:u,bytes:r(u)}}function d(h,f){return s(h,o(f))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:i,toWords:o}}var po=Yl("bech32");var dt=Symbol("verified"),Jl=t=>t instanceof Object;function Xl(t){if(!Jl(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var Fl=new TextDecoder("utf-8"),wo=new TextEncoder;function sn(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}var Ql=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=yo(n),n.sig=ee(xe.sign(ne(yo(n)),e)),n[dt]=!0,n}verifyEvent(t){if(typeof t[dt]=="boolean")return t[dt];try{let e=yo(t);if(e!==t.id)return t[dt]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[dt]=n,n}catch{return t[dt]=!1,!1}}};function ef(t){if(!Xl(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 yo(t){let e=fe(wo.encode(ef(t)));return ee(e)}var Jn=new Ql,Hh=Jn.generateSecretKey,Rs=Jn.getPublicKey,tf=Jn.finalizeEvent,Ts=Jn.verifyEvent,Ls=1,Is=65535;function bo(t,e){let n=$n.getSharedSecret(t,ne("02"+e)).subarray(1,33);return jn(fe,n,wo.encode("nip44-v2"))}function Ns(t,e){let n=Zn(fe,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function _s(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=1<<Math.floor(Math.log2(t-1))+1,n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function nf(t){if(!Number.isSafeInteger(t)||t<Ls||t>Is)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 rf(t){let e=wo.encode(t),n=e.length,r=nf(n),o=new Uint8Array(_s(n)-n);return te(r,e,o)}function of(t){let e=new DataView(t.buffer).getUint16(0),n=t.subarray(2,2+e);if(e<Ls||e>Is||n.length!==e||t.length!==2+_s(e))throw new Error("invalid padding");return Fl.decode(n)}function Us(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Te(fe,t,r)}function sf(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=It.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function af(t,e,n=Be(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ns(e,n),s=rf(t),a=ft(r,o,s),c=Us(i,a,n);return It.encode(te(new Uint8Array([2]),n,a,c))}function Cs(t,e){let{nonce:n,ciphertext:r,mac:o}=sf(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ns(e,n),c=Us(a,r,n);if(!Tt(c,o))throw new Error("invalid MAC");let l=ft(i,s,r);return of(l)}var cf=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,lf;try{lf=fetch}catch{}var ff=22242,mo=24133;function uf(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),o=t[`#${r}`];if(o&&!e.tags.find(([i,s])=>i===n.slice(1)&&o.indexOf(s)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function df(t,e){for(let n=0;n<t.length;n++)if(uf(t[n],e))return!0;return!1}function hf(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,o=t.slice(r).indexOf('"')+r+1;return t.slice(o,o+64)}function gf(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,o=t.slice(r+1,80).indexOf('"');if(o===-1)return null;let i=r+1+o;return t.slice(r+1,i)}function pf(t,e){return{kind:ff,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var Os=class extends Error{constructor(t,e){super(`Tried to send message '${t} on a closed connection to ${e}.`),this.name="SendingOnClosedConnection"}},Hs=class{constructor(t,e){v(this,"url");v(this,"_connected",!1);v(this,"onclose",null);v(this,"onnotice",t=>console.debug(`NOTICE from ${this.url}: ${t}`));v(this,"onauth");v(this,"baseEoseTimeout",4400);v(this,"publishTimeout",4400);v(this,"pingFrequency",29e3);v(this,"pingTimeout",2e4);v(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);v(this,"openSubs",new Map);v(this,"enablePing");v(this,"enableReconnect");v(this,"idleSince",Date.now());v(this,"ongoingOperations",0);v(this,"reconnectTimeoutHandle");v(this,"pingIntervalHandle");v(this,"reconnectAttempts",0);v(this,"skipReconnection",!1);v(this,"connectionPromise");v(this,"openCountRequests",new Map);v(this,"openEventPublishes",new Map);v(this,"ws");v(this,"challenge");v(this,"authPromise");v(this,"serial",0);v(this,"verifyEvent");v(this,"_WebSocket");this.url=sn(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1}static async connect(t,e){let n=new Hs(t,e);return await n.connect(e),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){let t=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},t)}handleHardClose(t){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(t))}async connect(t){let e;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{t?.timeout&&(e=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},t.timeout)),t?.abort&&(t.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(o){clearTimeout(e),r(o);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(e),this._connected=!0;let o=this.reconnectAttempts>0;this.reconnectAttempts=0;for(let i of this.openSubs.values()){if(i.eosed=!1,o)for(let s=0;s<i.filters.length;s++)i.lastEmitted&&(i.filters[s].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(e),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=o=>{clearTimeout(e),r(o.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(t=>{this.ws.once("pong",()=>t(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((t,e)=>{if(!this.connectionPromise)return e(new Error(`no connection to ${this.url}, can't ping`));try{let n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{t(!0),n.close()},onclose(){t(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){e(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(e=>setTimeout(()=>e(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(t){if(!this.connectionPromise)throw new Os(t,this.url);this.connectionPromise.then(()=>{this.ws?.send(t)})}async auth(t){let e=this.challenge;if(!e)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let o=await t(pf(this.url,e)),i=setTimeout(()=>{let s=this.openEventPublishes.get(o.id);s&&(s.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))},this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(o){console.warn("subscribe auth function failed:",o)}}),this.authPromise)}async publish(t){this.idleSince=void 0,this.ongoingOperations++;let e=new Promise((n,r)=>{let o=setTimeout(()=>{let i=this.openEventPublishes.get(t.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))},this.publishTimeout);this.openEventPublishes.set(t.id,{resolve:n,reject:r,timeout:o})});return this.send('["EVENT",'+JSON.stringify(t)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),e}async count(t,e){this.serial++;let n=e?.id||"count:"+this.serial,r=new Promise((o,i)=>{this.openCountRequests.set(n,{resolve:o,reject:i})});return this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1)),r}subscribe(t,e){e.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);let n=this.prepareSubscription(t,e);return n.fire(),e.abort&&(e.abort.onabort=()=>n.close(String(e.abort.reason||"<aborted>"))),n}prepareSubscription(t,e){this.serial++;let n=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new yf(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(t){let e=t.data;if(!e)return;let n=gf(e);if(n){let r=this.openSubs.get(n);if(!r)return;let o=hf(e,"id"),i=r.alreadyHaveEvent?.(o);if(r.receivedEvent?.(this,o),i)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{let o=this.openSubs.get(r[1]),i=r[2];this.verifyEvent(i)&&df(o.filters,i)?o.onevent(i):o.oninvalidevent?.(i),(!o.lastEmitted||o.lastEmitted<i.created_at)&&(o.lastEmitted=i.created_at);return}case"COUNT":{let o=r[1],i=r[2],s=this.openCountRequests.get(o);s&&(s.resolve(i.count),this.openCountRequests.delete(o));return}case"EOSE":{let o=this.openSubs.get(r[1]);if(!o)return;o.receivedEose();return}case"OK":{let o=r[1],i=r[2],s=r[3],a=this.openEventPublishes.get(o);a&&(clearTimeout(a.timeout),i?a.resolve(s):a.reject(new Error(s)),this.openEventPublishes.delete(o));return}case"CLOSED":{let o=r[1],i=this.openSubs.get(o);if(!i)return;i.closed=!0,i.close(r[2]);return}case"NOTICE":{this.onnotice(r[1]);return}case"AUTH":{this.challenge=r[1],this.onauth&&this.auth(this.onauth);return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{let[o,i,s]=JSON.parse(e);console.warn(`[nostr] relay ${this.url} error processing message:`,r,s)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},yf=class{constructor(t,e,n,r){v(this,"relay");v(this,"id");v(this,"lastEmitted");v(this,"closed",!1);v(this,"eosed",!1);v(this,"filters");v(this,"alreadyHaveEvent");v(this,"receivedEvent");v(this,"onevent");v(this,"oninvalidevent");v(this,"oneose");v(this,"onclose");v(this,"oncustom");v(this,"eoseTimeout");v(this,"eoseTimeoutHandle");if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof Os))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(t)}},bf=t=>(t[dt]=!0,!0),mf=class{constructor(t){v(this,"relays",new Map);v(this,"seenOn",new Map);v(this,"trackRelays",!1);v(this,"verifyEvent");v(this,"enablePing");v(this,"enableReconnect");v(this,"automaticallyAuth");v(this,"trustedRelayURLs",new Set);v(this,"onRelayConnectionFailure");v(this,"onRelayConnectionSuccess");v(this,"allowConnectingToRelay");v(this,"maxWaitForConnection");v(this,"_WebSocket");this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,this.automaticallyAuth=t.automaticallyAuth,this.onRelayConnectionFailure=t.onRelayConnectionFailure,this.onRelayConnectionSuccess=t.onRelayConnectionSuccess,this.allowConnectingToRelay=t.allowConnectingToRelay,this.maxWaitForConnection=t.maxWaitForConnection||3e3}async ensureRelay(t,e){t=sn(t);let n=this.relays.get(t);if(n||(n=new Hs(t,{verifyEvent:this.trustedRelayURLs.has(t)?bf:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),n.onclose=()=>{this.relays.delete(t)},this.relays.set(t,n)),this.automaticallyAuth){let r=this.automaticallyAuth(t);r&&(n.onauth=r)}try{await n.connect({timeout:e?.connectionTimeout,abort:e?.abort})}catch(r){throw this.relays.delete(t),r}return n}close(t){t.map(sn).forEach(e=>{this.relays.get(e)?.close(),this.relays.delete(e)})}subscribe(t,e,n){let r=[],o=[];for(let i=0;i<t.length;i++){let s=sn(t[i]);r.find(a=>a.url===s)||o.indexOf(s)===-1&&(o.push(s),r.push({url:s,filter:e}))}return this.subscribeMap(r,n)}subscribeMany(t,e,n){return this.subscribe(t,e,n)}subscribeMap(t,e){let n=new Map;for(let f of t){let{url:u,filter:y}=f;n.has(u)||n.set(u,[]),n.get(u).push(y)}let r=Array.from(n.entries()).map(([f,u])=>({url:f,filters:u}));this.trackRelays&&(e.receivedEvent=(f,u)=>{let y=this.seenOn.get(u);y||(y=new Set,this.seenOn.set(u,y)),y.add(f)});let o=new Set,i=[],s=[],a=f=>{s[f]||(s[f]=!0,s.filter(u=>u).length===r.length&&(e.oneose?.(),a=()=>{}))},c=[],l=(f,u)=>{c[f]||(a(f),c[f]=u,c.filter(y=>y).length===r.length&&(e.onclose?.(c),l=()=>{}))},d=f=>{if(e.alreadyHaveEvent?.(f))return!0;let u=o.has(f);return o.add(f),u},h=Promise.all(r.map(async({url:f,filters:u},y)=>{if(this.allowConnectingToRelay?.(f,["read",u])===!1){l(y,"connection skipped by allowConnectingToRelay");return}let m;try{m=await this.ensureRelay(f,{connectionTimeout:this.maxWaitForConnection<(e.maxWait||0)?Math.max(e.maxWait*.8,e.maxWait-1e3):this.maxWaitForConnection,abort:e.abort})}catch(R){this.onRelayConnectionFailure?.(f),l(y,R?.message||String(R));return}this.onRelayConnectionSuccess?.(f);let S=m.subscribe(u,{...e,oneose:()=>a(y),onclose:R=>{R.startsWith("auth-required: ")&&e.onauth?m.auth(e.onauth).then(()=>{m.subscribe(u,{...e,oneose:()=>a(y),onclose:N=>{l(y,N)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort})}).catch(N=>{l(y,`auth was required and attempted, but failed with: ${N}`)}):l(y,R)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort});i.push(S)}));return{async close(f){await h,i.forEach(u=>{u.close(f)})}}}subscribeEose(t,e,n){let r;return r=this.subscribe(t,e,{...n,oneose(){let o="closed automatically on eose";r?r.close(o):n.onclose?.(t.map(i=>o))}}),r}subscribeManyEose(t,e,n){return this.subscribeEose(t,e,n)}async querySync(t,e,n){return new Promise(async r=>{let o=[];this.subscribeEose(t,e,{...n,onevent(i){o.push(i)},onclose(i){r(o)}})})}async get(t,e,n){e.limit=1;let r=await this.querySync(t,e,n);return r.sort((o,i)=>i.created_at-o.created_at),r[0]||null}publish(t,e,n){return t.map(sn).map(async(r,o,i)=>{if(i.indexOf(r)!==o)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(r,["write",e])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let s;try{s=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(a){return this.onRelayConnectionFailure?.(r),"connection failure: "+String(a)}return s.publish(e).catch(async a=>{if(a instanceof Error&&a.message.startsWith("auth-required: ")&&n?.onauth)return await s.auth(n.onauth),s.publish(e);throw a}).then(a=>{if(this.trackRelays){let c=this.seenOn.get(e.id);c||(c=new Set,this.seenOn.set(e.id,c)),c.add(s)}return a})})}listConnectionStatus(){let t=new Map;return this.relays.forEach((e,n)=>t.set(n,e.connected)),t}destroy(){this.relays.forEach(t=>t.close()),this.relays=new Map}pruneIdleRelays(t=1e4){let e=[];for(let[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=t&&(this.relays.delete(n),e.push(n),r.close());return e}},Ps;try{Ps=WebSocket}catch{}var wf=class extends mf{constructor(t){super({verifyEvent:Ts,websocketImplementation:Ps,maxWaitForConnection:3e3,...t})}},Ms;try{Ms=fetch}catch{}var xf=/^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/;async function qs(t){let e=t.match(xf);if(e)try{let n=e[1],r=new URLSearchParams(e[2]);return{pubkey:n,relays:r.getAll("relay"),secret:r.get("secret")}}catch{}return Ef(t)}async function Ef(t){let e=t.match(cf);if(!e)return null;let[n,r="_",o]=e;try{let i=`https://${o}/.well-known/nostr.json?name=${r}`,s=await(await Ms(i,{redirect:"error"})).json(),a=s.names[r],c=s.nip46[a]||[];return{pubkey:a,relays:c,secret:null}}catch{return null}}var Nt=class{constructor(t,e){v(this,"params");v(this,"pool");v(this,"subCloser");v(this,"isOpen");v(this,"serial");v(this,"idPrefix");v(this,"listeners");v(this,"waitingForAuth");v(this,"secretKey");v(this,"conversationKey");v(this,"bp");v(this,"cachedPubKey");this.params=e,this.pool=e.pool||new wf,this.secretKey=t,this.isOpen=!1,this.idPrefix=Math.random().toString(36).substring(7),this.serial=0,this.listeners={},this.waitingForAuth={}}static fromBunker(t,e,n={}){if(e.relays.length===0)throw new Error("no relays specified for this bunker");let r=new Nt(t,n);return r.conversationKey=bo(t,e.pubkey),r.bp=e,r.setupSubscription(),r}static async fromURI(t,e,n={},r=3e5){let o=new Nt(t,n),i=new URL(e),s=Rs(t);return new Promise((a,c)=>{let l=!1,d=o.pool.subscribe(i.searchParams.getAll("relay"),{kinds:[mo],"#p":[s],limit:0},{onevent:async h=>{try{let f=bo(t,h.pubkey),u=Cs(h.content,f);JSON.parse(u).result===i.searchParams.get("secret")&&(d.close(),o.bp={pubkey:h.pubkey,relays:i.searchParams.getAll("relay"),secret:i.searchParams.get("secret")},o.conversationKey=bo(t,h.pubkey),o.setupSubscription(),l=!0,await Promise.race([new Promise(m=>setTimeout(m,1e3)),o.switchRelays()]),a(o))}catch(f){console.warn("failed to process potential connection event",f)}},onclose:()=>{l||c(new Error("subscription closed before connection was established."))},maxWait:typeof r=="number"?r:void 0,abort:typeof r!="number"?r:void 0})})}setupSubscription(){let t=this.listeners,e=this.waitingForAuth,n=this.conversationKey;this.subCloser=this.pool.subscribe(this.bp.relays,{kinds:[mo],authors:[this.bp.pubkey],"#p":[Rs(this.secretKey)],limit:0},{onevent:async r=>{let o=JSON.parse(Cs(r.content,n)),{id:i,result:s,error:a}=o;if(s==="auth_url"&&e[i]){delete e[i],this.params.onauth?this.params.onauth(a):console.warn(`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${a}' but there was no onauth() callback configured.`);return}let c=t[i];c&&(a?c.reject(a):s&&c.resolve(s),delete t[i])},onclose:()=>{this.subCloser=void 0}}),this.isOpen=!0}async switchRelays(){try{let t=await this.sendRequest("switch_relays",[]),e=JSON.parse(t);if(!e||JSON.stringify(e.sort())===JSON.stringify(this.bp.relays))return!1;this.bp.relays=e;let n=this.subCloser;return setTimeout(()=>{n.close()},5e3),this.subCloser=void 0,this.setupSubscription(),!0}catch{return!1}}async close(){this.isOpen=!1,this.subCloser.close()}async sendRequest(t,e){return new Promise(async(n,r)=>{try{if(!this.isOpen)throw new Error("this signer is not open anymore, create a new one");this.subCloser||this.setupSubscription(),this.serial++;let o=`${this.idPrefix}-${this.serial}`,i=af(JSON.stringify({id:o,method:t,params:e}),this.conversationKey),s=tf({kind:mo,tags:[["p",this.bp.pubkey]],content:i,created_at:Math.floor(Date.now()/1e3)},this.secretKey);this.listeners[o]={resolve:n,reject:r},this.waitingForAuth[o]=!0,await Promise.any(this.pool.publish(this.bp.relays,s))}catch(o){r(o)}})}async ping(){let t=await this.sendRequest("ping",[]);if(t!=="pong")throw new Error(`result is not pong: ${t}`)}async connect(){await this.sendRequest("connect",[this.bp.pubkey,this.bp.secret||""])}async getPublicKey(){return this.cachedPubKey||(this.cachedPubKey=await this.sendRequest("get_public_key",[])),this.cachedPubKey}async signEvent(t){let e=await this.sendRequest("sign_event",[JSON.stringify(t)]),n=JSON.parse(e);if(Ts(n))return n;throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(n)}`)}async nip04Encrypt(t,e){return await this.sendRequest("nip04_encrypt",[t,e])}async nip04Decrypt(t,e){return await this.sendRequest("nip04_decrypt",[t,e])}async nip44Encrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}async nip44Decrypt(t,e){return await this.sendRequest("nip44_decrypt",[t,e])}};var _t=Symbol("verified"),vf=t=>t instanceof Object;function Sf(t){if(!vf(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var r0=new TextDecoder("utf-8"),Bf=new TextEncoder,kf=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=xo(n),n.sig=ee(xe.sign(ne(xo(n)),e)),n[_t]=!0,n}verifyEvent(t){if(typeof t[_t]=="boolean")return t[_t];try{let e=xo(t);if(e!==t.id)return t[_t]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[_t]=n,n}catch{return t[_t]=!1,!1}}};function Af(t){if(!Sf(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 xo(t){let e=fe(Bf.encode(Af(t)));return ee(e)}var Xn=new kf,o0=Xn.generateSecretKey,Ds=Xn.getPublicKey,$s=Xn.finalizeEvent,i0=Xn.verifyEvent;var Fn=new TextDecoder("utf-8"),f0=new TextEncoder;var Rf=5e3;function Vs(t){let{prefix:e,words:n}=po.decode(t,Rf),r=new Uint8Array(po.fromWords(n));switch(e){case"nprofile":{let o=Eo(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:ee(o[0][0]),relays:o[1]?o[1].map(i=>Fn.decode(i)):[]}}}case"nevent":{let o=Eo(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:ee(o[0][0]),relays:o[1]?o[1].map(i=>Fn.decode(i)):[],author:o[2]?.[0]?ee(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(ee(o[3][0]),16):void 0}}}case"naddr":{let o=Eo(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Fn.decode(o[0][0]),pubkey:ee(o[2][0]),kind:parseInt(ee(o[3][0]),16),relays:o[1]?o[1].map(i=>Fn.decode(i)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:ee(r)};default:throw new Error(`unknown prefix ${e}`)}}function Eo(t){let e={},n=t;for(;n.length>0;){let r=n[0],o=n[1],i=n.slice(2,2+o);if(n=n.slice(2+o),i.length<o)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(i)}return e}var Cf=new TextDecoder("utf-8"),Ks=new TextEncoder,zs=1,js=65535;function Ut(t,e){let n=$n.getSharedSecret(t,ne("02"+e)).subarray(1,33);return jn(fe,n,Ks.encode("nip44-v2"))}function Zs(t,e){let n=Zn(fe,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Gs(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=1<<Math.floor(Math.log2(t-1))+1,n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function Tf(t){if(!Number.isSafeInteger(t)||t<zs||t>js)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 Lf(t){let e=Ks.encode(t),n=e.length,r=Tf(n),o=new Uint8Array(Gs(n)-n);return te(r,e,o)}function If(t){let e=new DataView(t.buffer).getUint16(0),n=t.subarray(2,2+e);if(e<zs||e>js||n.length!==e||t.length!==2+Gs(e))throw new Error("invalid padding");return Cf.decode(n)}function Ws(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Te(fe,t,r)}function Nf(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=It.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Ys(t,e,n=Be(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Zs(e,n),s=Lf(t),a=ft(r,o,s),c=Ws(i,a,n);return It.encode(te(new Uint8Array([2]),n,a,c))}function an(t,e){let{nonce:n,ciphertext:r,mac:o}=Nf(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Zs(e,n),c=Ws(a,r,n);if(!Tt(c,o))throw new Error("invalid MAC");let l=ft(i,s,r);return If(l)}function cn(){return typeof window<"u"&&!!window.nostr&&typeof window.nostr.signEvent=="function"}var vo=class{constructor(e,n){this.pubkey=e;this.provider=n;this.method="nip07";this.capabilities={canSignEvents:!0,hasNip44:!!n.nip44},n.nip44&&(this.nip44={encrypt:(r,o)=>n.nip44.encrypt(r,o),decrypt:(r,o)=>n.nip44.decrypt(r,o)})}async signEvent(e){return this.provider.signEvent(e)}async close(){}};async function ln(){if(!cn())throw new Error("no-nip07-provider");let t=window.nostr,e=await t.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-pubkey-from-nip07");return new vo(e.toLowerCase(),t)}var Qn=class{constructor(e,n,r,o){this.pubkey=e;this.bunker=n;this.bunkerUri=r;this.clientSecretKey=o;this.method="bunker";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:(i,s)=>n.nip44Encrypt(i,s),decrypt:(i,s)=>n.nip44Decrypt(i,s)}}async signEvent(e){let{pubkey:n,...r}=e,o={kind:r.kind,content:r.content,created_at:r.created_at??Math.floor(Date.now()/1e3),tags:r.tags??[]};return await this.bunker.signEvent(o)}async close(){await this.bunker.close()}};async function Js(t){let{uri:e,clientSecretKey:n,abortSignal:r}=t;if(n.length!==32)throw new Error("invalid-client-secret-key");let o=r?await Nt.fromURI(n,e,void 0,r):await Nt.fromURI(n,e),i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new Qn(i.toLowerCase(),o,e,n)}function Xs(t){let{clientPubkeyHex:e,relayUrl:n,secret:r}=t;if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-client-pubkey");if(!/^wss?:\/\//.test(n))throw new Error("invalid-relay-url");let o=new URLSearchParams({relay:n,secret:r});return t.perms&&t.perms.length>0&&o.set("perms",t.perms.join(",")),t.appName&&o.set("name",t.appName),t.appUrl&&o.set("url",t.appUrl),`nostrconnect://${e}?${o.toString()}`}async function fn(t){let e=t.uri.trim();if(!e)throw new Error("empty-bunker-uri");let n=await qs(e);if(!n)throw new Error("invalid-bunker-uri");let r=t.clientSecretKey??_f();if(r.length!==32)throw new Error("invalid-client-secret-key");let o=Nt.fromBunker(r,n,{onauth:t.onauth});await o.connect();let i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new Qn(i.toLowerCase(),o,e,r)}function _f(){let t=new Uint8Array(32);return crypto.getRandomValues(t),t}var So=class{constructor(e,n){this.pubkey=e;this.privkey=n;this.method="nsec";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:async(r,o)=>Ys(o,Ut(this.privkey,r)),decrypt:async(r,o)=>an(o,Ut(this.privkey,r))}}async signEvent(e){let n={kind:e.kind,content:e.content,created_at:e.created_at??Math.floor(Date.now()/1e3),tags:e.tags??[]};return $s(n,this.privkey)}async close(){this.privkey.fill(0)}};function Fs(t){let e=t.trim();if(!e)throw new Error("empty-nsec");let n;if(e.startsWith("nsec1")){let o=Vs(e);if(o.type!=="nsec")throw new Error("not-an-nsec");n=o.data}else if(/^[0-9a-f]{64}$/i.test(e)){n=new Uint8Array(32);for(let o=0;o<32;o++)n[o]=parseInt(e.slice(o*2,o*2+2),16)}else throw new Error("invalid-nsec-format");if(n.length!==32)throw new Error("invalid-nsec-length");let r=Ds(n);if(!/^[0-9a-f]{64}$/i.test(r))throw new Error("invalid-pubkey-from-nsec");return new So(r.toLowerCase(),n)}var Ee=class{constructor(e,n){this.pubkey=e;this.authEvent=n;this.method="redirect";this.capabilities={canSignEvents:!1,hasNip44:!1}}async signEvent(e){throw new Error("signer-auth-only: this session was established via redirect and cannot sign new events. Install a NIP-07 extension (bark, Alby) or paste a bunker URI to upgrade.")}async close(){}};function We(t){try{return typeof localStorage<"u"?localStorage.getItem(t):null}catch{return null}}function Ye(t,e){try{typeof localStorage<"u"&&localStorage.setItem(t,e)}catch{}}function Je(t){try{typeof localStorage<"u"&&localStorage.removeItem(t)}catch{}}function Qs(t){Ye(Q.pubkey,t.pubkey),Ye(Q.method,t.method),Ye(Q.authEvent,t.authEventJson),t.bunkerUri!==void 0&&Ye(Q.bunkerUri,t.bunkerUri),t.bunkerClientSkHex!==void 0&&Ye(Q.bunkerClientSk,t.bunkerClientSkHex),t.expiresAt!==void 0&&Ye(Q.expiresAt,String(t.expiresAt)),t.displayName!==void 0&&Ye(Q.displayName,t.displayName)}function ea(){let t=We(Q.pubkey),e=We(Q.method),n=We(Q.authEvent);if(!t||!e||!n||!/^[0-9a-f]{64}$/i.test(t)||e!=="nip07"&&e!=="redirect"&&e!=="bunker"&&e!=="amber")return null;let r;try{if(r=JSON.parse(n),typeof r!="object"||r===null||r.pubkey!==t)return null}catch{return null}let o=We(Q.expiresAt),i=o?Number(o):void 0;if(i!==void 0&&Number.isFinite(i)&&Date.now()>i)return He(),null;let s={pubkey:t,method:e,authEventJson:n},a=We(Q.bunkerUri),c=We(Q.bunkerClientSk),l=We(Q.displayName);return a&&(s.bunkerUri=a),c&&(s.bunkerClientSkHex=c),i!==void 0&&Number.isFinite(i)&&(s.expiresAt=i),l&&(s.displayName=l),s}function He(){Je(Q.pubkey),Je(Q.method),Je(Q.authEvent),Je(Q.bunkerUri),Je(Q.bunkerClientSk),Je(Q.expiresAt),Je(Q.displayName)}function er(t){Ye(Q.pendingRedirect,JSON.stringify(t))}function tr(){let t=We(Q.pendingRedirect);if(!t)return null;try{let e=JSON.parse(t),n=e.challenge,r=e.origin,o=e.appName,i=e.createdAt;return typeof n!="string"||!/^[0-9a-f]{64}$/i.test(n)||typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof i!="number"||!Number.isFinite(i)?null:{challenge:n,origin:r,appName:o,createdAt:i}}catch{return null}}function nr(){Je(Q.pendingRedirect)}function ta(t){let e="";for(let n=0;n<t.length;n++)e+=t[n].toString(16).padStart(2,"0");return e}function na(t){if(t.length%2!==0)throw new Error("odd-hex-length");let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function rr(){return typeof navigator>"u"?!1:/android/i.test(navigator.userAgent)}var ra=/^[0-9a-f]{64}$/i;function Uf(t){return{kind:21236,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["challenge",t.challenge],["origin",t.origin],["app",t.appName]]}}function Of(t){let e=Uf(t),n=JSON.stringify(e),r=typeof btoa=="function"?btoa(n):Buffer.from(n,"utf-8").toString("base64"),o=t.redirectCallback??`${t.origin}/?signet_amber=1`,i=new URLSearchParams({type:"sign_event",compressionType:"base64",returnType:"event",callbackUrl:o});return`nostrsigner:${r}?${i.toString()}`}function oa(t){if(typeof window>"u")throw new Error("signet-login: amber mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};return er(e),window.location.href=Of(t),new Promise(()=>{})}function Hf(){if(typeof window>"u")return;let t=new URL(window.location.href),e=!1;for(let r of["event","signet_amber","error"])t.searchParams.has(r)&&(t.searchParams.delete(r),e=!0);if(!e)return;let n=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,n)}catch{}}function ia(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search);if(!(t.has("signet_amber")||t.has("event")))return{kind:"no-callback"};let n=h=>(nr(),Hf(),h);if(t.get("error")==="denied")return n({kind:"denied"});let r=tr();if(!r)return n({kind:"invalid",reason:"no-pending-state"});if(r.origin!==window.location.origin)return n({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-r.createdAt>Rn)return n({kind:"invalid",reason:"pending-stale"});let o=t.get("event");if(!o)return n({kind:"invalid",reason:"no-event-param"});let i;try{let h;try{h=typeof atob=="function"?atob(o):Buffer.from(o,"base64").toString("utf-8")}catch{h=o}i=JSON.parse(h)}catch{return n({kind:"invalid",reason:"event-malformed"})}if(typeof i!="object"||i===null)return n({kind:"invalid",reason:"event-not-object"});let s=i;if(typeof s.id!="string"||!ra.test(s.id)||typeof s.pubkey!="string"||!ra.test(s.pubkey)||typeof s.sig!="string"||!/^[0-9a-f]{128}$/i.test(s.sig)||typeof s.created_at!="number"||!Array.isArray(s.tags)||s.kind!==21236||typeof s.content!="string")return n({kind:"invalid",reason:"event-shape-invalid"});let a=s.tags.find(h=>Array.isArray(h)&&h[0]==="challenge");if(!a||a[1]!==r.challenge)return n({kind:"invalid",reason:"challenge-mismatch"});let c={id:s.id.toLowerCase(),pubkey:s.pubkey.toLowerCase(),kind:21236,created_at:s.created_at,tags:s.tags,content:s.content,sig:s.sig.toLowerCase()},l=new Ee(c.pubkey,c),d={pubkey:c.pubkey,method:"amber",signer:l,authEvent:c};return n({kind:"session",session:d})}var ht=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function gt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function un(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ae(t,...e){if(!gt(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function or(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");un(t.outputLen),un(t.blockLen)}function Ht(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 aa(t,e){Ae(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function pt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ir(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Re(t,e){return t<<32-e|t>>>e}var ca=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function le(t){if(Ae(t),ca)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Pf[t[n]];return e}var Pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function sa(t){if(t>=Pe._0&&t<=Pe._9)return t-Pe._0;if(t>=Pe.A&&t<=Pe.F)return t-(Pe.A-10);if(t>=Pe.a&&t<=Pe.f)return t-(Pe.a-10)}function yt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(ca)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=sa(t.charCodeAt(i)),a=sa(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function sr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function dn(t){return typeof t=="string"&&(t=sr(t)),Ae(t),t}function pe(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Ae(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}var Ot=class{};function la(t){let e=r=>t().update(dn(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function bt(t=32){if(ht&&typeof ht.getRandomValues=="function")return ht.getRandomValues(new Uint8Array(t));if(ht&&typeof ht.randomBytes=="function")return Uint8Array.from(ht.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Mf(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+l,a,r)}function fa(t,e,n){return t&e^~t&n}function ua(t,e,n){return t&e^t&n^e&n}var ar=class extends Ot{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ir(this.buffer)}update(e){Ht(this),e=dn(e),Ae(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ir(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ht(this),aa(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,pt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let h=s;h<o;h++)n[h]=0;Mf(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=ir(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qf=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]),Xe=new Uint32Array(64),cr=class extends ar{constructor(e=32){super(64,e,8,!1),this.A=Me[0]|0,this.B=Me[1]|0,this.C=Me[2]|0,this.D=Me[3]|0,this.E=Me[4]|0,this.F=Me[5]|0,this.G=Me[6]|0,this.H=Me[7]|0}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)Xe[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){let f=Xe[h-15],u=Xe[h-2],y=Re(f,7)^Re(f,18)^f>>>3,m=Re(u,17)^Re(u,19)^u>>>10;Xe[h]=m+Xe[h-7]+y+Xe[h-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){let f=Re(a,6)^Re(a,11)^Re(a,25),u=d+f+fa(a,c,l)+qf[h]+Xe[h]|0,m=(Re(r,2)^Re(r,13)^Re(r,22))+ua(r,o,i)|0;d=l,l=c,c=a,a=s+u|0,s=i,i=o,o=r,r=u+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){pt(Xe)}destroy(){this.set(0,0,0,0,0,0,0,0),pt(this.buffer)}};var Pt=la(()=>new cr);var lr=class extends Ot{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,or(e);let r=dn(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(r.length>o?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),pt(i)}update(e){return Ht(this),this.iHash.update(e),this}digestInto(e){Ht(this),Ae(e,this.outputLen),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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Bo=(t,e,n)=>new lr(t,e).update(n).digest();Bo.create=(t,e)=>new lr(t,e);var Ro=BigInt(0),Ao=BigInt(1);function hn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Fe(t,e,n=""){let r=gt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function gn(t){let e=t.toString(16);return e.length&1?"0"+e:e}function da(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ro:BigInt("0x"+t)}function qe(t){return da(le(t))}function Co(t){return Ae(t),da(le(Uint8Array.from(t).reverse()))}function Mt(t,e){return yt(t.toString(16).padStart(e*2,"0"))}function To(t,e){return Mt(t,e).reverse()}function re(t,e,n){let r;if(typeof e=="string")try{r=yt(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(gt(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}var ko=t=>typeof t=="bigint"&&Ro<=t;function pn(t,e,n){return ko(t)&&ko(e)&&ko(n)&&e<=t&&t<n}function ha(t,e,n,r){if(!pn(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function fr(t){let e;for(e=0;t>Ro;t>>=Ao,e+=1);return e}var Qe=t=>(Ao<<BigInt(t))-Ao;function ga(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=u=>new Uint8Array(u),o=u=>Uint8Array.of(u),i=r(t),s=r(t),a=0,c=()=>{i.fill(1),s.fill(0),a=0},l=(...u)=>n(s,i,...u),d=(u=r(0))=>{s=l(o(0),u),i=l(),u.length!==0&&(s=l(o(1),u),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,y=[];for(;u<e;){i=l();let m=i.slice();y.push(m),u+=i.length}return pe(...y)};return(u,y)=>{c(),d(u);let m;for(;!(m=y(h()));)d();return c(),m}}function yn(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,i,s){let a=t[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Lo(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var ge=BigInt(0),de=BigInt(1),mt=BigInt(2),ba=BigInt(3),ma=BigInt(4),wa=BigInt(5),Df=BigInt(7),xa=BigInt(8),$f=BigInt(9),Ea=BigInt(16);function be(t,e){let n=t%e;return n>=ge?n:e+n}function me(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function pa(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,o=ge,i=de,s=de,a=ge;for(;n!==ge;){let l=r/n,d=r%n,h=o-s*l,f=i-a*l;r=n,n=d,o=s,i=a,s=h,a=f}if(r!==de)throw new Error("invert: does not exist");return be(o,e)}function Io(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function va(t,e){let n=(t.ORDER+de)/ma,r=t.pow(e,n);return Io(t,r,e),r}function Vf(t,e){let n=(t.ORDER-wa)/xa,r=t.mul(e,mt),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,mt),o),a=t.mul(i,t.sub(s,t.ONE));return Io(t,a,e),a}function Kf(t){let e=et(t),n=Sa(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Df)/Ea;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),h=a.mul(l,o),f=a.mul(l,i),u=a.eql(a.sqr(d),c),y=a.eql(a.sqr(h),c);l=a.cmov(l,d,u),d=a.cmov(f,h,y);let m=a.eql(a.sqr(d),c),S=a.cmov(l,d,m);return Io(a,S,c),S}}function Sa(t){if(t<ba)throw new Error("sqrt is not defined for small field");let e=t-de,n=0;for(;e%mt===ge;)e/=mt,n++;let r=mt,o=et(t);for(;ya(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return va;let i=o.pow(r,e),s=(e+de)/mt;return function(c,l){if(c.is0(l))return l;if(ya(c,l)!==1)throw new Error("Cannot find square root");let d=n,h=c.mul(c.ONE,i),f=c.pow(l,e),u=c.pow(l,s);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let y=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let S=de<<BigInt(d-y-1),R=c.pow(h,S);d=y,h=c.sqr(R),f=c.mul(f,h),u=c.mul(u,R)}return u}}function zf(t){return t%ma===ba?va:t%xa===wa?Vf:t%Ea===$f?Kf(t):Sa(t)}var jf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function No(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=jf.reduce((r,o)=>(r[o]="function",r),e);return yn(t,n),t}function Zf(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===de)return e;let r=t.ONE,o=e;for(;n>ge;)n&de&&(r=t.mul(r,o)),o=t.sqr(o),n>>=de;return r}function ur(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function ya(t,e){let n=(t.ORDER-de)/mt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function dr(t,e){e!==void 0&&un(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function et(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,i,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(o=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(s=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(i=r.sqrt);let{nBitLength:c,nByteLength:l}=dr(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,h=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Qe(c),ZERO:ge,ONE:de,allowedLengths:a,create:f=>be(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ge<=f&&f<t},is0:f=>f===ge,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&de)===de,neg:f=>be(-f,t),eql:(f,u)=>f===u,sqr:f=>be(f*f,t),add:(f,u)=>be(f+u,t),sub:(f,u)=>be(f-u,t),mul:(f,u)=>be(f*u,t),pow:(f,u)=>Zf(h,f,u),div:(f,u)=>be(f*pa(u,t),t),sqrN:f=>f*f,addN:(f,u)=>f+u,subN:(f,u)=>f-u,mulN:(f,u)=>f*u,inv:f=>pa(f,t),sqrt:i||(f=>(d||(d=zf(t)),d(h,f))),toBytes:f=>n?To(f,l):Mt(f,l),fromBytes:(f,u=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let y=n?Co(f):qe(f);if(s&&(y=be(y,t)),!u&&!h.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:f=>ur(h,f),cmov:(f,u,y)=>y?u:f});return Object.freeze(h)}function Ba(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 _o(t){let e=Ba(t);return e+Math.ceil(e/2)}function hr(t,e,n=!1){let r=t.length,o=Ba(e),i=_o(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Co(t):qe(t),a=be(s,e-de)+de;return n?To(a,o):Mt(a,o)}var qt=BigInt(0),wt=BigInt(1);function bn(t,e){let n=e.negate();return t?n:e}function pr(t,e){let n=ur(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[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 Uo(t,e){Ca(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Qe(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function ka(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=wt);let l=e*r,d=l+Math.abs(a)-1,h=a===0,f=a<0,u=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:f,isNegF:u,offsetF:l}}function Gf(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Wf(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}var Oo=new WeakMap,Ta=new WeakMap;function Ho(t){return Ta.get(t)||1}function Aa(t){if(t!==qt)throw new Error("invalid wNAF")}var gr=class{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>qt;)n&wt&&(r=r.add(o)),o=o.double(),n>>=wt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Uo(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Uo(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}=ka(r,a,s);r=c,d?i=i.add(bn(f,n[u])):o=o.add(bn(h,n[l]))}return Aa(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=Uo(e,this.bits);for(let s=0;s<i.windows&&r!==qt;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=ka(r,s,i);if(r=a,!l){let h=n[c];o=o.add(d?h.negate():h)}}return Aa(r),o}getPrecomputes(e,n,r){let o=Oo.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Oo.set(n,o))),o}cached(e,n,r){let o=Ho(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ho(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Ca(n,this.bits),Ta.set(e,n),Oo.delete(e)}hasCache(e){return Ho(e)!==1}};function La(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>qt||r>qt;)n&wt&&(i=i.add(o)),r&wt&&(s=s.add(o)),o=o.double(),n>>=wt,r>>=wt;return{p1:i,p2:s}}function Ia(t,e,n,r){Gf(n,t),Wf(r,e);let o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,a=fr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Qe(c),d=new Array(Number(l)+1).fill(s),h=Math.floor((e.BITS-1)/c)*c,f=s;for(let u=h;u>=0;u-=c){d.fill(s);for(let m=0;m<i;m++){let S=r[m],R=Number(S>>BigInt(u)&l);d[R]=d[R].add(n[m])}let y=s;for(let m=d.length-1,S=s;m>0;m--)S=S.add(d[m]),y=y.add(S);if(f=f.add(y),u!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Ra(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return No(e),e}else return et(t,{isLE:n})}function Na(t,e,n={},r){if(r===void 0&&(r=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>qt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ra(e.p,n.Fp,r),i=Ra(e.n,n.Fn,r),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:i}}var _a=(t,e)=>(t+(t>=0?e:-e)/Ua)/e;function Yf(t,e,n){let[[r,o],[i,s]]=e,a=_a(s*t,n),c=_a(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,h=l<$e,f=d<$e;h&&(l=-l),f&&(d=-d);let u=Qe(Math.ceil(fr(n)/2))+Dt;if(l<$e||l>=u||d<$e||d>=u)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:d}}function Mo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Po(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return hn(n.lowS,"lowS"),hn(n.prehash,"prehash"),n.format!==void 0&&Mo(n.format),n}var qo=class extends Error{constructor(e=""){super(e)}},De={Err:qo,_tlv:{encode:(t,e)=>{let{Err:n}=De;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=gn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?gn(o.length/2|128):"";return gn(t)+i+o+e},decode(t,e){let{Err:n}=De,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=De;if(t<$e)throw new e("integer: negative integers are not allowed");let n=gn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=De;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 qe(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=De,o=re("signature",t),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=De,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},$e=BigInt(0),Dt=BigInt(1),Ua=BigInt(2),yr=BigInt(3),Jf=BigInt(4);function tt(t,e){let{BYTES:n}=t,r;if(typeof e=="bigint")r=e;else{let o=re("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Xf(t,e={}){let n=Na("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;yn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Ha(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(T,x,g){let{x:p,y:b}=x.toAffine(),E=r.toBytes(p);if(hn(g,"isCompressed"),g){d();let k=!r.isOdd(b);return pe(Oa(k),E)}else return pe(Uint8Array.of(4),E,r.toBytes(b))}function f(T){Fe(T,void 0,"Point");let{publicKey:x,publicKeyUncompressed:g}=l,p=T.length,b=T[0],E=T.subarray(1);if(p===x&&(b===2||b===3)){let k=r.fromBytes(E);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");let w=m(k),A;try{A=r.sqrt(w)}catch(O){let q=O instanceof Error?": "+O.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();let B=r.isOdd(A);return(b&1)===1!==B&&(A=r.neg(A)),{x:k,y:A}}else if(p===g&&b===4){let k=r.BYTES,w=r.fromBytes(E.subarray(0,k)),A=r.fromBytes(E.subarray(k,k*2));if(!S(w,A))throw new Error("bad point: is not on curve");return{x:w,y:A}}else throw new Error(`bad point: got length ${p}, expected compressed=${x} or uncompressed=${g}`)}let u=e.toBytes||h,y=e.fromBytes||f;function m(T){let x=r.sqr(T),g=r.mul(x,T);return r.add(r.add(g,r.mul(T,i.a)),i.b)}function S(T,x){let g=r.sqr(x),p=m(T);return r.eql(g,p)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,yr),Jf),N=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,N)))throw new Error("bad curve params: a or b");function _(T,x,g=!1){if(!r.isValid(x)||g&&r.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function M(T){if(!(T instanceof L))throw new Error("ProjectivePoint expected")}function U(T){if(!c||!c.basises)throw new Error("no endo");return Yf(T,c.basises,o.ORDER)}let D=Lo((T,x)=>{let{X:g,Y:p,Z:b}=T;if(r.eql(b,r.ONE))return{x:g,y:p};let E=T.is0();x==null&&(x=E?r.ONE:r.inv(b));let k=r.mul(g,x),w=r.mul(p,x),A=r.mul(b,x);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:k,y:w}}),j=Lo(T=>{if(T.is0()){if(e.allowInfinityPoint&&!r.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x,y:g}=T.toAffine();if(!r.isValid(x)||!r.isValid(g))throw new Error("bad point: x or y not field elements");if(!S(x,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(T,x,g,p,b){return g=new L(r.mul(g.X,T),g.Y,g.Z),x=bn(p,x),g=bn(b,g),x.add(g)}class L{constructor(x,g,p){this.X=_("x",x),this.Y=_("y",g,!0),this.Z=_("z",p),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:g,y:p}=x||{};if(!x||!r.isValid(g)||!r.isValid(p))throw new Error("invalid affine point");if(x instanceof L)throw new Error("projective point not allowed");return r.is0(g)&&r.is0(p)?L.ZERO:new L(g,p,r.ONE)}static fromBytes(x){let g=L.fromAffine(y(Fe(x,void 0,"point")));return g.assertValidity(),g}static fromHex(x){return L.fromBytes(re("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,g=!0){return $.createCache(this,x),g||this.multiply(yr),this}assertValidity(){j(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){M(x);let{X:g,Y:p,Z:b}=this,{X:E,Y:k,Z:w}=x,A=r.eql(r.mul(g,w),r.mul(E,b)),B=r.eql(r.mul(p,w),r.mul(k,b));return A&&B}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:g}=i,p=r.mul(g,yr),{X:b,Y:E,Z:k}=this,w=r.ZERO,A=r.ZERO,B=r.ZERO,C=r.mul(b,b),O=r.mul(E,E),q=r.mul(k,k),P=r.mul(b,E);return P=r.add(P,P),B=r.mul(b,k),B=r.add(B,B),w=r.mul(x,B),A=r.mul(p,q),A=r.add(w,A),w=r.sub(O,A),A=r.add(O,A),A=r.mul(w,A),w=r.mul(P,w),B=r.mul(p,B),q=r.mul(x,q),P=r.sub(C,q),P=r.mul(x,P),P=r.add(P,B),B=r.add(C,C),C=r.add(B,C),C=r.add(C,q),C=r.mul(C,P),A=r.add(A,C),q=r.mul(E,k),q=r.add(q,q),C=r.mul(q,P),w=r.sub(w,C),B=r.mul(q,O),B=r.add(B,B),B=r.add(B,B),new L(w,A,B)}add(x){M(x);let{X:g,Y:p,Z:b}=this,{X:E,Y:k,Z:w}=x,A=r.ZERO,B=r.ZERO,C=r.ZERO,O=i.a,q=r.mul(i.b,yr),P=r.mul(g,E),I=r.mul(p,k),V=r.mul(b,w),W=r.add(g,p),K=r.add(E,k);W=r.mul(W,K),K=r.add(P,I),W=r.sub(W,K),K=r.add(g,b);let G=r.add(E,w);return K=r.mul(K,G),G=r.add(P,V),K=r.sub(K,G),G=r.add(p,b),A=r.add(k,w),G=r.mul(G,A),A=r.add(I,V),G=r.sub(G,A),C=r.mul(O,K),A=r.mul(q,V),C=r.add(A,C),A=r.sub(I,C),C=r.add(I,C),B=r.mul(A,C),I=r.add(P,P),I=r.add(I,P),V=r.mul(O,V),K=r.mul(q,K),I=r.add(I,V),V=r.sub(P,V),V=r.mul(O,V),K=r.add(K,V),P=r.mul(I,K),B=r.add(B,P),P=r.mul(G,K),A=r.mul(W,A),A=r.sub(A,P),P=r.mul(W,I),C=r.mul(G,C),C=r.add(C,P),new L(A,B,C)}subtract(x){return this.add(x.negate())}is0(){return this.equals(L.ZERO)}multiply(x){let{endo:g}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let p,b,E=k=>$.cached(this,k,w=>pr(L,w));if(g){let{k1neg:k,k1:w,k2neg:A,k2:B}=U(x),{p:C,f:O}=E(w),{p:q,f:P}=E(B);b=O.add(P),p=Z(g.beta,C,q,k,A)}else{let{p:k,f:w}=E(x);p=k,b=w}return pr(L,[p,b])[0]}multiplyUnsafe(x){let{endo:g}=e,p=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===$e||p.is0())return L.ZERO;if(x===Dt)return p;if($.hasCache(this))return this.multiply(x);if(g){let{k1neg:b,k1:E,k2neg:k,k2:w}=U(x),{p1:A,p2:B}=La(L,p,E,w);return Z(g.beta,A,B,b,k)}else return $.unsafe(p,x)}multiplyAndAddUnsafe(x,g,p){let b=this.multiplyUnsafe(g).add(x.multiplyUnsafe(p));return b.is0()?void 0:b}toAffine(x){return D(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return s===Dt?!0:x?x(L,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===Dt?this:x?x(L,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return hn(x,"isCompressed"),this.assertValidity(),u(L,this,x)}toHex(x=!0){return le(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return pr(L,x)}static msm(x,g){return Ia(L,o,x,g)}static fromPrivateKey(x){return L.BASE.multiply(tt(o,x))}}L.BASE=new L(i.Gx,i.Gy,r.ONE),L.ZERO=new L(r.ZERO,r.ONE,r.ZERO),L.Fp=r,L.Fn=o;let z=o.BITS,$=new gr(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function Oa(t){return Uint8Array.of(t?2:3)}function Ha(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ff(t,e={}){let{Fn:n}=t,r=e.randomBytes||bt,o=Object.assign(Ha(t.Fp,n),{seed:_o(n.ORDER)});function i(u){try{return!!tt(n,u)}catch{return!1}}function s(u,y){let{publicKey:m,publicKeyUncompressed:S}=o;try{let R=u.length;return y===!0&&R!==m||y===!1&&R!==S?!1:!!t.fromBytes(u)}catch{return!1}}function a(u=r(o.seed)){return hr(Fe(u,o.seed,"seed"),n.ORDER)}function c(u,y=!0){return t.BASE.multiply(tt(n,u)).toBytes(y)}function l(u){let y=a(u);return{secretKey:y,publicKey:c(y)}}function d(u){if(typeof u=="bigint")return!1;if(u instanceof t)return!0;let{secretKey:y,publicKey:m,publicKeyUncompressed:S}=o;if(n.allowedLengths||y===m)return;let R=re("key",u).length;return R===m||R===S}function h(u,y,m=!0){if(d(u)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let S=tt(n,u);return t.fromHex(y).multiply(S).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:u=>tt(n,u),precompute(u=8,y=t.BASE){return y.precompute(u,!1)}},lengths:o})}function Qf(t,e,n={}){or(e),yn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||bt,o=n.hmac||((g,...p)=>Bo(e,g,pe(...p))),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u}=Ff(t,n),y={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function S(g){let p=a>>Dt;return g>p}function R(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function N(g,p){Mo(p);let b=u.signature,E=p==="compact"?b:p==="recovered"?b+1:void 0;return Fe(g,E,`${p} signature`)}class _{constructor(p,b,E){this.r=R("r",p),this.s=R("s",b),E!=null&&(this.recovery=E),Object.freeze(this)}static fromBytes(p,b=m){N(p,b);let E;if(b==="der"){let{r:B,s:C}=De.toSig(Fe(p));return new _(B,C)}b==="recovered"&&(E=p[0],b="compact",p=p.subarray(1));let k=s.BYTES,w=p.subarray(0,k),A=p.subarray(k,k*2);return new _(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(p,b){return this.fromBytes(yt(p),b)}addRecoveryBit(p){return new _(this.r,this.s,p)}recoverPublicKey(p){let b=i.ORDER,{r:E,s:k,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*Ua<b&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=w===2||w===3?E+a:E;if(!i.isValid(B))throw new Error("recovery id 2 or 3 invalid");let C=i.toBytes(B),O=t.fromBytes(pe(Oa((w&1)===0),C)),q=s.inv(B),P=U(re("msgHash",p)),I=s.create(-P*q),V=s.create(k*q),W=t.BASE.multiplyUnsafe(I).add(O.multiplyUnsafe(V));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return S(this.s)}toBytes(p=m){if(Mo(p),p==="der")return yt(De.hexFromSig(this));let b=s.toBytes(this.r),E=s.toBytes(this.s);if(p==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pe(Uint8Array.of(this.recovery),b,E)}return pe(b,E)}toHex(p){return le(this.toBytes(p))}assertValidity(){}static fromCompact(p){return _.fromBytes(re("sig",p),"compact")}static fromDER(p){return _.fromBytes(re("sig",p),"der")}normalizeS(){return this.hasHighS()?new _(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return le(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return le(this.toBytes("compact"))}}let M=n.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let b=qe(p),E=p.length*8-c;return E>0?b>>BigInt(E):b},U=n.bits2int_modN||function(p){return s.create(M(p))},D=Qe(c);function j(g){return ha("num < 2^"+c,g,$e,D),s.toBytes(g)}function Z(g,p){return Fe(g,void 0,"message"),p?Fe(e(g),void 0,"prehashed message"):g}function L(g,p,b){if(["recovered","canonical"].some(I=>I in b))throw new Error("sign() legacy options not supported");let{lowS:E,prehash:k,extraEntropy:w}=Po(b,y);g=Z(g,k);let A=U(g),B=tt(s,p),C=[j(B),j(A)];if(w!=null&&w!==!1){let I=w===!0?r(u.secretKey):w;C.push(re("extraEntropy",I))}let O=pe(...C),q=A;function P(I){let V=M(I);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===$e)return;let oe=s.create(W*s.create(q+G*B));if(oe===$e)return;let Wt=(K.x===G?0:2)|Number(K.y&Dt),Yt=oe;return E&&S(oe)&&(Yt=s.neg(oe),Wt^=1),new _(G,Yt,Wt)}return{seed:O,k2sig:P}}function z(g,p,b={}){g=re("message",g);let{seed:E,k2sig:k}=L(g,p,b);return ga(e.outputLen,s.BYTES,o)(E,k)}function $(g){let p,b=typeof g=="string"||gt(g),E=!b&&g!==null&&typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint";if(!b&&!E)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(E)p=new _(g.r,g.s);else if(b){try{p=_.fromBytes(re("sig",g),"der")}catch(k){if(!(k instanceof De.Err))throw k}if(!p)try{p=_.fromBytes(re("sig",g),"compact")}catch{return!1}}return p||!1}function T(g,p,b,E={}){let{lowS:k,prehash:w,format:A}=Po(E,y);if(b=re("publicKey",b),p=Z(re("message",p),w),"strict"in E)throw new Error("options.strict was renamed to lowS");let B=A===void 0?$(g):_.fromBytes(re("sig",g),A);if(B===!1)return!1;try{let C=t.fromBytes(b);if(k&&B.hasHighS())return!1;let{r:O,s:q}=B,P=U(p),I=s.inv(q),V=s.create(P*I),W=s.create(O*I),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===O}catch{return!1}}function x(g,p,b={}){let{prehash:E}=Po(b,y);return p=Z(p,E),_.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u,Point:t,sign:z,verify:T,recoverPublicKey:x,Signature:_,hash:e})}function eu(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=et(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function tu(t){let{CURVE:e,curveOpts:n}=eu(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function nu(t,e){let n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,dr(n.Fn.ORDER,n.Fn.BITS))})}function Pa(t){let{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=tu(t),i=Xf(e,n),s=Qf(i,r,o);return nu(t,s)}function Ma(t,e){let n=r=>Pa({...t,hash:r});return{...n(e),create:n}}var $t={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ru={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ou=BigInt(0),qa=BigInt(1),Do=BigInt(2);function iu(t){let e=$t.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,h=me(d,n,e)*d%e,f=me(h,n,e)*d%e,u=me(f,Do,e)*l%e,y=me(u,o,e)*u%e,m=me(y,i,e)*y%e,S=me(m,a,e)*m%e,R=me(S,c,e)*S%e,N=me(R,a,e)*m%e,_=me(N,n,e)*d%e,M=me(_,s,e)*y%e,U=me(M,r,e)*l%e,D=me(U,Do,e);if(!br.eql(br.sqr(D),t))throw new Error("Cannot find square root");return D}var br=et($t.p,{sqrt:iu}),Va=Ma({...$t,Fp:br,lowS:!0,endo:ru},Pt),Da={};function mr(t,...e){let n=Da[t];if(n===void 0){let r=Pt(sr(t));n=pe(r,r),Da[t]=n}return Pt(pe(n,...e))}var Vo=t=>t.toBytes(!0).slice(1),Vt=Va.Point,Ko=t=>t%Do===ou;function $o(t){let{Fn:e,BASE:n}=Vt,r=tt(e,t),o=n.multiply(r);return{scalar:Ko(o.y)?r:e.neg(r),bytes:Vo(o)}}function Ka(t){let e=br;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);Ko(o)||(o=e.neg(o));let i=Vt.fromAffine({x:t,y:o});return i.assertValidity(),i}var mn=qe;function za(...t){return Vt.Fn.create(mn(mr("BIP0340/challenge",...t)))}function $a(t){return $o(t).bytes}function su(t,e,n=bt(32)){let{Fn:r}=Vt,o=re("message",t),{bytes:i,scalar:s}=$o(e),a=re("auxRand",n,32),c=r.toBytes(s^mn(mr("BIP0340/aux",a))),l=mr("BIP0340/nonce",c,i,o),{bytes:d,scalar:h}=$o(l),f=za(d,i,o),u=new Uint8Array(64);if(u.set(d,0),u.set(r.toBytes(r.create(h+f*s)),32),!ja(u,o,i))throw new Error("sign: Invalid signature produced");return u}function ja(t,e,n){let{Fn:r,BASE:o}=Vt,i=re("signature",t,64),s=re("message",e),a=re("publicKey",n,32);try{let c=Ka(mn(a)),l=mn(i.subarray(0,32));if(!pn(l,qa,$t.p))return!1;let d=mn(i.subarray(32,64));if(!pn(d,qa,$t.n))return!1;let h=za(r.toBytes(l),Vo(c),s),f=o.multiplyUnsafe(d).add(c.multiplyUnsafe(r.neg(h))),{x:u,y}=f.toAffine();return!(f.is0()||!Ko(y)||u!==l)}catch{return!1}}var Ce=(()=>{let n=(o=bt(48))=>hr(o,$t.n);Va.utils.randomSecretKey;function r(o){let i=n(o);return{secretKey:i,publicKey:$a(i)}}return{keygen:r,getPublicKey:$a,sign:su,verify:ja,Point:Vt,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:mr,lift_x:Ka,pointToBytes:Vo,numberToBytesBE:Mt,bytesToNumberBE:qe,mod:be},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var zo=Pt;function au(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function cu(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function wr(t,e){let n=t.find(r=>r[0]===e);return n?n[1]:void 0}function Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}async function lu(t){if(!t.id||!t.pubkey||!t.sig||!t.tags||t.kind!==30470||!/^[0-9a-f]{128}$/i.test(t.sig)||!/^[0-9a-f]{64}$/i.test(t.pubkey)||!/^[0-9a-f]{64}$/i.test(t.id)||t.tags.length>100||t.content.length>65536||t.tags.some(s=>s.some(a=>a.length>1024)))return!1;let e=t.tags.map(s=>s[0]);if(!e.includes("tier")||!e.includes("age-range")||!e.includes("entity-type"))return!1;let n=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),r=new TextEncoder,o=zo(r.encode(n));if(le(o)!==t.id.toLowerCase())return!1;try{let s=Ve(t.sig),a=Ve(t.id),c=Ve(t.pubkey);return Ce.verify(s,a,c)}catch{return!1}}function fu(t,e){if(t===e||t==="18+"&&e==="18+")return!0;let n=["0-3","4-7","8-12","13-17","18+"],r=n.indexOf(t),o=n.indexOf(e);return r===-1||o===-1?!1:e==="18+"?t==="18+":t===e}async function uu(t,e){if(e==null||!/^https:\/\//i.test(e)||!/^[0-9a-f]{64}$/i.test(t))return null;try{let n=await fetch(`${e}/status/${t}`,{signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=await n.json();if(typeof r!="object"||r===null)return null;let o=r;return{confirmed:o.confirmed===!0,method:["A","B","C","D"].includes(o.method)?o.method:null,profession:typeof o.profession=="string"?o.profession:void 0,jurisdiction:typeof o.jurisdiction=="string"?o.jurisdiction:void 0}}catch{return null}}async function du(t,e){if(!["0-3","4-7","8-12","13-17","18+"].includes(t))return{verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"invalid-age-range"};let r={requiredAgeRange:t,relayUrl:e?.relayUrl||"wss://relay.damus.io",theme:e?.theme||"auto",timeout:e?.timeout||12e4,verifierCheckUrl:e?.verifierCheckUrl!==void 0?e.verifierCheckUrl:"https://verify.signet.forgesworn.dev",acceptUnconfirmed:e?.acceptUnconfirmed||!1,...e};r.timeout=Math.max(5e3,Math.min(r.timeout??12e4,6e5));let o=cu(),i={type:"signet-verify-request",requestId:o,requiredAgeRange:r.requiredAgeRange,relayUrl:r.relayUrl,timestamp:Math.floor(Date.now()/1e3)},s=JSON.stringify(i),a=btoa(s);return new Promise(c=>{let l=document.createElement("style");l.textContent="#signet-verify-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(l);let d=r.theme==="dark"||r.theme==="auto"&&window.matchMedia("(prefers-color-scheme: dark)").matches,h=d?"#1a1a2e":"#ffffff",f=d?"#e0e0e0":"#1a1a2e",u=d?"#888":"#666",y=document.createElement("dialog");y.id="signet-verify-dialog",y.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${h};color:${f};font-family:system-ui,-apple-system,sans-serif;`,y.innerHTML=`
7
+ `);let s=sd(e,n,o),a=Lr.getSymbolSize(e),c=new Yu(a);return td(c,e),nd(c),rd(c,e),pi(c,n,0),e>=7&&od(c,e),id(c,s),isNaN(r)&&(r=yi.getBestMask(c,pi.bind(null,c,n))),yi.applyMask(r,c),pi(c,n,r),{modules:c,version:e,errorCorrectionLevel:n,maskPattern:r,segments:o}}$c.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=hi.M,o,i;return typeof n<"u"&&(r=hi.from(n.errorCorrectionLevel,hi.M),o=Tr.from(n.version),i=yi.from(n.maskPattern),n.toSJISFunc&&Lr.setToSJISFunction(n.toSJISFunc)),cd(e,o,r,i)}});var mi=X(St=>{function Kc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}St.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,o=e.scale||4;return{width:r,scale:r?4:o,margin:n,color:{dark:Kc(e.color.dark||"#000000ff"),light:Kc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};St.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};St.getImageWidth=function(e,n){let r=St.getScale(e,n);return Math.floor((e+n.margin*2)*r)};St.qrToImageData=function(e,n,r){let o=n.modules.size,i=n.modules.data,s=St.getScale(o,r),a=Math.floor((o+r.margin*2)*s),c=r.margin*s,l=[r.color.light,r.color.dark];for(let d=0;d<a;d++)for(let h=0;h<a;h++){let f=(d*a+h)*4,u=r.color.light;if(d>=c&&h>=c&&d<a-c&&h<a-c){let y=Math.floor((d-c)/s),m=Math.floor((h-c)/s);u=l[i[y*o+m]?1:0]}e[f++]=u.r,e[f++]=u.g,e[f++]=u.b,e[f]=u.a}}});var zc=X(Ir=>{var wi=mi();function ld(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function fd(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ir.render=function(e,n,r){let o=r,i=n;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),n||(i=fd()),o=wi.getOptions(o);let s=wi.getImageWidth(e.modules.size,o),a=i.getContext("2d"),c=a.createImageData(s,s);return wi.qrToImageData(c.data,e,o),ld(a,i,s),a.putImageData(c,0,0),i};Ir.renderToDataURL=function(e,n,r){let o=r;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),o||(o={});let i=Ir.render(e,n,o),s=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(s,a.quality)}});var Gc=X(Zc=>{var ud=mi();function jc(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function xi(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function dd(t,e,n){let r="",o=0,i=!1,s=0;for(let a=0;a<t.length;a++){let c=Math.floor(a%e),l=Math.floor(a/e);!c&&!i&&(i=!0),t[a]?(s++,a>0&&c>0&&t[a-1]||(r+=i?xi("M",c+n,.5+l+n):xi("m",o,0),o=0,i=!1),c+1<e&&t[a+1]||(r+=xi("h",s),s=0)):o++}return r}Zc.render=function(e,n,r){let o=ud.getOptions(n),i=e.modules.size,s=e.modules.data,a=i+o.margin*2,c=o.color.light.a?"<path "+jc(o.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+jc(o.color.dark,"stroke")+' d="'+dd(s,i,o.margin)+'"/>',d='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+d+' shape-rendering="crispEdges">'+c+l+`</svg>
8
+ `;return typeof r=="function"&&r(null,f),f}});var Yc=X(An=>{var hd=Xa(),Ei=Vc(),Wc=zc(),gd=Gc();function vi(t,e,n,r,o){let i=[].slice.call(arguments,1),s=i.length,a=typeof i[s-1]=="function";if(!a&&!hd())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(o=n,n=e,e=r=void 0):s===3&&(e.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(n=e,e=r=void 0):s===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(c,l){try{let d=Ei.create(n,r);c(t(d,e,r))}catch(d){l(d)}})}try{let c=Ei.create(n,r);o(null,t(c,e,r))}catch(c){o(c)}}An.create=Ei.create;An.toCanvas=vi.bind(null,Wc.render);An.toDataURL=vi.bind(null,Wc.renderToDataURL);An.toString=vi.bind(null,function(t,e,n){return gd.render(t,n)})});var Ad={};ll(Ad,{handleCallback:()=>el,handleRedirectCallback:()=>tl,isAndroid:()=>rr,login:()=>Fc,logout:()=>nl,restoreSession:()=>Qc});var ze={relayUrl:"wss://relay.damus.io",signetAppOrigin:"https://mysignet.app",timeout:12e4,theme:"auto",persist:!0,mode:"relay"},Rn=300*1e3,Q={pubkey:"signet:login.pubkey",method:"signet:login.method",authEvent:"signet:login.authEvent",bunkerUri:"signet:login.bunkerUri",bunkerClientSk:"signet:login.bunkerClientSk",expiresAt:"signet:login.expiresAt",displayName:"signet:login.displayName",pendingRedirect:"signet:login.pendingRedirect"};function Xt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function we(t,e=""){if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function Y(t,e,n=""){let r=Xt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function st(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(t.outputLen),we(t.blockLen)}function kt(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 Ri(t,e){Y(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ie(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Cn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Se(t,e){return t<<32-e|t>>>e}var Ci=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dl=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ee(t){if(Y(t),Ci)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=dl[t[n]];return e}var Le={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ai(t){if(t>=Le._0&&t<=Le._9)return t-Le._0;if(t>=Le.A&&t<=Le.F)return t-(Le.A-10);if(t>=Le.a&&t<=Le.f)return t-(Le.a-10)}function ne(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ci)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Ai(t.charCodeAt(i)),a=Ai(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function te(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Y(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}function Ti(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function Be(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 Li=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ii(t,e,n){return t&e^~t&n}function Ni(t,e,n){return t&e^t&n^e&n}var Tn=class{constructor(e,n,r,o){v(this,"blockLen");v(this,"outputLen");v(this,"padOffset");v(this,"isLE");v(this,"buffer");v(this,"view");v(this,"finished",!1);v(this,"length",0);v(this,"pos",0);v(this,"destroyed",!1);this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Cn(this.buffer)}update(e){kt(this),Y(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Cn(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kt(this),Ri(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Ie(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let h=s;h<o;h++)n[h]=0;r.setBigUint64(o-8,BigInt(this.length*8),i),this.process(r,0);let a=Cn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hl=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]),je=new Uint32Array(64),_r=class extends Tn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)je[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){let f=je[h-15],u=je[h-2],y=Se(f,7)^Se(f,18)^f>>>3,m=Se(u,17)^Se(u,19)^u>>>10;je[h]=m+je[h-7]+y+je[h-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){let f=Se(a,6)^Se(a,11)^Se(a,25),u=d+f+Ii(a,c,l)+hl[h]+je[h]|0,m=(Se(r,2)^Se(r,13)^Se(r,22))+Ni(r,o,i)|0;d=l,l=c,c=a,a=s+u|0,s=i,i=o,o=r,r=u+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Ie(je)}destroy(){this.set(0,0,0,0,0,0,0,0),Ie(this.buffer)}},Ur=class extends _r{constructor(){super(32);v(this,"A",Ne[0]|0);v(this,"B",Ne[1]|0);v(this,"C",Ne[2]|0);v(this,"D",Ne[3]|0);v(this,"E",Ne[4]|0);v(this,"F",Ne[5]|0);v(this,"G",Ne[6]|0);v(this,"H",Ne[7]|0)}};var fe=Ti(()=>new Ur,Li(1));var Hr=BigInt(0),Or=BigInt(1);function Ft(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function _i(t){if(typeof t=="bigint"){if(!Ln(t))throw new Error("positive bigint expected, got "+t)}else we(t);return t}function Qt(t){let e=_i(t).toString(16);return e.length&1?"0"+e:e}function Ui(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Hr:BigInt("0x"+t)}function Ze(t){return Ui(ee(t))}function Pr(t){return Ui(ee(gl(Y(t)).reverse()))}function In(t,e){we(e),t=_i(t);let n=ne(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function Mr(t,e){return In(t,e).reverse()}function gl(t){return Uint8Array.from(t)}function Oi(t){return Uint8Array.from(t,(e,n)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}var Ln=t=>typeof t=="bigint"&&Hr<=t;function pl(t,e,n){return Ln(t)&&Ln(e)&&Ln(n)&&e<=t&&t<n}function Hi(t,e,n,r){if(!pl(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function qr(t){let e;for(e=0;t>Hr;t>>=Or,e+=1);return e}var en=t=>(Or<<BigInt(t))-Or;function Pi(t,e,n){if(we(t,"hashLen"),we(e,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");let r=S=>new Uint8Array(S),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(t),l=r(t),d=0,h=()=>{c.fill(1),l.fill(0),d=0},f=(...S)=>n(l,te(c,...S)),u=(S=o)=>{l=f(i,S),c=f(),S.length!==0&&(l=f(s,S),c=f())},y=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let S=0,R=[];for(;S<e;){c=f();let M=c.slice();R.push(M),S+=c.length}return te(...R)};return(S,R)=>{h(),u(S);let M;for(;!(M=R(y()));)u();return h(),M}}function tn(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,a){let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>r(a,c,s));o(e,!1),o(n,!0)}function Dr(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var he=BigInt(0),ue=BigInt(1),at=BigInt(2),Di=BigInt(3),$i=BigInt(4),Vi=BigInt(5),yl=BigInt(7),Ki=BigInt(8),bl=BigInt(9),zi=BigInt(16);function ke(t,e){let n=t%e;return n>=he?n:e+n}function ye(t,e,n){let r=t;for(;e-- >he;)r*=r,r%=n;return r}function Mi(t,e){if(t===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let n=ke(t,e),r=e,o=he,i=ue,s=ue,a=he;for(;n!==he;){let l=r/n,d=r%n,h=o-s*l,f=i-a*l;r=n,n=d,o=s,i=a,s=h,a=f}if(r!==ue)throw new Error("invert: does not exist");return ke(o,e)}function Vr(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function ji(t,e){let n=(t.ORDER+ue)/$i,r=t.pow(e,n);return Vr(t,r,e),r}function ml(t,e){let n=(t.ORDER-Vi)/Ki,r=t.mul(e,at),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,at),o),a=t.mul(i,t.sub(s,t.ONE));return Vr(t,a,e),a}function wl(t){let e=At(t),n=Zi(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+yl)/zi;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),h=a.mul(l,o),f=a.mul(l,i),u=a.eql(a.sqr(d),c),y=a.eql(a.sqr(h),c);l=a.cmov(l,d,u),d=a.cmov(f,h,y);let m=a.eql(a.sqr(d),c),S=a.cmov(l,d,m);return Vr(a,S,c),S}}function Zi(t){if(t<Di)throw new Error("sqrt is not defined for small field");let e=t-ue,n=0;for(;e%at===he;)e/=at,n++;let r=at,o=At(t);for(;qi(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ji;let i=o.pow(r,e),s=(e+ue)/at;return function(c,l){if(c.is0(l))return l;if(qi(c,l)!==1)throw new Error("Cannot find square root");let d=n,h=c.mul(c.ONE,i),f=c.pow(l,e),u=c.pow(l,s);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let y=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let S=ue<<BigInt(d-y-1),R=c.pow(h,S);d=y,h=c.sqr(R),f=c.mul(f,h),u=c.mul(u,R)}return u}}function xl(t){return t%$i===Di?ji:t%Ki===Vi?ml:t%zi===bl?wl(t):Zi(t)}var El=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=El.reduce((r,o)=>(r[o]="function",r),e);return tn(t,n),t}function vl(t,e,n){if(n<he)throw new Error("invalid exponent, negatives unsupported");if(n===he)return t.ONE;if(n===ue)return e;let r=t.ONE,o=e;for(;n>he;)n&ue&&(r=t.mul(r,o)),o=t.sqr(o),n>>=ue;return r}function Nn(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function qi(t,e){let n=(t.ORDER-ue)/at,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Sl(t,e){e!==void 0&&we(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var $r=class{constructor(e,n={}){v(this,"ORDER");v(this,"BITS");v(this,"BYTES");v(this,"isLE");v(this,"ZERO",he);v(this,"ONE",ue);v(this,"_lengths");v(this,"_sqrt");v(this,"_mod");if(e<=he)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=n.allowedLengths?.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=Sl(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ke(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ue)===ue}neg(e){return ke(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return ke(e*e,this.ORDER)}add(e,n){return ke(e+n,this.ORDER)}sub(e,n){return ke(e-n,this.ORDER)}mul(e,n){return ke(e*n,this.ORDER)}pow(e,n){return vl(this,e,n)}div(e,n){return ke(e*Mi(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Mi(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=xl(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Mr(e,this.BYTES):In(e,this.BYTES)}fromBytes(e,n=!1){Y(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Pr(e):Ze(e);if(a&&(c=ke(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nn(this,e)}cmov(e,n,r){return r?n:e}};function At(t,e={}){return new $r(t,e)}function Gi(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 zr(t){let e=Gi(t);return e+Math.ceil(e/2)}function _n(t,e,n=!1){Y(t);let r=t.length,o=Gi(e),i=zr(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Pr(t):Ze(t),a=ke(s,e-ue)+ue;return n?Mr(a,o):In(a,o)}var Rt=BigInt(0),ct=BigInt(1);function nn(t,e){let n=e.negate();return t?n:e}function Wr(t,e){let n=Nn(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Xi(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jr(t,e){Xi(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=en(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Wi(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=ct);let l=e*r,d=l+Math.abs(a)-1,h=a===0,f=a<0,u=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:f,isNegF:u,offsetF:l}}var Zr=new WeakMap,Fi=new WeakMap;function Gr(t){return Fi.get(t)||1}function Yi(t){if(t!==Rt)throw new Error("invalid wNAF")}var Un=class{constructor(e,n){v(this,"BASE");v(this,"ZERO");v(this,"Fn");v(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Rt;)n&ct&&(r=r.add(o)),o=o.double(),n>>=ct;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=jr(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=jr(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}=Wi(r,a,s);r=c,d?i=i.add(nn(f,n[u])):o=o.add(nn(h,n[l]))}return Yi(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=jr(e,this.bits);for(let s=0;s<i.windows&&r!==Rt;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Wi(r,s,i);if(r=a,!l){let h=n[c];o=o.add(d?h.negate():h)}}return Yi(r),o}getPrecomputes(e,n,r){let o=Zr.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Zr.set(n,o))),o}cached(e,n,r){let o=Gr(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Gr(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Xi(n,this.bits),Fi.set(e,n),Zr.delete(e)}hasCache(e){return Gr(e)!==1}};function Qi(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>Rt||r>Rt;)n&ct&&(i=i.add(o)),r&ct&&(s=s.add(o)),o=o.double(),n>>=ct,r>>=ct;return{p1:i,p2:s}}function Ji(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Kr(e),e}else return At(t,{isLE:n})}function es(t,e,n={},r){if(r===void 0&&(r=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>Rt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ji(e.p,n.Fp,r),i=Ji(e.n,n.Fn,r),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:i}}function On(t,e){return function(r){let o=t(r);return{secretKey:o,publicKey:e(o)}}}var Hn=class{constructor(e,n){v(this,"oHash");v(this,"iHash");v(this,"blockLen");v(this,"outputLen");v(this,"finished",!1);v(this,"destroyed",!1);if(st(e),Y(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ie(o)}update(e){return kt(this),this.iHash.update(e),this}digestInto(e){kt(this),Y(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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Te=(t,e,n)=>new Hn(t,e).update(n).digest();Te.create=(t,e)=>new Hn(t,e);var ts=(t,e)=>(t+(t>=0?e:-e)/ns)/e;function Bl(t,e,n){let[[r,o],[i,s]]=e,a=ts(s*t,n),c=ts(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,h=l<_e,f=d<_e;h&&(l=-l),f&&(d=-d);let u=en(Math.ceil(qr(n)/2))+Ct;if(l<_e||l>=u||d<_e||d>=u)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:d}}function Jr(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Yr(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Ft(n.lowS,"lowS"),Ft(n.prehash,"prehash"),n.format!==void 0&&Jr(n.format),n}var Xr=class extends Error{constructor(e=""){super(e)}},Ge={Err:Xr,_tlv:{encode:(t,e)=>{let{Err:n}=Ge;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=Qt(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?Qt(o.length/2|128):"";return Qt(t)+i+o+e},decode(t,e){let{Err:n}=Ge,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=Ge;if(t<_e)throw new e("integer: negative integers are not allowed");let n=Qt(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=Ge;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 Ze(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=Ge,o=Y(t,void 0,"signature"),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=Ge,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},_e=BigInt(0),Ct=BigInt(1),ns=BigInt(2),Pn=BigInt(3),kl=BigInt(4);function rs(t,e={}){let n=es("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;tn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=is(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(x,g,p){let{x:b,y:E}=g.toAffine(),k=r.toBytes(b);if(Ft(p,"isCompressed"),p){d();let w=!r.isOdd(E);return te(os(w),k)}else return te(Uint8Array.of(4),k,r.toBytes(E))}function f(x){Y(x,void 0,"Point");let{publicKey:g,publicKeyUncompressed:p}=l,b=x.length,E=x[0],k=x.subarray(1);if(b===g&&(E===2||E===3)){let w=r.fromBytes(k);if(!r.isValid(w))throw new Error("bad point: is not on curve, wrong x");let A=m(w),B;try{B=r.sqrt(A)}catch(D){let P=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+P)}d();let C=r.isOdd(B);return(E&1)===1!==C&&(B=r.neg(B)),{x:w,y:B}}else if(b===p&&E===4){let w=r.BYTES,A=r.fromBytes(k.subarray(0,w)),B=r.fromBytes(k.subarray(w,w*2));if(!S(A,B))throw new Error("bad point: is not on curve");return{x:A,y:B}}else throw new Error(`bad point: got length ${b}, expected compressed=${g} or uncompressed=${p}`)}let u=e.toBytes||h,y=e.fromBytes||f;function m(x){let g=r.sqr(x),p=r.mul(g,x);return r.add(r.add(p,r.mul(x,i.a)),i.b)}function S(x,g){let p=r.sqr(g),b=m(x);return r.eql(p,b)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,Pn),kl),M=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,M)))throw new Error("bad curve params: a or b");function I(x,g,p=!1){if(!r.isValid(g)||p&&r.is0(g))throw new Error(`bad point coordinate ${x}`);return g}function _(x){if(!(x instanceof L))throw new Error("Weierstrass Point expected")}function N(x){if(!c||!c.basises)throw new Error("no endo");return Bl(x,c.basises,o.ORDER)}let q=Dr((x,g)=>{let{X:p,Y:b,Z:E}=x;if(r.eql(E,r.ONE))return{x:p,y:b};let k=x.is0();g==null&&(g=k?r.ONE:r.inv(E));let w=r.mul(p,g),A=r.mul(b,g),B=r.mul(E,g);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:w,y:A}}),j=Dr(x=>{if(x.is0()){if(e.allowInfinityPoint&&!r.is0(x.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:p}=x.toAffine();if(!r.isValid(g)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!S(g,p))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(x,g,p,b,E){return p=new L(r.mul(p.X,x),p.Y,p.Z),g=nn(b,g),p=nn(E,p),g.add(p)}let T=class T{constructor(g,p,b){v(this,"X");v(this,"Y");v(this,"Z");this.X=I("x",g),this.Y=I("y",p,!0),this.Z=I("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){let{x:p,y:b}=g||{};if(!g||!r.isValid(p)||!r.isValid(b))throw new Error("invalid affine point");if(g instanceof T)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(b)?T.ZERO:new T(p,b,r.ONE)}static fromBytes(g){let p=T.fromAffine(y(Y(g,void 0,"point")));return p.assertValidity(),p}static fromHex(g){return T.fromBytes(ne(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,p=!0){return $.createCache(this,g),p||this.multiply(Pn),this}assertValidity(){j(this)}hasEvenY(){let{y:g}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(g)}equals(g){_(g);let{X:p,Y:b,Z:E}=this,{X:k,Y:w,Z:A}=g,B=r.eql(r.mul(p,A),r.mul(k,E)),C=r.eql(r.mul(b,A),r.mul(w,E));return B&&C}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:g,b:p}=i,b=r.mul(p,Pn),{X:E,Y:k,Z:w}=this,A=r.ZERO,B=r.ZERO,C=r.ZERO,O=r.mul(E,E),D=r.mul(k,k),P=r.mul(w,w),U=r.mul(E,k);return U=r.add(U,U),C=r.mul(E,w),C=r.add(C,C),A=r.mul(g,C),B=r.mul(b,P),B=r.add(A,B),A=r.sub(D,B),B=r.add(D,B),B=r.mul(A,B),A=r.mul(U,A),C=r.mul(b,C),P=r.mul(g,P),U=r.sub(O,P),U=r.mul(g,U),U=r.add(U,C),C=r.add(O,O),O=r.add(C,O),O=r.add(O,P),O=r.mul(O,U),B=r.add(B,O),P=r.mul(k,w),P=r.add(P,P),O=r.mul(P,U),A=r.sub(A,O),C=r.mul(P,D),C=r.add(C,C),C=r.add(C,C),new T(A,B,C)}add(g){_(g);let{X:p,Y:b,Z:E}=this,{X:k,Y:w,Z:A}=g,B=r.ZERO,C=r.ZERO,O=r.ZERO,D=i.a,P=r.mul(i.b,Pn),U=r.mul(p,k),V=r.mul(b,w),W=r.mul(E,A),K=r.add(p,b),G=r.add(k,w);K=r.mul(K,G),G=r.add(U,V),K=r.sub(K,G),G=r.add(p,E);let oe=r.add(k,A);return G=r.mul(G,oe),oe=r.add(U,W),G=r.sub(G,oe),oe=r.add(b,E),B=r.add(w,A),oe=r.mul(oe,B),B=r.add(V,W),oe=r.sub(oe,B),O=r.mul(D,G),B=r.mul(P,W),O=r.add(B,O),B=r.sub(V,O),O=r.add(V,O),C=r.mul(B,O),V=r.add(U,U),V=r.add(V,U),W=r.mul(D,W),G=r.mul(P,G),V=r.add(V,W),W=r.sub(U,W),W=r.mul(D,W),G=r.add(G,W),U=r.mul(V,G),C=r.add(C,U),U=r.mul(oe,G),B=r.mul(K,B),B=r.sub(B,U),U=r.mul(K,V),O=r.mul(oe,O),O=r.add(O,U),new T(B,C,O)}subtract(g){return this.add(g.negate())}is0(){return this.equals(T.ZERO)}multiply(g){let{endo:p}=e;if(!o.isValidNot0(g))throw new Error("invalid scalar: out of range");let b,E,k=w=>$.cached(this,w,A=>Wr(T,A));if(p){let{k1neg:w,k1:A,k2neg:B,k2:C}=N(g),{p:O,f:D}=k(A),{p:P,f:U}=k(C);E=D.add(U),b=Z(p.beta,O,P,w,B)}else{let{p:w,f:A}=k(g);b=w,E=A}return Wr(T,[b,E])[0]}multiplyUnsafe(g){let{endo:p}=e,b=this;if(!o.isValid(g))throw new Error("invalid scalar: out of range");if(g===_e||b.is0())return T.ZERO;if(g===Ct)return b;if($.hasCache(this))return this.multiply(g);if(p){let{k1neg:E,k1:k,k2neg:w,k2:A}=N(g),{p1:B,p2:C}=Qi(T,b,k,A);return Z(p.beta,B,C,E,w)}else return $.unsafe(b,g)}toAffine(g){return q(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return s===Ct?!0:g?g(T,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return s===Ct?this:g?g(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(g=!0){return Ft(g,"isCompressed"),this.assertValidity(),u(T,this,g)}toHex(g=!0){return ee(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};v(T,"BASE",new T(i.Gx,i.Gy,r.ONE)),v(T,"ZERO",new T(r.ZERO,r.ONE,r.ZERO)),v(T,"Fp",r),v(T,"Fn",o);let L=T,z=o.BITS,$=new Un(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function os(t){return Uint8Array.of(t?2:3)}function is(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Al(t,e={}){let{Fn:n}=t,r=e.randomBytes||Be,o=Object.assign(is(t.Fp,n),{seed:zr(n.ORDER)});function i(u){try{let y=n.fromBytes(u);return n.isValidNot0(y)}catch{return!1}}function s(u,y){let{publicKey:m,publicKeyUncompressed:S}=o;try{let R=u.length;return y===!0&&R!==m||y===!1&&R!==S?!1:!!t.fromBytes(u)}catch{return!1}}function a(u=r(o.seed)){return _n(Y(u,o.seed,"seed"),n.ORDER)}function c(u,y=!0){return t.BASE.multiply(n.fromBytes(u)).toBytes(y)}function l(u){let{secretKey:y,publicKey:m,publicKeyUncompressed:S}=o;if(!Xt(u)||"_lengths"in n&&n._lengths||y===m)return;let R=Y(u,void 0,"key").length;return R===m||R===S}function d(u,y,m=!0){if(l(u)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");let S=n.fromBytes(u);return t.fromBytes(y).multiply(S).toBytes(m)}let h={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=On(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:f,Point:t,utils:h,lengths:o})}function ss(t,e,n={}){st(e),tn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);let r=n.randomBytes||Be,o=n.hmac||((g,p)=>Te(e,g,p)),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u}=Al(t,n),y={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},m=a*ns<i.ORDER;function S(g){let p=a>>Ct;return g>p}function R(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function M(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function I(g,p){Jr(p);let b=u.signature,E=p==="compact"?b:p==="recovered"?b+1:void 0;return Y(g,E)}class _{constructor(p,b,E){v(this,"r");v(this,"s");v(this,"recovery");if(this.r=R("r",p),this.s=R("s",b),E!=null){if(M(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(p,b=y.format){I(p,b);let E;if(b==="der"){let{r:B,s:C}=Ge.toSig(Y(p));return new _(B,C)}b==="recovered"&&(E=p[0],b="compact",p=p.subarray(1));let k=u.signature/2,w=p.subarray(0,k),A=p.subarray(k,k*2);return new _(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(p,b){return this.fromBytes(ne(p),b)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new _(this.r,this.s,p)}recoverPublicKey(p){let{r:b,s:E}=this,k=this.assertRecovery(),w=k===2||k===3?b+a:b;if(!i.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let A=i.toBytes(w),B=t.fromBytes(te(os((k&1)===0),A)),C=s.inv(w),O=q(Y(p,void 0,"msgHash")),D=s.create(-O*C),P=s.create(E*C),U=t.BASE.multiplyUnsafe(D).add(B.multiplyUnsafe(P));if(U.is0())throw new Error("invalid recovery: point at infinify");return U.assertValidity(),U}hasHighS(){return S(this.s)}toBytes(p=y.format){if(Jr(p),p==="der")return ne(Ge.hexFromSig(this));let{r:b,s:E}=this,k=s.toBytes(b),w=s.toBytes(E);return p==="recovered"?(M(),te(Uint8Array.of(this.assertRecovery()),k,w)):te(k,w)}toHex(p){return ee(this.toBytes(p))}}let N=n.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let b=Ze(p),E=p.length*8-c;return E>0?b>>BigInt(E):b},q=n.bits2int_modN||function(p){return s.create(N(p))},j=en(c);function Z(g){return Hi("num < 2^"+c,g,_e,j),s.toBytes(g)}function L(g,p){return Y(g,void 0,"message"),p?Y(e(g),void 0,"prehashed message"):g}function z(g,p,b){let{lowS:E,prehash:k,extraEntropy:w}=Yr(b,y);g=L(g,k);let A=q(g),B=s.fromBytes(p);if(!s.isValidNot0(B))throw new Error("invalid private key");let C=[Z(B),Z(A)];if(w!=null&&w!==!1){let U=w===!0?r(u.secretKey):w;C.push(Y(U,void 0,"extraEntropy"))}let O=te(...C),D=A;function P(U){let V=N(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===_e)return;let oe=s.create(W*s.create(D+G*B));if(oe===_e)return;let Wt=(K.x===G?0:2)|Number(K.y&Ct),Yt=oe;return E&&S(oe)&&(Yt=s.neg(oe),Wt^=1),new _(G,Yt,m?void 0:Wt)}return{seed:O,k2sig:P}}function $(g,p,b={}){let{seed:E,k2sig:k}=z(g,p,b);return Pi(e.outputLen,s.BYTES,o)(E,k).toBytes(b.format)}function T(g,p,b,E={}){let{lowS:k,prehash:w,format:A}=Yr(E,y);if(b=Y(b,void 0,"publicKey"),p=L(p,w),!Xt(g)){let B=g instanceof _?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+B)}I(g,A);try{let B=_.fromBytes(g,A),C=t.fromBytes(b);if(k&&B.hasHighS())return!1;let{r:O,s:D}=B,P=q(p),U=s.inv(D),V=s.create(P*U),W=s.create(O*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===O}catch{return!1}}function x(g,p,b={}){let{prehash:E}=Yr(b,y);return p=L(p,E),_.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u,Point:t,sign:$,verify:T,recoverPublicKey:x,Signature:_,hash:e})}var Dn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Rl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Cl=BigInt(0),Fr=BigInt(2);function Tl(t){let e=Dn.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,h=ye(d,n,e)*d%e,f=ye(h,n,e)*d%e,u=ye(f,Fr,e)*l%e,y=ye(u,o,e)*u%e,m=ye(y,i,e)*y%e,S=ye(m,a,e)*m%e,R=ye(S,c,e)*S%e,M=ye(R,a,e)*m%e,I=ye(M,n,e)*d%e,_=ye(I,s,e)*y%e,N=ye(_,r,e)*l%e,q=ye(N,Fr,e);if(!Mn.eql(Mn.sqr(q),t))throw new Error("Cannot find square root");return q}var Mn=At(Dn.p,{sqrt:Tl}),lt=rs(Dn,{Fp:Mn,endo:Rl}),$n=ss(lt,fe),as={};function qn(t,...e){let n=as[t];if(n===void 0){let r=fe(Oi(t));n=te(r,r),as[t]=n}return fe(te(n,...e))}var eo=t=>t.toBytes(!0).slice(1),to=t=>t%Fr===Cl;function Qr(t){let{Fn:e,BASE:n}=lt,r=e.fromBytes(t),o=n.multiply(r);return{scalar:to(o.y)?r:e.neg(r),bytes:eo(o)}}function ls(t){let e=Mn;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);to(o)||(o=e.neg(o));let i=lt.fromAffine({x:t,y:o});return i.assertValidity(),i}var rn=Ze;function fs(...t){return lt.Fn.create(rn(qn("BIP0340/challenge",...t)))}function cs(t){return Qr(t).bytes}function Ll(t,e,n=Be(32)){let{Fn:r}=lt,o=Y(t,void 0,"message"),{bytes:i,scalar:s}=Qr(e),a=Y(n,32,"auxRand"),c=r.toBytes(s^rn(qn("BIP0340/aux",a))),l=qn("BIP0340/nonce",c,i,o),{bytes:d,scalar:h}=Qr(l),f=fs(d,i,o),u=new Uint8Array(64);if(u.set(d,0),u.set(r.toBytes(r.create(h+f*s)),32),!us(u,o,i))throw new Error("sign: Invalid signature produced");return u}function us(t,e,n){let{Fp:r,Fn:o,BASE:i}=lt,s=Y(t,64,"signature"),a=Y(e,void 0,"message"),c=Y(n,32,"publicKey");try{let l=ls(rn(c)),d=rn(s.subarray(0,32));if(!r.isValidNot0(d))return!1;let h=rn(s.subarray(32,64));if(!o.isValidNot0(h))return!1;let f=fs(o.toBytes(d),eo(l),a),u=i.multiplyUnsafe(h).add(l.multiplyUnsafe(o.neg(f))),{x:y,y:m}=u.toAffine();return!(u.is0()||!to(m)||y!==d)}catch{return!1}}var xe=(()=>{let n=(r=Be(48))=>_n(r,Dn.n);return{keygen:On(n,cs),getPublicKey:cs,sign:Ll,verify:us,Point:lt,utils:{randomSecretKey:n,taggedHash:qn,lift_x:ls,pointToBytes:eo},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Il(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Vn(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Kn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function se(t,e,n=""){let r=Il(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function no(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 ds(t,e){se(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Ue(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 Nl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var _l=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hs(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Tt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}var ro=(t,e)=>{function n(r,...o){if(se(r,void 0,"key"),!_l)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let d=o[0];se(d,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let i=t.tagLength;i&&o[1]!==void 0&&se(o[1],void 0,"AAD");let s=e(r,...o),a=(d,h)=>{if(h!==void 0){if(d!==2)throw new Error("cipher output not supported");se(h,void 0,"output")}},c=!1;return{encrypt(d,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,se(d),a(s.encrypt.length,h),s.encrypt(d,h)},decrypt(d,h){if(se(d),i&&d.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,h),s.decrypt(d,h)}}}return Object.assign(n,t),n};function oo(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(n&&!Ul(e))throw new Error("invalid output, must be aligned");return e}function gs(t,e,n){Vn(n);let r=new Uint8Array(16),o=Nl(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Ul(t){return t.byteOffset%4===0}function Lt(t){return Uint8Array.from(t)}var ys=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Ol=ys("expand 16-byte k"),Hl=ys("expand 32-byte k"),Pl=Ue(Ol),Ml=Ue(Hl);function H(t,e){return t<<e|t>>>32-e}function io(t){return t.byteOffset%4===0}var zn=64,ql=16,bs=2**32-1,ps=Uint32Array.of();function Dl(t,e,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(zn),d=Ue(l),h=io(o)&&io(i),f=h?Ue(o):ps,u=h?Ue(i):ps;for(let y=0;y<c;s++){if(t(e,n,r,d,s,a),s>=bs)throw new Error("arx: counter overflow");let m=Math.min(zn,c-y);if(h&&m===zn){let S=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let R=0,M;R<ql;R++)M=S+R,u[M]=f[M]^d[R];y+=zn;continue}for(let S=0,R;S<m;S++)R=y+S,i[R]=o[R]^l[S];y+=m}}function so(t,e){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=hs({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Kn(o),Kn(s),Vn(i),Vn(n),(a,c,l,d,h=0)=>{se(a,void 0,"key"),se(c,void 0,"nonce"),se(l,void 0,"data");let f=l.length;if(d===void 0&&(d=new Uint8Array(f)),se(d,void 0,"output"),Kn(h),h<0||h>=bs)throw new Error("arx: counter overflow");if(d.length<f)throw new Error(`arx: output (${d.length}) is shorter than data (${f})`);let u=[],y=a.length,m,S;if(y===32)u.push(m=Lt(a)),S=Ml;else if(y===16&&n)m=new Uint8Array(32),m.set(a),m.set(a,16),S=Pl,u.push(m);else throw se(a,32,"arx key"),new Error("invalid key size");io(c)||u.push(c=Lt(c));let R=Ue(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(S,R,Ue(c.subarray(0,16)),R),c=c.subarray(16)}let M=16-o;if(M!==c.length)throw new Error(`arx: nonce must be ${M} or 16 bytes`);if(M!==12){let _=new Uint8Array(12);_.set(c,i?0:12-c.length),c=_,u.push(c)}let I=Ue(c);return Dl(t,S,R,I,l,d,h,s),Oe(...u),d}}function ce(t,e){return t[e++]&255|(t[e++]&255)<<8}var ao=class{constructor(e){v(this,"blockLen",16);v(this,"outputLen",16);v(this,"buffer",new Uint8Array(16));v(this,"r",new Uint16Array(10));v(this,"h",new Uint16Array(10));v(this,"pad",new Uint16Array(8));v(this,"pos",0);v(this,"finished",!1);e=Lt(se(e,32,"key"));let n=ce(e,0),r=ce(e,2),o=ce(e,4),i=ce(e,6),s=ce(e,8),a=ce(e,10),c=ce(e,12),l=ce(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>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 d=0;d<8;d++)this.pad[d]=ce(e,16+2*d)}process(e,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],h=s[4],f=s[5],u=s[6],y=s[7],m=s[8],S=s[9],R=ce(e,n+0),M=ce(e,n+2),I=ce(e,n+4),_=ce(e,n+6),N=ce(e,n+8),q=ce(e,n+10),j=ce(e,n+12),Z=ce(e,n+14),L=i[0]+(R&8191),z=i[1]+((R>>>13|M<<3)&8191),$=i[2]+((M>>>10|I<<6)&8191),T=i[3]+((I>>>7|_<<9)&8191),x=i[4]+((_>>>4|N<<12)&8191),g=i[5]+(N>>>1&8191),p=i[6]+((N>>>14|q<<2)&8191),b=i[7]+((q>>>11|j<<5)&8191),E=i[8]+((j>>>8|Z<<8)&8191),k=i[9]+(Z>>>5|o),w=0,A=w+L*a+z*(5*S)+$*(5*m)+T*(5*y)+x*(5*u);w=A>>>13,A&=8191,A+=g*(5*f)+p*(5*h)+b*(5*d)+E*(5*l)+k*(5*c),w+=A>>>13,A&=8191;let B=w+L*c+z*a+$*(5*S)+T*(5*m)+x*(5*y);w=B>>>13,B&=8191,B+=g*(5*u)+p*(5*f)+b*(5*h)+E*(5*d)+k*(5*l),w+=B>>>13,B&=8191;let C=w+L*l+z*c+$*a+T*(5*S)+x*(5*m);w=C>>>13,C&=8191,C+=g*(5*y)+p*(5*u)+b*(5*f)+E*(5*h)+k*(5*d),w+=C>>>13,C&=8191;let O=w+L*d+z*l+$*c+T*a+x*(5*S);w=O>>>13,O&=8191,O+=g*(5*m)+p*(5*y)+b*(5*u)+E*(5*f)+k*(5*h),w+=O>>>13,O&=8191;let D=w+L*h+z*d+$*l+T*c+x*a;w=D>>>13,D&=8191,D+=g*(5*S)+p*(5*m)+b*(5*y)+E*(5*u)+k*(5*f),w+=D>>>13,D&=8191;let P=w+L*f+z*h+$*d+T*l+x*c;w=P>>>13,P&=8191,P+=g*a+p*(5*S)+b*(5*m)+E*(5*y)+k*(5*u),w+=P>>>13,P&=8191;let U=w+L*u+z*f+$*h+T*d+x*l;w=U>>>13,U&=8191,U+=g*c+p*a+b*(5*S)+E*(5*m)+k*(5*y),w+=U>>>13,U&=8191;let V=w+L*y+z*u+$*f+T*h+x*d;w=V>>>13,V&=8191,V+=g*l+p*c+b*a+E*(5*S)+k*(5*m),w+=V>>>13,V&=8191;let W=w+L*m+z*y+$*u+T*f+x*h;w=W>>>13,W&=8191,W+=g*d+p*l+b*c+E*a+k*(5*S),w+=W>>>13,W&=8191;let K=w+L*S+z*m+$*y+T*u+x*f;w=K>>>13,K&=8191,K+=g*h+p*d+b*l+E*c+k*a,w+=K>>>13,K&=8191,w=(w<<2)+w|0,w=w+A|0,A=w&8191,w=w>>>13,B+=w,i[0]=A,i[1]=B,i[2]=C,i[3]=O,i[4]=D,i[5]=P,i[6]=U,i[7]=V,i[8]=W,i[9]=K}finalize(){let{h:e,pad:n}=this,r=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,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[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 s=e[0]+n[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+n[a]|0)+(s>>>16)|0,e[a]=s&65535;Oe(r)}update(e){no(this),se(e),e=Lt(e);let{buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){no(this),ds(e,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=r[s]>>>0,e[i++]=r[s]>>>8;return e}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}};function $l(t){let e=(r,o)=>t(o).update(r).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}var ms=$l(t=>new ao(t));function Es(t,e,n,r,o,i=20){let s=t[0],a=t[1],c=t[2],l=t[3],d=e[0],h=e[1],f=e[2],u=e[3],y=e[4],m=e[5],S=e[6],R=e[7],M=o,I=n[0],_=n[1],N=n[2],q=s,j=a,Z=c,L=l,z=d,$=h,T=f,x=u,g=y,p=m,b=S,E=R,k=M,w=I,A=_,B=N;for(let O=0;O<i;O+=2)q=q+z|0,k=H(k^q,16),g=g+k|0,z=H(z^g,12),q=q+z|0,k=H(k^q,8),g=g+k|0,z=H(z^g,7),j=j+$|0,w=H(w^j,16),p=p+w|0,$=H($^p,12),j=j+$|0,w=H(w^j,8),p=p+w|0,$=H($^p,7),Z=Z+T|0,A=H(A^Z,16),b=b+A|0,T=H(T^b,12),Z=Z+T|0,A=H(A^Z,8),b=b+A|0,T=H(T^b,7),L=L+x|0,B=H(B^L,16),E=E+B|0,x=H(x^E,12),L=L+x|0,B=H(B^L,8),E=E+B|0,x=H(x^E,7),q=q+$|0,B=H(B^q,16),b=b+B|0,$=H($^b,12),q=q+$|0,B=H(B^q,8),b=b+B|0,$=H($^b,7),j=j+T|0,k=H(k^j,16),E=E+k|0,T=H(T^E,12),j=j+T|0,k=H(k^j,8),E=E+k|0,T=H(T^E,7),Z=Z+x|0,w=H(w^Z,16),g=g+w|0,x=H(x^g,12),Z=Z+x|0,w=H(w^Z,8),g=g+w|0,x=H(x^g,7),L=L+z|0,A=H(A^L,16),p=p+A|0,z=H(z^p,12),L=L+z|0,A=H(A^L,8),p=p+A|0,z=H(z^p,7);let C=0;r[C++]=s+q|0,r[C++]=a+j|0,r[C++]=c+Z|0,r[C++]=l+L|0,r[C++]=d+z|0,r[C++]=h+$|0,r[C++]=f+T|0,r[C++]=u+x|0,r[C++]=y+g|0,r[C++]=m+p|0,r[C++]=S+b|0,r[C++]=R+E|0,r[C++]=M+k|0,r[C++]=I+w|0,r[C++]=_+A|0,r[C++]=N+B|0}function Vl(t,e,n,r){let o=t[0],i=t[1],s=t[2],a=t[3],c=e[0],l=e[1],d=e[2],h=e[3],f=e[4],u=e[5],y=e[6],m=e[7],S=n[0],R=n[1],M=n[2],I=n[3];for(let N=0;N<20;N+=2)o=o+c|0,S=H(S^o,16),f=f+S|0,c=H(c^f,12),o=o+c|0,S=H(S^o,8),f=f+S|0,c=H(c^f,7),i=i+l|0,R=H(R^i,16),u=u+R|0,l=H(l^u,12),i=i+l|0,R=H(R^i,8),u=u+R|0,l=H(l^u,7),s=s+d|0,M=H(M^s,16),y=y+M|0,d=H(d^y,12),s=s+d|0,M=H(M^s,8),y=y+M|0,d=H(d^y,7),a=a+h|0,I=H(I^a,16),m=m+I|0,h=H(h^m,12),a=a+h|0,I=H(I^a,8),m=m+I|0,h=H(h^m,7),o=o+l|0,I=H(I^o,16),y=y+I|0,l=H(l^y,12),o=o+l|0,I=H(I^o,8),y=y+I|0,l=H(l^y,7),i=i+d|0,S=H(S^i,16),m=m+S|0,d=H(d^m,12),i=i+d|0,S=H(S^i,8),m=m+S|0,d=H(d^m,7),s=s+h|0,R=H(R^s,16),f=f+R|0,h=H(h^f,12),s=s+h|0,R=H(R^s,8),f=f+R|0,h=H(h^f,7),a=a+c|0,M=H(M^a,16),u=u+M|0,c=H(c^u,12),a=a+c|0,M=H(M^a,8),u=u+M|0,c=H(c^u,7);let _=0;r[_++]=o,r[_++]=i,r[_++]=s,r[_++]=a,r[_++]=S,r[_++]=R,r[_++]=M,r[_++]=I}var ft=so(Es,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Kl=so(Es,{counterRight:!1,counterLength:8,extendNonceFn:Vl,allowShortKeys:!1});var zl=new Uint8Array(16),ws=(t,e)=>{t.update(e);let n=e.length%16;n&&t.update(zl.subarray(n))},jl=new Uint8Array(32);function xs(t,e,n,r,o){o!==void 0&&se(o,void 0,"AAD");let i=t(e,n,jl),s=gs(r.length,o?o.length:0,!0),a=ms.create(i);o&&ws(a,o),ws(a,r),a.update(s);let c=a.digest();return Oe(i,s),c}var vs=t=>(e,n,r)=>({encrypt(i,s){let a=i.length;s=oo(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);t(e,n,c,c,1);let l=xs(t,e,n,c,r);return s.set(l,a),Oe(l),s},decrypt(i,s){s=oo(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=xs(t,e,n,a,r);if(!Tt(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Oe(l),s}}),Lh=ro({blockSize:64,nonceLength:12,tagLength:16},vs(ft)),Ih=ro({blockSize:64,nonceLength:24,tagLength:16},vs(Kl));function jn(t,e,n){return st(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Te(t,n,e)}var co=Uint8Array.of(0),Ss=Uint8Array.of();function Zn(t,e,n,r=32){st(t),we(r,"length");let o=t.outputLen;if(r>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/o);n===void 0?n=Ss:Y(n,void 0,"info");let s=new Uint8Array(i*o),a=Te.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)co[0]=d+1,c.update(d===0?Ss:l).update(n).update(co).digestInto(l),s.set(l,o*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ie(l,co),s.slice(0,r)}function ho(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Zl(t){if(!ho(t))throw new Error("Uint8Array expected")}function Rs(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Gl(t){if(typeof t!="function")throw new Error("function expected");return!0}function ut(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function go(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function lo(t){if(!Array.isArray(t))throw new Error("array expected")}function Wn(t,e){if(!Rs(!0,e))throw new Error(`${t}: array of strings expected`)}function Cs(t,e){if(!Rs(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ts(...t){let e=i=>i,n=(i,s)=>a=>i(s(a)),r=t.map(i=>i.encode).reduceRight(n,e),o=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:o}}function Ls(t){let e=typeof t=="string"?t.split(""):t,n=e.length;Wn("alphabet",e);let r=new Map(e.map((o,i)=>[o,i]));return{encode:o=>(lo(o),o.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:o=>(lo(o),o.map(i=>{ut("alphabet.decode",i);let s=r.get(i);if(s===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return s}))}}function Is(t=""){return ut("join",t),{encode:e=>(Wn("join.decode",e),e.join(t)),decode:e=>(ut("join.decode",e),e.split(t))}}function Wl(t,e="="){return go(t),ut("padding",e),{encode(n){for(Wn("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Wn("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}var Ns=(t,e)=>e===0?t:Ns(e,t%e),Yn=(t,e)=>t+(e-Ns(t,e)),Gn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function fo(t,e,n,r){if(lo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Yn(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Yn(e,n)}`);let o=0,i=0,s=Gn[e],a=Gn[n]-1,c=[];for(let l of t){if(go(l),l>=s)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((o>>i-n&a)>>>0);let d=Gn[i];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function _s(t,e=!1){if(go(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Yn(8,t)>32||Yn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!ho(n))throw new Error("radix2.encode input should be Uint8Array");return fo(Array.from(n),8,t,!e)},decode:n=>(Cs("radix2.decode",n),Uint8Array.from(fo(n,t,8,e)))}}function Bs(t){return Gl(t),function(...e){try{return t.apply(null,e)}catch{}}}var Yl=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Jl=(t,e)=>{ut("base64",t);let n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},It=Yl?{encode(t){return Zl(t),t.toBase64()},decode(t){return Jl(t,!1)}}:Ts(_s(6),Ls("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Wl(6),Is(""));var uo=Ts(Ls("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Is("")),ks=[996825010,642813549,513874426,1027748829,705979059];function on(t){let e=t>>25,n=(t&33554431)<<5;for(let r=0;r<ks.length;r++)(e>>r&1)===1&&(n^=ks[r]);return n}function As(t,e,n=1){let r=t.length,o=1;for(let i=0;i<r;i++){let s=t.charCodeAt(i);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);o=on(o)^s>>5}o=on(o);for(let i=0;i<r;i++)o=on(o)^t.charCodeAt(i)&31;for(let i of e)o=on(o)^i;for(let i=0;i<6;i++)o=on(o);return o^=n,uo.encode(fo([o%Gn[30]],30,5,!1))}function Xl(t){let e=t==="bech32"?1:734539939,n=_s(5),r=n.decode,o=n.encode,i=Bs(r);function s(h,f,u=90){ut("bech32.encode prefix",h),ho(f)&&(f=Array.from(f)),Cs("bech32.encode",f);let y=h.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);let m=y+7+f.length;if(u!==!1&&m>u)throw new TypeError(`Length ${m} exceeds limit ${u}`);let S=h.toLowerCase(),R=As(S,f,e);return`${S}1${uo.encode(f)}${R}`}function a(h,f=90){ut("bech32.decode input",h);let u=h.length;if(u<8||f!==!1&&u>f)throw new TypeError(`invalid string length: ${u} (${h}). Expected (8..${f})`);let y=h.toLowerCase();if(h!==y&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");let m=y.lastIndexOf("1");if(m===0||m===-1)throw new Error('Letter "1" must be present between prefix and data only');let S=y.slice(0,m),R=y.slice(m+1);if(R.length<6)throw new Error("Data must be at least 6 characters long");let M=uo.decode(R).slice(0,-6),I=As(S,M,e);if(!R.endsWith(I))throw new Error(`Invalid checksum in ${h}: expected "${I}"`);return{prefix:S,words:M}}let c=Bs(a);function l(h){let{prefix:f,words:u}=a(h,!1);return{prefix:f,words:u,bytes:r(u)}}function d(h,f){return s(h,o(f))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:i,toWords:o}}var po=Xl("bech32");var dt=Symbol("verified"),Fl=t=>t instanceof Object;function Ql(t){if(!Fl(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var ef=new TextDecoder("utf-8"),xo=new TextEncoder;function sn(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}var tf=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=yo(n),n.sig=ee(xe.sign(ne(yo(n)),e)),n[dt]=!0,n}verifyEvent(t){if(typeof t[dt]=="boolean")return t[dt];try{let e=yo(t);if(e!==t.id)return t[dt]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[dt]=n,n}catch{return t[dt]=!1,!1}}};function nf(t){if(!Ql(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 yo(t){let e=fe(xo.encode(nf(t)));return ee(e)}var Jn=new tf,Dh=Jn.generateSecretKey,Us=Jn.getPublicKey,rf=Jn.finalizeEvent,Hs=Jn.verifyEvent,Eo=1,vo=4294967295,So=65536;function bo(t,e){let n=$n.getSharedSecret(t,ne("02"+e)).subarray(1,33);return jn(fe,n,xo.encode("nip44-v2"))}function Ps(t,e){let n=Zn(fe,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Ms(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),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function of(t){if(!Number.isSafeInteger(t)||t<Eo||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 sf(t){if(!Number.isSafeInteger(t)||t<So||t>vo)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 af(t){let e=xo.encode(t),n=e.length;if(n<Eo||n>vo)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=So?te(new Uint8Array([0,0]),sf(n)):of(n),o=new Uint8Array(Ms(n)-n);return te(r,e,o)}function cf(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<So)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<Eo||r>vo||i.length!==r||t.length!==o+Ms(r))throw new Error("invalid padding");return ef.decode(i)}function qs(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Te(fe,t,r)}function lf(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 n;try{n=It.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function ff(t,e,n=Be(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ps(e,n),s=af(t),a=ft(r,o,s),c=qs(i,a,n);return It.encode(te(new Uint8Array([2]),n,a,c))}function Os(t,e){let{nonce:n,ciphertext:r,mac:o}=lf(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ps(e,n),c=qs(a,r,n);if(!Tt(c,o))throw new Error("invalid MAC");let l=ft(i,s,r);return cf(l)}var uf=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,df;try{df=fetch}catch{}var hf=22242,mo=24133;function gf(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),o=t[`#${r}`];if(o&&!e.tags.find(([i,s])=>i===n.slice(1)&&o.indexOf(s)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function pf(t,e){for(let n=0;n<t.length;n++)if(gf(t[n],e))return!0;return!1}function yf(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,o=t.slice(r).indexOf('"')+r+1;return t.slice(o,o+64)}function bf(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,o=t.slice(r+1,80).indexOf('"');if(o===-1)return null;let i=r+1+o;return t.slice(r+1,i)}function mf(t,e){return{kind:hf,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var wo=class extends Error{constructor(t,e){super(`Tried to send message '${t} on a closed connection to ${e}.`),this.name="SendingOnClosedConnection"}},Ds=class{constructor(t,e){v(this,"url");v(this,"_connected",!1);v(this,"onclose",null);v(this,"onnotice",t=>console.debug(`NOTICE from ${this.url}: ${t}`));v(this,"onauth");v(this,"baseEoseTimeout",4400);v(this,"publishTimeout",4400);v(this,"pingFrequency",29e3);v(this,"pingTimeout",2e4);v(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);v(this,"openSubs",new Map);v(this,"enablePing");v(this,"enableReconnect");v(this,"idleSince",Date.now());v(this,"ongoingOperations",0);v(this,"reconnectTimeoutHandle");v(this,"pingIntervalHandle");v(this,"reconnectAttempts",0);v(this,"skipReconnection",!1);v(this,"connectionPromise");v(this,"openCountRequests",new Map);v(this,"openEventPublishes",new Map);v(this,"ws");v(this,"challenge");v(this,"authPromise");v(this,"serial",0);v(this,"verifyEvent");v(this,"_WebSocket");this.url=sn(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1}static async connect(t,e){let n=new Ds(t,e);return await n.connect(e),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){let t=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},t)}handleHardClose(t){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(t))}async connect(t){let e;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{t?.timeout&&(e=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},t.timeout)),t?.abort&&(t.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(o){clearTimeout(e),r(o);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(e),this._connected=!0;let o=this.reconnectAttempts>0;this.reconnectAttempts=0;for(let i of this.openSubs.values()){if(i.eosed=!1,o)for(let s=0;s<i.filters.length;s++)i.lastEmitted&&(i.filters[s].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(e),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=o=>{clearTimeout(e),r(o.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(t=>{this.ws.once("pong",()=>t(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((t,e)=>{if(!this.connectionPromise)return e(new Error(`no connection to ${this.url}, can't ping`));try{let n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{t(!0),n.close()},onclose(){t(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){e(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(e=>setTimeout(()=>e(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(t){if(!this.connectionPromise)throw new wo(t,this.url);this.connectionPromise.then(()=>{this.ws?.send(t)})}async auth(t){let e=this.challenge;if(!e)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let o=await t(mf(this.url,e)),i=setTimeout(()=>{let s=this.openEventPublishes.get(o.id);s&&(s.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))},this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(o){console.warn("subscribe auth function failed:",o)}}),this.authPromise)}async publish(t){this.idleSince=void 0,this.ongoingOperations++;let e=new Promise((n,r)=>{let o=setTimeout(()=>{let i=this.openEventPublishes.get(t.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))},this.publishTimeout);this.openEventPublishes.set(t.id,{resolve:n,reject:r,timeout:o})});return this.send('["EVENT",'+JSON.stringify(t)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),e}async count(t,e){this.serial++;let n=e?.id||"count:"+this.serial,r=new Promise((o,i)=>{this.openCountRequests.set(n,{resolve:o,reject:i})});return this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1)),r}subscribe(t,e){e.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);let n=this.prepareSubscription(t,e);return n.fire(),e.abort&&(e.abort.onabort=()=>n.close(String(e.abort.reason||"<aborted>"))),n}prepareSubscription(t,e){this.serial++;let n=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new wf(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(t){let e=t.data;if(!e)return;let n=bf(e);if(n){let r=this.openSubs.get(n);if(!r)return;let o=yf(e,"id"),i=r.alreadyHaveEvent?.(o);if(r.receivedEvent?.(this,o),i)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{let o=this.openSubs.get(r[1]),i=r[2];this.verifyEvent(i)&&pf(o.filters,i)?o.onevent(i):o.oninvalidevent?.(i),(!o.lastEmitted||o.lastEmitted<i.created_at)&&(o.lastEmitted=i.created_at);return}case"COUNT":{let o=r[1],i=r[2],s=this.openCountRequests.get(o);s&&(s.resolve(i.count),this.openCountRequests.delete(o));return}case"EOSE":{let o=this.openSubs.get(r[1]);if(!o)return;o.receivedEose();return}case"OK":{let o=r[1],i=r[2],s=r[3],a=this.openEventPublishes.get(o);a&&(clearTimeout(a.timeout),i?a.resolve(s):a.reject(new Error(s)),this.openEventPublishes.delete(o));return}case"CLOSED":{let o=r[1],i=this.openSubs.get(o);if(!i)return;i.closed=!0,i.close(r[2]);return}case"NOTICE":{this.onnotice(r[1]);return}case"AUTH":{this.challenge=r[1],this.onauth&&this.auth(this.onauth).catch(o=>{if(!(o instanceof wo))throw o});return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{let[o,i,s]=JSON.parse(e);console.warn(`[nostr] relay ${this.url} error processing message:`,r,s)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},wf=class{constructor(t,e,n,r){v(this,"relay");v(this,"id");v(this,"lastEmitted");v(this,"closed",!1);v(this,"eosed",!1);v(this,"filters");v(this,"alreadyHaveEvent");v(this,"receivedEvent");v(this,"onevent");v(this,"oninvalidevent");v(this,"oneose");v(this,"onclose");v(this,"oncustom");v(this,"eoseTimeout");v(this,"eoseTimeoutHandle");if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof wo))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(t)}},xf=t=>(t[dt]=!0,!0),Ef=class{constructor(t){v(this,"relays",new Map);v(this,"seenOn",new Map);v(this,"trackRelays",!1);v(this,"verifyEvent");v(this,"enablePing");v(this,"enableReconnect");v(this,"automaticallyAuth");v(this,"trustedRelayURLs",new Set);v(this,"onRelayConnectionFailure");v(this,"onRelayConnectionSuccess");v(this,"allowConnectingToRelay");v(this,"maxWaitForConnection");v(this,"_WebSocket");this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,this.automaticallyAuth=t.automaticallyAuth,this.onRelayConnectionFailure=t.onRelayConnectionFailure,this.onRelayConnectionSuccess=t.onRelayConnectionSuccess,this.allowConnectingToRelay=t.allowConnectingToRelay,this.maxWaitForConnection=t.maxWaitForConnection||3e3}async ensureRelay(t,e){t=sn(t);let n=this.relays.get(t);if(n||(n=new Ds(t,{verifyEvent:this.trustedRelayURLs.has(t)?xf:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),n.onclose=()=>{this.relays.delete(t)},this.relays.set(t,n)),this.automaticallyAuth){let r=this.automaticallyAuth(t);r&&(n.onauth=r)}try{await n.connect({timeout:e?.connectionTimeout,abort:e?.abort})}catch(r){throw this.relays.delete(t),r}return n}close(t){t.map(sn).forEach(e=>{this.relays.get(e)?.close(),this.relays.delete(e)})}subscribe(t,e,n){let r=[],o=[];for(let i=0;i<t.length;i++){let s=sn(t[i]);r.find(a=>a.url===s)||o.indexOf(s)===-1&&(o.push(s),r.push({url:s,filter:e}))}return this.subscribeMap(r,n)}subscribeMany(t,e,n){return this.subscribe(t,e,n)}subscribeMap(t,e){let n=new Map;for(let f of t){let{url:u,filter:y}=f;n.has(u)||n.set(u,[]),n.get(u).push(y)}let r=Array.from(n.entries()).map(([f,u])=>({url:f,filters:u}));this.trackRelays&&(e.receivedEvent=(f,u)=>{let y=this.seenOn.get(u);y||(y=new Set,this.seenOn.set(u,y)),y.add(f)});let o=new Set,i=[],s=[],a=f=>{s[f]||(s[f]=!0,s.filter(u=>u).length===r.length&&(e.oneose?.(),a=()=>{}))},c=[],l=(f,u)=>{c[f]||(a(f),c[f]=u,c.filter(y=>y).length===r.length&&(e.onclose?.(c),l=()=>{}))},d=f=>{if(e.alreadyHaveEvent?.(f))return!0;let u=o.has(f);return o.add(f),u},h=Promise.all(r.map(async({url:f,filters:u},y)=>{if(this.allowConnectingToRelay?.(f,["read",u])===!1){l(y,"connection skipped by allowConnectingToRelay");return}let m;try{m=await this.ensureRelay(f,{connectionTimeout:this.maxWaitForConnection<(e.maxWait||0)?Math.max(e.maxWait*.8,e.maxWait-1e3):this.maxWaitForConnection,abort:e.abort})}catch(R){this.onRelayConnectionFailure?.(f),l(y,R?.message||String(R));return}this.onRelayConnectionSuccess?.(f);let S=m.subscribe(u,{...e,oneose:()=>a(y),onclose:R=>{R.startsWith("auth-required: ")&&e.onauth?m.auth(e.onauth).then(()=>{m.subscribe(u,{...e,oneose:()=>a(y),onclose:M=>{l(y,M)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort})}).catch(M=>{l(y,`auth was required and attempted, but failed with: ${M}`)}):l(y,R)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort});i.push(S)}));return{async close(f){await h,i.forEach(u=>{u.close(f)})}}}subscribeEose(t,e,n){let r;return r=this.subscribe(t,e,{...n,oneose(){let o="closed automatically on eose";r?r.close(o):n.onclose?.(t.map(i=>o))}}),r}subscribeManyEose(t,e,n){return this.subscribeEose(t,e,n)}async querySync(t,e,n){return new Promise(async r=>{let o=[];this.subscribeEose(t,e,{...n,onevent(i){o.push(i)},onclose(i){r(o)}})})}async get(t,e,n){e.limit=1;let r=await this.querySync(t,e,n);return r.sort((o,i)=>i.created_at-o.created_at),r[0]||null}publish(t,e,n){return t.map(sn).map(async(r,o,i)=>{if(i.indexOf(r)!==o)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(r,["write",e])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let s;try{s=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(a){return this.onRelayConnectionFailure?.(r),"connection failure: "+String(a)}return s.publish(e).catch(async a=>{if(a instanceof Error&&a.message.startsWith("auth-required: ")&&n?.onauth)return await s.auth(n.onauth),s.publish(e);throw a}).then(a=>{if(this.trackRelays){let c=this.seenOn.get(e.id);c||(c=new Set,this.seenOn.set(e.id,c)),c.add(s)}return a})})}listConnectionStatus(){let t=new Map;return this.relays.forEach((e,n)=>t.set(n,e.connected)),t}destroy(){this.relays.forEach(t=>t.close()),this.relays=new Map}pruneIdleRelays(t=1e4){let e=[];for(let[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=t&&(this.relays.delete(n),e.push(n),r.close());return e}},$s;try{$s=WebSocket}catch{}var vf=class extends Ef{constructor(t){super({verifyEvent:Hs,websocketImplementation:$s,maxWaitForConnection:3e3,...t})}},Vs;try{Vs=fetch}catch{}var Sf=/^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/;async function Ks(t){let e=t.match(Sf);if(e)try{let n=e[1],r=new URLSearchParams(e[2]);return{pubkey:n,relays:r.getAll("relay"),secret:r.get("secret")}}catch{}return Bf(t)}async function Bf(t){let e=t.match(uf);if(!e)return null;let[n,r="_",o]=e;try{let i=`https://${o}/.well-known/nostr.json?name=${r}`,s=await(await Vs(i,{redirect:"error"})).json(),a=s.names[r],c=s.nip46[a]||[];return{pubkey:a,relays:c,secret:null}}catch{return null}}var Nt=class{constructor(t,e){v(this,"params");v(this,"pool");v(this,"subCloser");v(this,"isOpen");v(this,"serial");v(this,"idPrefix");v(this,"listeners");v(this,"waitingForAuth");v(this,"secretKey");v(this,"conversationKey");v(this,"bp");v(this,"cachedPubKey");this.params=e,this.pool=e.pool||new vf,this.secretKey=t,this.isOpen=!1,this.idPrefix=Math.random().toString(36).substring(7),this.serial=0,this.listeners={},this.waitingForAuth={}}static fromBunker(t,e,n={}){if(e.relays.length===0)throw new Error("no relays specified for this bunker");let r=new Nt(t,n);return r.conversationKey=bo(t,e.pubkey),r.bp=e,r.setupSubscription(),r}static async fromURI(t,e,n={},r=3e5){let o=new Nt(t,n),i=new URL(e),s=Us(t);return new Promise((a,c)=>{let l=!1,d=o.pool.subscribe(i.searchParams.getAll("relay"),{kinds:[mo],"#p":[s],limit:0},{onevent:async h=>{try{let f=bo(t,h.pubkey),u=Os(h.content,f);JSON.parse(u).result===i.searchParams.get("secret")&&(d.close(),o.bp={pubkey:h.pubkey,relays:i.searchParams.getAll("relay"),secret:i.searchParams.get("secret")},o.conversationKey=bo(t,h.pubkey),o.setupSubscription(),l=!0,n.skipSwitchRelays||await Promise.race([new Promise(m=>setTimeout(m,1e3)),o.switchRelays()]),a(o))}catch(f){console.warn("failed to process potential connection event",f)}},onclose:()=>{l||c(new Error("subscription closed before connection was established."))},maxWait:typeof r=="number"?r:void 0,abort:typeof r!="number"?r:void 0})})}setupSubscription(){let t=this.listeners,e=this.waitingForAuth,n=this.conversationKey;this.subCloser=this.pool.subscribe(this.bp.relays,{kinds:[mo],authors:[this.bp.pubkey],"#p":[Us(this.secretKey)],limit:0},{onevent:async r=>{let o=JSON.parse(Os(r.content,n)),{id:i,result:s,error:a}=o;if(s==="auth_url"&&e[i]){delete e[i],this.params.onauth?this.params.onauth(a):console.warn(`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${a}' but there was no onauth() callback configured.`);return}let c=t[i];c&&(a?c.reject(a):s&&c.resolve(s),delete t[i])},onclose:()=>{this.subCloser=void 0}}),this.isOpen=!0}async switchRelays(){try{let t=await this.sendRequest("switch_relays",[]),e=JSON.parse(t);if(!e||JSON.stringify(e.sort())===JSON.stringify(this.bp.relays))return!1;this.bp.relays=e;let n=this.subCloser;return setTimeout(()=>{n.close()},5e3),this.subCloser=void 0,this.setupSubscription(),!0}catch{return!1}}async close(){this.isOpen=!1,this.subCloser.close()}async sendRequest(t,e){return new Promise(async(n,r)=>{try{if(!this.isOpen)throw new Error("this signer is not open anymore, create a new one");this.subCloser||this.setupSubscription(),this.serial++;let o=`${this.idPrefix}-${this.serial}`,i=ff(JSON.stringify({id:o,method:t,params:e}),this.conversationKey),s=rf({kind:mo,tags:[["p",this.bp.pubkey]],content:i,created_at:Math.floor(Date.now()/1e3)},this.secretKey);this.listeners[o]={resolve:n,reject:r},this.waitingForAuth[o]=!0,await Promise.any(this.pool.publish(this.bp.relays,s))}catch(o){r(o)}})}async ping(){let t=await this.sendRequest("ping",[]);if(t!=="pong")throw new Error(`result is not pong: ${t}`)}async connect(){await this.sendRequest("connect",[this.bp.pubkey,this.bp.secret||""])}async getPublicKey(){return this.cachedPubKey||(this.cachedPubKey=await this.sendRequest("get_public_key",[])),this.cachedPubKey}async signEvent(t){let e=await this.sendRequest("sign_event",[JSON.stringify(t)]),n=JSON.parse(e);if(Hs(n))return n;throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(n)}`)}async nip04Encrypt(t,e){return await this.sendRequest("nip04_encrypt",[t,e])}async nip04Decrypt(t,e){return await this.sendRequest("nip04_decrypt",[t,e])}async nip44Encrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}async nip44Decrypt(t,e){return await this.sendRequest("nip44_decrypt",[t,e])}};var _t=Symbol("verified"),kf=t=>t instanceof Object;function Af(t){if(!kf(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var a0=new TextDecoder("utf-8"),Rf=new TextEncoder,Cf=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=Bo(n),n.sig=ee(xe.sign(ne(Bo(n)),e)),n[_t]=!0,n}verifyEvent(t){if(typeof t[_t]=="boolean")return t[_t];try{let e=Bo(t);if(e!==t.id)return t[_t]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[_t]=n,n}catch{return t[_t]=!1,!1}}};function Tf(t){if(!Af(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 Bo(t){let e=fe(Rf.encode(Tf(t)));return ee(e)}var Xn=new Cf,c0=Xn.generateSecretKey,zs=Xn.getPublicKey,js=Xn.finalizeEvent,l0=Xn.verifyEvent;var Fn=new TextDecoder("utf-8"),g0=new TextEncoder;var Lf=5e3;function Zs(t){let{prefix:e,words:n}=po.decode(t,Lf),r=new Uint8Array(po.fromWords(n));switch(e){case"nprofile":{let o=ko(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:ee(o[0][0]),relays:o[1]?o[1].map(i=>Fn.decode(i)):[]}}}case"nevent":{let o=ko(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:ee(o[0][0]),relays:o[1]?o[1].map(i=>Fn.decode(i)):[],author:o[2]?.[0]?ee(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(ee(o[3][0]),16):void 0}}}case"naddr":{let o=ko(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Fn.decode(o[0][0]),pubkey:ee(o[2][0]),kind:parseInt(ee(o[3][0]),16),relays:o[1]?o[1].map(i=>Fn.decode(i)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:ee(r)};default:throw new Error(`unknown prefix ${e}`)}}function ko(t){let e={},n=t;for(;n.length>0;){let r=n[0],o=n[1],i=n.slice(2,2+o);if(n=n.slice(2+o),i.length<o)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(i)}return e}var If=new TextDecoder("utf-8"),Gs=new TextEncoder,Ao=1,Ro=4294967295,Co=65536;function Ut(t,e){let n=$n.getSharedSecret(t,ne("02"+e)).subarray(1,33);return jn(fe,n,Gs.encode("nip44-v2"))}function Ws(t,e){let n=Zn(fe,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Ys(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),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function Nf(t){if(!Number.isSafeInteger(t)||t<Ao||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 _f(t){if(!Number.isSafeInteger(t)||t<Co||t>Ro)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 Uf(t){let e=Gs.encode(t),n=e.length;if(n<Ao||n>Ro)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=Co?te(new Uint8Array([0,0]),_f(n)):Nf(n),o=new Uint8Array(Ys(n)-n);return te(r,e,o)}function Of(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<Co)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<Ao||r>Ro||i.length!==r||t.length!==o+Ys(r))throw new Error("invalid padding");return If.decode(i)}function Js(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Te(fe,t,r)}function Hf(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 n;try{n=It.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Xs(t,e,n=Be(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ws(e,n),s=Uf(t),a=ft(r,o,s),c=Js(i,a,n);return It.encode(te(new Uint8Array([2]),n,a,c))}function an(t,e){let{nonce:n,ciphertext:r,mac:o}=Hf(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ws(e,n),c=Js(a,r,n);if(!Tt(c,o))throw new Error("invalid MAC");let l=ft(i,s,r);return Of(l)}function cn(){return typeof window<"u"&&!!window.nostr&&typeof window.nostr.signEvent=="function"}var To=class{constructor(e,n){this.pubkey=e;this.provider=n;this.method="nip07";this.capabilities={canSignEvents:!0,hasNip44:!!n.nip44},n.nip44&&(this.nip44={encrypt:(r,o)=>n.nip44.encrypt(r,o),decrypt:(r,o)=>n.nip44.decrypt(r,o)})}async signEvent(e){return this.provider.signEvent(e)}async close(){}};async function ln(){if(!cn())throw new Error("no-nip07-provider");let t=window.nostr,e=await t.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-pubkey-from-nip07");return new To(e.toLowerCase(),t)}var Qn=class{constructor(e,n,r,o){this.pubkey=e;this.bunker=n;this.bunkerUri=r;this.clientSecretKey=o;this.method="bunker";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:(i,s)=>n.nip44Encrypt(i,s),decrypt:(i,s)=>n.nip44Decrypt(i,s)}}async signEvent(e){let{pubkey:n,...r}=e,o={kind:r.kind,content:r.content,created_at:r.created_at??Math.floor(Date.now()/1e3),tags:r.tags??[]};return await this.bunker.signEvent(o)}async close(){await this.bunker.close()}};async function Fs(t){let{uri:e,clientSecretKey:n,abortSignal:r}=t;if(n.length!==32)throw new Error("invalid-client-secret-key");let o=r?await Nt.fromURI(n,e,void 0,r):await Nt.fromURI(n,e),i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new Qn(i.toLowerCase(),o,e,n)}function Qs(t){let{clientPubkeyHex:e,relayUrl:n,secret:r}=t;if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-client-pubkey");if(!/^wss?:\/\//.test(n))throw new Error("invalid-relay-url");let o=new URLSearchParams({relay:n,secret:r});return t.perms&&t.perms.length>0&&o.set("perms",t.perms.join(",")),t.appName&&o.set("name",t.appName),t.appUrl&&o.set("url",t.appUrl),`nostrconnect://${e}?${o.toString()}`}async function fn(t){let e=t.uri.trim();if(!e)throw new Error("empty-bunker-uri");let n=await Ks(e);if(!n)throw new Error("invalid-bunker-uri");let r=t.clientSecretKey??Pf();if(r.length!==32)throw new Error("invalid-client-secret-key");let o=Nt.fromBunker(r,n,{onauth:t.onauth});await o.connect();let i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new Qn(i.toLowerCase(),o,e,r)}function Pf(){let t=new Uint8Array(32);return crypto.getRandomValues(t),t}var Lo=class{constructor(e,n){this.pubkey=e;this.privkey=n;this.method="nsec";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:async(r,o)=>Xs(o,Ut(this.privkey,r)),decrypt:async(r,o)=>an(o,Ut(this.privkey,r))}}async signEvent(e){let n={kind:e.kind,content:e.content,created_at:e.created_at??Math.floor(Date.now()/1e3),tags:e.tags??[]};return js(n,this.privkey)}async close(){this.privkey.fill(0)}};function ea(t){let e=t.trim();if(!e)throw new Error("empty-nsec");let n;if(e.startsWith("nsec1")){let o=Zs(e);if(o.type!=="nsec")throw new Error("not-an-nsec");n=o.data}else if(/^[0-9a-f]{64}$/i.test(e)){n=new Uint8Array(32);for(let o=0;o<32;o++)n[o]=parseInt(e.slice(o*2,o*2+2),16)}else throw new Error("invalid-nsec-format");if(n.length!==32)throw new Error("invalid-nsec-length");let r=zs(n);if(!/^[0-9a-f]{64}$/i.test(r))throw new Error("invalid-pubkey-from-nsec");return new Lo(r.toLowerCase(),n)}var Ee=class{constructor(e,n){this.pubkey=e;this.authEvent=n;this.method="redirect";this.capabilities={canSignEvents:!1,hasNip44:!1}}async signEvent(e){throw new Error("signer-auth-only: this session was established via redirect and cannot sign new events. Install a NIP-07 extension (bark, Alby) or paste a bunker URI to upgrade.")}async close(){}};function We(t){try{return typeof localStorage<"u"?localStorage.getItem(t):null}catch{return null}}function Ye(t,e){try{typeof localStorage<"u"&&localStorage.setItem(t,e)}catch{}}function Je(t){try{typeof localStorage<"u"&&localStorage.removeItem(t)}catch{}}function ta(t){Ye(Q.pubkey,t.pubkey),Ye(Q.method,t.method),Ye(Q.authEvent,t.authEventJson),t.bunkerUri!==void 0&&Ye(Q.bunkerUri,t.bunkerUri),t.bunkerClientSkHex!==void 0&&Ye(Q.bunkerClientSk,t.bunkerClientSkHex),t.expiresAt!==void 0&&Ye(Q.expiresAt,String(t.expiresAt)),t.displayName!==void 0&&Ye(Q.displayName,t.displayName)}function na(){let t=We(Q.pubkey),e=We(Q.method),n=We(Q.authEvent);if(!t||!e||!n||!/^[0-9a-f]{64}$/i.test(t)||e!=="nip07"&&e!=="redirect"&&e!=="bunker"&&e!=="amber")return null;let r;try{if(r=JSON.parse(n),typeof r!="object"||r===null||r.pubkey!==t)return null}catch{return null}let o=We(Q.expiresAt),i=o?Number(o):void 0;if(i!==void 0&&Number.isFinite(i)&&Date.now()>i)return He(),null;let s={pubkey:t,method:e,authEventJson:n},a=We(Q.bunkerUri),c=We(Q.bunkerClientSk),l=We(Q.displayName);return a&&(s.bunkerUri=a),c&&(s.bunkerClientSkHex=c),i!==void 0&&Number.isFinite(i)&&(s.expiresAt=i),l&&(s.displayName=l),s}function He(){Je(Q.pubkey),Je(Q.method),Je(Q.authEvent),Je(Q.bunkerUri),Je(Q.bunkerClientSk),Je(Q.expiresAt),Je(Q.displayName)}function er(t){Ye(Q.pendingRedirect,JSON.stringify(t))}function tr(){let t=We(Q.pendingRedirect);if(!t)return null;try{let e=JSON.parse(t),n=e.challenge,r=e.origin,o=e.appName,i=e.createdAt;return typeof n!="string"||!/^[0-9a-f]{64}$/i.test(n)||typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof i!="number"||!Number.isFinite(i)?null:{challenge:n,origin:r,appName:o,createdAt:i}}catch{return null}}function nr(){Je(Q.pendingRedirect)}function ra(t){let e="";for(let n=0;n<t.length;n++)e+=t[n].toString(16).padStart(2,"0");return e}function oa(t){if(t.length%2!==0)throw new Error("odd-hex-length");let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function rr(){return typeof navigator>"u"?!1:/android/i.test(navigator.userAgent)}var ia=/^[0-9a-f]{64}$/i;function Mf(t){return{kind:21236,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["challenge",t.challenge],["origin",t.origin],["app",t.appName]]}}function qf(t){let e=Mf(t),n=JSON.stringify(e),r=typeof btoa=="function"?btoa(n):Buffer.from(n,"utf-8").toString("base64"),o=t.redirectCallback??`${t.origin}/?signet_amber=1`,i=new URLSearchParams({type:"sign_event",compressionType:"base64",returnType:"event",callbackUrl:o});return`nostrsigner:${r}?${i.toString()}`}function sa(t){if(typeof window>"u")throw new Error("signet-login: amber mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};return er(e),window.location.href=qf(t),new Promise(()=>{})}function Df(){if(typeof window>"u")return;let t=new URL(window.location.href),e=!1;for(let r of["event","signet_amber","error"])t.searchParams.has(r)&&(t.searchParams.delete(r),e=!0);if(!e)return;let n=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,n)}catch{}}function aa(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search);if(!(t.has("signet_amber")||t.has("event")))return{kind:"no-callback"};let n=h=>(nr(),Df(),h);if(t.get("error")==="denied")return n({kind:"denied"});let r=tr();if(!r)return n({kind:"invalid",reason:"no-pending-state"});if(r.origin!==window.location.origin)return n({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-r.createdAt>Rn)return n({kind:"invalid",reason:"pending-stale"});let o=t.get("event");if(!o)return n({kind:"invalid",reason:"no-event-param"});let i;try{let h;try{h=typeof atob=="function"?atob(o):Buffer.from(o,"base64").toString("utf-8")}catch{h=o}i=JSON.parse(h)}catch{return n({kind:"invalid",reason:"event-malformed"})}if(typeof i!="object"||i===null)return n({kind:"invalid",reason:"event-not-object"});let s=i;if(typeof s.id!="string"||!ia.test(s.id)||typeof s.pubkey!="string"||!ia.test(s.pubkey)||typeof s.sig!="string"||!/^[0-9a-f]{128}$/i.test(s.sig)||typeof s.created_at!="number"||!Array.isArray(s.tags)||s.kind!==21236||typeof s.content!="string")return n({kind:"invalid",reason:"event-shape-invalid"});let a=s.tags.find(h=>Array.isArray(h)&&h[0]==="challenge");if(!a||a[1]!==r.challenge)return n({kind:"invalid",reason:"challenge-mismatch"});let c={id:s.id.toLowerCase(),pubkey:s.pubkey.toLowerCase(),kind:21236,created_at:s.created_at,tags:s.tags,content:s.content,sig:s.sig.toLowerCase()},l=new Ee(c.pubkey,c),d={pubkey:c.pubkey,method:"amber",signer:l,authEvent:c};return n({kind:"session",session:d})}var ht=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function gt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function un(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ae(t,...e){if(!gt(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function or(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");un(t.outputLen),un(t.blockLen)}function Ht(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 la(t,e){Ae(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function pt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ir(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Re(t,e){return t<<32-e|t>>>e}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$f=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function le(t){if(Ae(t),fa)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=$f[t[n]];return e}var Pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function ca(t){if(t>=Pe._0&&t<=Pe._9)return t-Pe._0;if(t>=Pe.A&&t<=Pe.F)return t-(Pe.A-10);if(t>=Pe.a&&t<=Pe.f)return t-(Pe.a-10)}function yt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(fa)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=ca(t.charCodeAt(i)),a=ca(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function sr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function dn(t){return typeof t=="string"&&(t=sr(t)),Ae(t),t}function pe(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Ae(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}var Ot=class{};function ua(t){let e=r=>t().update(dn(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function bt(t=32){if(ht&&typeof ht.getRandomValues=="function")return ht.getRandomValues(new Uint8Array(t));if(ht&&typeof ht.randomBytes=="function")return Uint8Array.from(ht.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Vf(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+l,a,r)}function da(t,e,n){return t&e^~t&n}function ha(t,e,n){return t&e^t&n^e&n}var ar=class extends Ot{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ir(this.buffer)}update(e){Ht(this),e=dn(e),Ae(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ir(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ht(this),la(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,pt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let h=s;h<o;h++)n[h]=0;Vf(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=ir(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Kf=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]),Xe=new Uint32Array(64),cr=class extends ar{constructor(e=32){super(64,e,8,!1),this.A=Me[0]|0,this.B=Me[1]|0,this.C=Me[2]|0,this.D=Me[3]|0,this.E=Me[4]|0,this.F=Me[5]|0,this.G=Me[6]|0,this.H=Me[7]|0}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)Xe[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){let f=Xe[h-15],u=Xe[h-2],y=Re(f,7)^Re(f,18)^f>>>3,m=Re(u,17)^Re(u,19)^u>>>10;Xe[h]=m+Xe[h-7]+y+Xe[h-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){let f=Re(a,6)^Re(a,11)^Re(a,25),u=d+f+da(a,c,l)+Kf[h]+Xe[h]|0,m=(Re(r,2)^Re(r,13)^Re(r,22))+ha(r,o,i)|0;d=l,l=c,c=a,a=s+u|0,s=i,i=o,o=r,r=u+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){pt(Xe)}destroy(){this.set(0,0,0,0,0,0,0,0),pt(this.buffer)}};var Pt=ua(()=>new cr);var lr=class extends Ot{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,or(e);let r=dn(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(r.length>o?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),pt(i)}update(e){return Ht(this),this.iHash.update(e),this}digestInto(e){Ht(this),Ae(e,this.outputLen),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||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Io=(t,e,n)=>new lr(t,e).update(n).digest();Io.create=(t,e)=>new lr(t,e);var Uo=BigInt(0),_o=BigInt(1);function hn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Fe(t,e,n=""){let r=gt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function gn(t){let e=t.toString(16);return e.length&1?"0"+e:e}function ga(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Uo:BigInt("0x"+t)}function qe(t){return ga(le(t))}function Oo(t){return Ae(t),ga(le(Uint8Array.from(t).reverse()))}function Mt(t,e){return yt(t.toString(16).padStart(e*2,"0"))}function Ho(t,e){return Mt(t,e).reverse()}function re(t,e,n){let r;if(typeof e=="string")try{r=yt(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(gt(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}var No=t=>typeof t=="bigint"&&Uo<=t;function pn(t,e,n){return No(t)&&No(e)&&No(n)&&e<=t&&t<n}function pa(t,e,n,r){if(!pn(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function fr(t){let e;for(e=0;t>Uo;t>>=_o,e+=1);return e}var Qe=t=>(_o<<BigInt(t))-_o;function ya(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=u=>new Uint8Array(u),o=u=>Uint8Array.of(u),i=r(t),s=r(t),a=0,c=()=>{i.fill(1),s.fill(0),a=0},l=(...u)=>n(s,i,...u),d=(u=r(0))=>{s=l(o(0),u),i=l(),u.length!==0&&(s=l(o(1),u),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,y=[];for(;u<e;){i=l();let m=i.slice();y.push(m),u+=i.length}return pe(...y)};return(u,y)=>{c(),d(u);let m;for(;!(m=y(h()));)d();return c(),m}}function yn(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,i,s){let a=t[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Po(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var ge=BigInt(0),de=BigInt(1),mt=BigInt(2),wa=BigInt(3),xa=BigInt(4),Ea=BigInt(5),zf=BigInt(7),va=BigInt(8),jf=BigInt(9),Sa=BigInt(16);function be(t,e){let n=t%e;return n>=ge?n:e+n}function me(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function ba(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,o=ge,i=de,s=de,a=ge;for(;n!==ge;){let l=r/n,d=r%n,h=o-s*l,f=i-a*l;r=n,n=d,o=s,i=a,s=h,a=f}if(r!==de)throw new Error("invert: does not exist");return be(o,e)}function Mo(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ba(t,e){let n=(t.ORDER+de)/xa,r=t.pow(e,n);return Mo(t,r,e),r}function Zf(t,e){let n=(t.ORDER-Ea)/va,r=t.mul(e,mt),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,mt),o),a=t.mul(i,t.sub(s,t.ONE));return Mo(t,a,e),a}function Gf(t){let e=et(t),n=ka(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+zf)/Sa;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),h=a.mul(l,o),f=a.mul(l,i),u=a.eql(a.sqr(d),c),y=a.eql(a.sqr(h),c);l=a.cmov(l,d,u),d=a.cmov(f,h,y);let m=a.eql(a.sqr(d),c),S=a.cmov(l,d,m);return Mo(a,S,c),S}}function ka(t){if(t<wa)throw new Error("sqrt is not defined for small field");let e=t-de,n=0;for(;e%mt===ge;)e/=mt,n++;let r=mt,o=et(t);for(;ma(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ba;let i=o.pow(r,e),s=(e+de)/mt;return function(c,l){if(c.is0(l))return l;if(ma(c,l)!==1)throw new Error("Cannot find square root");let d=n,h=c.mul(c.ONE,i),f=c.pow(l,e),u=c.pow(l,s);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let y=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let S=de<<BigInt(d-y-1),R=c.pow(h,S);d=y,h=c.sqr(R),f=c.mul(f,h),u=c.mul(u,R)}return u}}function Wf(t){return t%xa===wa?Ba:t%va===Ea?Zf:t%Sa===jf?Gf(t):ka(t)}var Yf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qo(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Yf.reduce((r,o)=>(r[o]="function",r),e);return yn(t,n),t}function Jf(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===de)return e;let r=t.ONE,o=e;for(;n>ge;)n&de&&(r=t.mul(r,o)),o=t.sqr(o),n>>=de;return r}function ur(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function ma(t,e){let n=(t.ORDER-de)/mt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function dr(t,e){e!==void 0&&un(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function et(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,i,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(o=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(s=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(i=r.sqrt);let{nBitLength:c,nByteLength:l}=dr(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,h=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Qe(c),ZERO:ge,ONE:de,allowedLengths:a,create:f=>be(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ge<=f&&f<t},is0:f=>f===ge,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&de)===de,neg:f=>be(-f,t),eql:(f,u)=>f===u,sqr:f=>be(f*f,t),add:(f,u)=>be(f+u,t),sub:(f,u)=>be(f-u,t),mul:(f,u)=>be(f*u,t),pow:(f,u)=>Jf(h,f,u),div:(f,u)=>be(f*ba(u,t),t),sqrN:f=>f*f,addN:(f,u)=>f+u,subN:(f,u)=>f-u,mulN:(f,u)=>f*u,inv:f=>ba(f,t),sqrt:i||(f=>(d||(d=Wf(t)),d(h,f))),toBytes:f=>n?Ho(f,l):Mt(f,l),fromBytes:(f,u=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let y=n?Oo(f):qe(f);if(s&&(y=be(y,t)),!u&&!h.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:f=>ur(h,f),cmov:(f,u,y)=>y?u:f});return Object.freeze(h)}function Aa(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 Do(t){let e=Aa(t);return e+Math.ceil(e/2)}function hr(t,e,n=!1){let r=t.length,o=Aa(e),i=Do(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Oo(t):qe(t),a=be(s,e-de)+de;return n?Ho(a,o):Mt(a,o)}var qt=BigInt(0),wt=BigInt(1);function bn(t,e){let n=e.negate();return t?n:e}function pr(t,e){let n=ur(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function La(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $o(t,e){La(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Qe(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Ra(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=wt);let l=e*r,d=l+Math.abs(a)-1,h=a===0,f=a<0,u=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:f,isNegF:u,offsetF:l}}function Xf(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Ff(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}var Vo=new WeakMap,Ia=new WeakMap;function Ko(t){return Ia.get(t)||1}function Ca(t){if(t!==qt)throw new Error("invalid wNAF")}var gr=class{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>qt;)n&wt&&(r=r.add(o)),o=o.double(),n>>=wt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=$o(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=$o(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:f,offsetF:u}=Ra(r,a,s);r=c,d?i=i.add(bn(f,n[u])):o=o.add(bn(h,n[l]))}return Ca(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=$o(e,this.bits);for(let s=0;s<i.windows&&r!==qt;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Ra(r,s,i);if(r=a,!l){let h=n[c];o=o.add(d?h.negate():h)}}return Ca(r),o}getPrecomputes(e,n,r){let o=Vo.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Vo.set(n,o))),o}cached(e,n,r){let o=Ko(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Ko(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){La(n,this.bits),Ia.set(e,n),Vo.delete(e)}hasCache(e){return Ko(e)!==1}};function Na(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>qt||r>qt;)n&wt&&(i=i.add(o)),r&wt&&(s=s.add(o)),o=o.double(),n>>=wt,r>>=wt;return{p1:i,p2:s}}function _a(t,e,n,r){Xf(n,t),Ff(r,e);let o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,a=fr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Qe(c),d=new Array(Number(l)+1).fill(s),h=Math.floor((e.BITS-1)/c)*c,f=s;for(let u=h;u>=0;u-=c){d.fill(s);for(let m=0;m<i;m++){let S=r[m],R=Number(S>>BigInt(u)&l);d[R]=d[R].add(n[m])}let y=s;for(let m=d.length-1,S=s;m>0;m--)S=S.add(d[m]),y=y.add(S);if(f=f.add(y),u!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Ta(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qo(e),e}else return et(t,{isLE:n})}function Ua(t,e,n={},r){if(r===void 0&&(r=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>qt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ta(e.p,n.Fp,r),i=Ta(e.n,n.Fn,r),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:i}}var Oa=(t,e)=>(t+(t>=0?e:-e)/Ha)/e;function Qf(t,e,n){let[[r,o],[i,s]]=e,a=Oa(s*t,n),c=Oa(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,h=l<$e,f=d<$e;h&&(l=-l),f&&(d=-d);let u=Qe(Math.ceil(fr(n)/2))+Dt;if(l<$e||l>=u||d<$e||d>=u)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:d}}function jo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function zo(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return hn(n.lowS,"lowS"),hn(n.prehash,"prehash"),n.format!==void 0&&jo(n.format),n}var Zo=class extends Error{constructor(e=""){super(e)}},De={Err:Zo,_tlv:{encode:(t,e)=>{let{Err:n}=De;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=gn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?gn(o.length/2|128):"";return gn(t)+i+o+e},decode(t,e){let{Err:n}=De,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=De;if(t<$e)throw new e("integer: negative integers are not allowed");let n=gn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=De;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 qe(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=De,o=re("signature",t),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=De,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},$e=BigInt(0),Dt=BigInt(1),Ha=BigInt(2),yr=BigInt(3),eu=BigInt(4);function tt(t,e){let{BYTES:n}=t,r;if(typeof e=="bigint")r=e;else{let o=re("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function tu(t,e={}){let n=Ua("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;yn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Ma(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(T,x,g){let{x:p,y:b}=x.toAffine(),E=r.toBytes(p);if(hn(g,"isCompressed"),g){d();let k=!r.isOdd(b);return pe(Pa(k),E)}else return pe(Uint8Array.of(4),E,r.toBytes(b))}function f(T){Fe(T,void 0,"Point");let{publicKey:x,publicKeyUncompressed:g}=l,p=T.length,b=T[0],E=T.subarray(1);if(p===x&&(b===2||b===3)){let k=r.fromBytes(E);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");let w=m(k),A;try{A=r.sqrt(w)}catch(O){let D=O instanceof Error?": "+O.message:"";throw new Error("bad point: is not on curve, sqrt error"+D)}d();let B=r.isOdd(A);return(b&1)===1!==B&&(A=r.neg(A)),{x:k,y:A}}else if(p===g&&b===4){let k=r.BYTES,w=r.fromBytes(E.subarray(0,k)),A=r.fromBytes(E.subarray(k,k*2));if(!S(w,A))throw new Error("bad point: is not on curve");return{x:w,y:A}}else throw new Error(`bad point: got length ${p}, expected compressed=${x} or uncompressed=${g}`)}let u=e.toBytes||h,y=e.fromBytes||f;function m(T){let x=r.sqr(T),g=r.mul(x,T);return r.add(r.add(g,r.mul(T,i.a)),i.b)}function S(T,x){let g=r.sqr(x),p=m(T);return r.eql(g,p)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,yr),eu),M=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,M)))throw new Error("bad curve params: a or b");function I(T,x,g=!1){if(!r.isValid(x)||g&&r.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function _(T){if(!(T instanceof L))throw new Error("ProjectivePoint expected")}function N(T){if(!c||!c.basises)throw new Error("no endo");return Qf(T,c.basises,o.ORDER)}let q=Po((T,x)=>{let{X:g,Y:p,Z:b}=T;if(r.eql(b,r.ONE))return{x:g,y:p};let E=T.is0();x==null&&(x=E?r.ONE:r.inv(b));let k=r.mul(g,x),w=r.mul(p,x),A=r.mul(b,x);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:k,y:w}}),j=Po(T=>{if(T.is0()){if(e.allowInfinityPoint&&!r.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x,y:g}=T.toAffine();if(!r.isValid(x)||!r.isValid(g))throw new Error("bad point: x or y not field elements");if(!S(x,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(T,x,g,p,b){return g=new L(r.mul(g.X,T),g.Y,g.Z),x=bn(p,x),g=bn(b,g),x.add(g)}class L{constructor(x,g,p){this.X=I("x",x),this.Y=I("y",g,!0),this.Z=I("z",p),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:g,y:p}=x||{};if(!x||!r.isValid(g)||!r.isValid(p))throw new Error("invalid affine point");if(x instanceof L)throw new Error("projective point not allowed");return r.is0(g)&&r.is0(p)?L.ZERO:new L(g,p,r.ONE)}static fromBytes(x){let g=L.fromAffine(y(Fe(x,void 0,"point")));return g.assertValidity(),g}static fromHex(x){return L.fromBytes(re("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,g=!0){return $.createCache(this,x),g||this.multiply(yr),this}assertValidity(){j(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){_(x);let{X:g,Y:p,Z:b}=this,{X:E,Y:k,Z:w}=x,A=r.eql(r.mul(g,w),r.mul(E,b)),B=r.eql(r.mul(p,w),r.mul(k,b));return A&&B}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:g}=i,p=r.mul(g,yr),{X:b,Y:E,Z:k}=this,w=r.ZERO,A=r.ZERO,B=r.ZERO,C=r.mul(b,b),O=r.mul(E,E),D=r.mul(k,k),P=r.mul(b,E);return P=r.add(P,P),B=r.mul(b,k),B=r.add(B,B),w=r.mul(x,B),A=r.mul(p,D),A=r.add(w,A),w=r.sub(O,A),A=r.add(O,A),A=r.mul(w,A),w=r.mul(P,w),B=r.mul(p,B),D=r.mul(x,D),P=r.sub(C,D),P=r.mul(x,P),P=r.add(P,B),B=r.add(C,C),C=r.add(B,C),C=r.add(C,D),C=r.mul(C,P),A=r.add(A,C),D=r.mul(E,k),D=r.add(D,D),C=r.mul(D,P),w=r.sub(w,C),B=r.mul(D,O),B=r.add(B,B),B=r.add(B,B),new L(w,A,B)}add(x){_(x);let{X:g,Y:p,Z:b}=this,{X:E,Y:k,Z:w}=x,A=r.ZERO,B=r.ZERO,C=r.ZERO,O=i.a,D=r.mul(i.b,yr),P=r.mul(g,E),U=r.mul(p,k),V=r.mul(b,w),W=r.add(g,p),K=r.add(E,k);W=r.mul(W,K),K=r.add(P,U),W=r.sub(W,K),K=r.add(g,b);let G=r.add(E,w);return K=r.mul(K,G),G=r.add(P,V),K=r.sub(K,G),G=r.add(p,b),A=r.add(k,w),G=r.mul(G,A),A=r.add(U,V),G=r.sub(G,A),C=r.mul(O,K),A=r.mul(D,V),C=r.add(A,C),A=r.sub(U,C),C=r.add(U,C),B=r.mul(A,C),U=r.add(P,P),U=r.add(U,P),V=r.mul(O,V),K=r.mul(D,K),U=r.add(U,V),V=r.sub(P,V),V=r.mul(O,V),K=r.add(K,V),P=r.mul(U,K),B=r.add(B,P),P=r.mul(G,K),A=r.mul(W,A),A=r.sub(A,P),P=r.mul(W,U),C=r.mul(G,C),C=r.add(C,P),new L(A,B,C)}subtract(x){return this.add(x.negate())}is0(){return this.equals(L.ZERO)}multiply(x){let{endo:g}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let p,b,E=k=>$.cached(this,k,w=>pr(L,w));if(g){let{k1neg:k,k1:w,k2neg:A,k2:B}=N(x),{p:C,f:O}=E(w),{p:D,f:P}=E(B);b=O.add(P),p=Z(g.beta,C,D,k,A)}else{let{p:k,f:w}=E(x);p=k,b=w}return pr(L,[p,b])[0]}multiplyUnsafe(x){let{endo:g}=e,p=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===$e||p.is0())return L.ZERO;if(x===Dt)return p;if($.hasCache(this))return this.multiply(x);if(g){let{k1neg:b,k1:E,k2neg:k,k2:w}=N(x),{p1:A,p2:B}=Na(L,p,E,w);return Z(g.beta,A,B,b,k)}else return $.unsafe(p,x)}multiplyAndAddUnsafe(x,g,p){let b=this.multiplyUnsafe(g).add(x.multiplyUnsafe(p));return b.is0()?void 0:b}toAffine(x){return q(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return s===Dt?!0:x?x(L,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===Dt?this:x?x(L,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return hn(x,"isCompressed"),this.assertValidity(),u(L,this,x)}toHex(x=!0){return le(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return pr(L,x)}static msm(x,g){return _a(L,o,x,g)}static fromPrivateKey(x){return L.BASE.multiply(tt(o,x))}}L.BASE=new L(i.Gx,i.Gy,r.ONE),L.ZERO=new L(r.ZERO,r.ONE,r.ZERO),L.Fp=r,L.Fn=o;let z=o.BITS,$=new gr(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function Pa(t){return Uint8Array.of(t?2:3)}function Ma(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function nu(t,e={}){let{Fn:n}=t,r=e.randomBytes||bt,o=Object.assign(Ma(t.Fp,n),{seed:Do(n.ORDER)});function i(u){try{return!!tt(n,u)}catch{return!1}}function s(u,y){let{publicKey:m,publicKeyUncompressed:S}=o;try{let R=u.length;return y===!0&&R!==m||y===!1&&R!==S?!1:!!t.fromBytes(u)}catch{return!1}}function a(u=r(o.seed)){return hr(Fe(u,o.seed,"seed"),n.ORDER)}function c(u,y=!0){return t.BASE.multiply(tt(n,u)).toBytes(y)}function l(u){let y=a(u);return{secretKey:y,publicKey:c(y)}}function d(u){if(typeof u=="bigint")return!1;if(u instanceof t)return!0;let{secretKey:y,publicKey:m,publicKeyUncompressed:S}=o;if(n.allowedLengths||y===m)return;let R=re("key",u).length;return R===m||R===S}function h(u,y,m=!0){if(d(u)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let S=tt(n,u);return t.fromHex(y).multiply(S).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:u=>tt(n,u),precompute(u=8,y=t.BASE){return y.precompute(u,!1)}},lengths:o})}function ru(t,e,n={}){or(e),yn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||bt,o=n.hmac||((g,...p)=>Io(e,g,pe(...p))),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u}=nu(t,n),y={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function S(g){let p=a>>Dt;return g>p}function R(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function M(g,p){jo(p);let b=u.signature,E=p==="compact"?b:p==="recovered"?b+1:void 0;return Fe(g,E,`${p} signature`)}class I{constructor(p,b,E){this.r=R("r",p),this.s=R("s",b),E!=null&&(this.recovery=E),Object.freeze(this)}static fromBytes(p,b=m){M(p,b);let E;if(b==="der"){let{r:B,s:C}=De.toSig(Fe(p));return new I(B,C)}b==="recovered"&&(E=p[0],b="compact",p=p.subarray(1));let k=s.BYTES,w=p.subarray(0,k),A=p.subarray(k,k*2);return new I(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(p,b){return this.fromBytes(yt(p),b)}addRecoveryBit(p){return new I(this.r,this.s,p)}recoverPublicKey(p){let b=i.ORDER,{r:E,s:k,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*Ha<b&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=w===2||w===3?E+a:E;if(!i.isValid(B))throw new Error("recovery id 2 or 3 invalid");let C=i.toBytes(B),O=t.fromBytes(pe(Pa((w&1)===0),C)),D=s.inv(B),P=N(re("msgHash",p)),U=s.create(-P*D),V=s.create(k*D),W=t.BASE.multiplyUnsafe(U).add(O.multiplyUnsafe(V));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return S(this.s)}toBytes(p=m){if(jo(p),p==="der")return yt(De.hexFromSig(this));let b=s.toBytes(this.r),E=s.toBytes(this.s);if(p==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pe(Uint8Array.of(this.recovery),b,E)}return pe(b,E)}toHex(p){return le(this.toBytes(p))}assertValidity(){}static fromCompact(p){return I.fromBytes(re("sig",p),"compact")}static fromDER(p){return I.fromBytes(re("sig",p),"der")}normalizeS(){return this.hasHighS()?new I(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return le(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return le(this.toBytes("compact"))}}let _=n.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let b=qe(p),E=p.length*8-c;return E>0?b>>BigInt(E):b},N=n.bits2int_modN||function(p){return s.create(_(p))},q=Qe(c);function j(g){return pa("num < 2^"+c,g,$e,q),s.toBytes(g)}function Z(g,p){return Fe(g,void 0,"message"),p?Fe(e(g),void 0,"prehashed message"):g}function L(g,p,b){if(["recovered","canonical"].some(U=>U in b))throw new Error("sign() legacy options not supported");let{lowS:E,prehash:k,extraEntropy:w}=zo(b,y);g=Z(g,k);let A=N(g),B=tt(s,p),C=[j(B),j(A)];if(w!=null&&w!==!1){let U=w===!0?r(u.secretKey):w;C.push(re("extraEntropy",U))}let O=pe(...C),D=A;function P(U){let V=_(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===$e)return;let oe=s.create(W*s.create(D+G*B));if(oe===$e)return;let Wt=(K.x===G?0:2)|Number(K.y&Dt),Yt=oe;return E&&S(oe)&&(Yt=s.neg(oe),Wt^=1),new I(G,Yt,Wt)}return{seed:O,k2sig:P}}function z(g,p,b={}){g=re("message",g);let{seed:E,k2sig:k}=L(g,p,b);return ya(e.outputLen,s.BYTES,o)(E,k)}function $(g){let p,b=typeof g=="string"||gt(g),E=!b&&g!==null&&typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint";if(!b&&!E)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(E)p=new I(g.r,g.s);else if(b){try{p=I.fromBytes(re("sig",g),"der")}catch(k){if(!(k instanceof De.Err))throw k}if(!p)try{p=I.fromBytes(re("sig",g),"compact")}catch{return!1}}return p||!1}function T(g,p,b,E={}){let{lowS:k,prehash:w,format:A}=zo(E,y);if(b=re("publicKey",b),p=Z(re("message",p),w),"strict"in E)throw new Error("options.strict was renamed to lowS");let B=A===void 0?$(g):I.fromBytes(re("sig",g),A);if(B===!1)return!1;try{let C=t.fromBytes(b);if(k&&B.hasHighS())return!1;let{r:O,s:D}=B,P=N(p),U=s.inv(D),V=s.create(P*U),W=s.create(O*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===O}catch{return!1}}function x(g,p,b={}){let{prehash:E}=zo(b,y);return p=Z(p,E),I.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:f,lengths:u,Point:t,sign:z,verify:T,recoverPublicKey:x,Signature:I,hash:e})}function ou(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=et(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function iu(t){let{CURVE:e,curveOpts:n}=ou(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function su(t,e){let n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,dr(n.Fn.ORDER,n.Fn.BITS))})}function qa(t){let{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=iu(t),i=tu(e,n),s=ru(i,r,o);return su(t,s)}function Da(t,e){let n=r=>qa({...t,hash:r});return{...n(e),create:n}}var $t={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},au={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},cu=BigInt(0),$a=BigInt(1),Go=BigInt(2);function lu(t){let e=$t.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,h=me(d,n,e)*d%e,f=me(h,n,e)*d%e,u=me(f,Go,e)*l%e,y=me(u,o,e)*u%e,m=me(y,i,e)*y%e,S=me(m,a,e)*m%e,R=me(S,c,e)*S%e,M=me(R,a,e)*m%e,I=me(M,n,e)*d%e,_=me(I,s,e)*y%e,N=me(_,r,e)*l%e,q=me(N,Go,e);if(!br.eql(br.sqr(q),t))throw new Error("Cannot find square root");return q}var br=et($t.p,{sqrt:lu}),za=Da({...$t,Fp:br,lowS:!0,endo:au},Pt),Va={};function mr(t,...e){let n=Va[t];if(n===void 0){let r=Pt(sr(t));n=pe(r,r),Va[t]=n}return Pt(pe(n,...e))}var Yo=t=>t.toBytes(!0).slice(1),Vt=za.Point,Jo=t=>t%Go===cu;function Wo(t){let{Fn:e,BASE:n}=Vt,r=tt(e,t),o=n.multiply(r);return{scalar:Jo(o.y)?r:e.neg(r),bytes:Yo(o)}}function ja(t){let e=br;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);Jo(o)||(o=e.neg(o));let i=Vt.fromAffine({x:t,y:o});return i.assertValidity(),i}var mn=qe;function Za(...t){return Vt.Fn.create(mn(mr("BIP0340/challenge",...t)))}function Ka(t){return Wo(t).bytes}function fu(t,e,n=bt(32)){let{Fn:r}=Vt,o=re("message",t),{bytes:i,scalar:s}=Wo(e),a=re("auxRand",n,32),c=r.toBytes(s^mn(mr("BIP0340/aux",a))),l=mr("BIP0340/nonce",c,i,o),{bytes:d,scalar:h}=Wo(l),f=Za(d,i,o),u=new Uint8Array(64);if(u.set(d,0),u.set(r.toBytes(r.create(h+f*s)),32),!Ga(u,o,i))throw new Error("sign: Invalid signature produced");return u}function Ga(t,e,n){let{Fn:r,BASE:o}=Vt,i=re("signature",t,64),s=re("message",e),a=re("publicKey",n,32);try{let c=ja(mn(a)),l=mn(i.subarray(0,32));if(!pn(l,$a,$t.p))return!1;let d=mn(i.subarray(32,64));if(!pn(d,$a,$t.n))return!1;let h=Za(r.toBytes(l),Yo(c),s),f=o.multiplyUnsafe(d).add(c.multiplyUnsafe(r.neg(h))),{x:u,y}=f.toAffine();return!(f.is0()||!Jo(y)||u!==l)}catch{return!1}}var Ce=(()=>{let n=(o=bt(48))=>hr(o,$t.n);za.utils.randomSecretKey;function r(o){let i=n(o);return{secretKey:i,publicKey:Ka(i)}}return{keygen:r,getPublicKey:Ka,sign:fu,verify:Ga,Point:Vt,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:mr,lift_x:ja,pointToBytes:Yo,numberToBytesBE:Mt,bytesToNumberBE:qe,mod:be},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var Xo=Pt;function uu(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function du(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function wr(t,e){let n=t.find(r=>r[0]===e);return n?n[1]:void 0}function Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}async function hu(t){if(!t.id||!t.pubkey||!t.sig||!t.tags||t.kind!==30470||!/^[0-9a-f]{128}$/i.test(t.sig)||!/^[0-9a-f]{64}$/i.test(t.pubkey)||!/^[0-9a-f]{64}$/i.test(t.id)||t.tags.length>100||t.content.length>65536||t.tags.some(s=>s.some(a=>a.length>1024)))return!1;let e=t.tags.map(s=>s[0]);if(!e.includes("tier")||!e.includes("age-range")||!e.includes("entity-type"))return!1;let n=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),r=new TextEncoder,o=Xo(r.encode(n));if(le(o)!==t.id.toLowerCase())return!1;try{let s=Ve(t.sig),a=Ve(t.id),c=Ve(t.pubkey);return Ce.verify(s,a,c)}catch{return!1}}function gu(t,e){if(t===e||t==="18+"&&e==="18+")return!0;let n=["0-3","4-7","8-12","13-17","18+"],r=n.indexOf(t),o=n.indexOf(e);return r===-1||o===-1?!1:e==="18+"?t==="18+":t===e}async function pu(t,e){if(e==null||!/^https:\/\//i.test(e)||!/^[0-9a-f]{64}$/i.test(t))return null;try{let n=await fetch(`${e}/status/${t}`,{signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=await n.json();if(typeof r!="object"||r===null)return null;let o=r;return{confirmed:o.confirmed===!0,method:["A","B","C","D"].includes(o.method)?o.method:null,profession:typeof o.profession=="string"?o.profession:void 0,jurisdiction:typeof o.jurisdiction=="string"?o.jurisdiction:void 0}}catch{return null}}async function yu(t,e){if(!["0-3","4-7","8-12","13-17","18+"].includes(t))return{verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"invalid-age-range"};let r={requiredAgeRange:t,relayUrl:e?.relayUrl||"wss://relay.damus.io",theme:e?.theme||"auto",timeout:e?.timeout||12e4,verifierCheckUrl:e?.verifierCheckUrl!==void 0?e.verifierCheckUrl:"https://verify.signet.forgesworn.dev",acceptUnconfirmed:e?.acceptUnconfirmed||!1,...e};r.timeout=Math.max(5e3,Math.min(r.timeout??12e4,6e5));let o=du(),i={type:"signet-verify-request",requestId:o,requiredAgeRange:r.requiredAgeRange,relayUrl:r.relayUrl,timestamp:Math.floor(Date.now()/1e3)},s=JSON.stringify(i),a=btoa(s);return new Promise(c=>{let l=document.createElement("style");l.textContent="#signet-verify-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(l);let d=r.theme==="dark"||r.theme==="auto"&&window.matchMedia("(prefers-color-scheme: dark)").matches,h=d?"#1a1a2e":"#ffffff",f=d?"#e0e0e0":"#1a1a2e",u=d?"#888":"#666",y=document.createElement("dialog");y.id="signet-verify-dialog",y.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${h};color:${f};font-family:system-ui,-apple-system,sans-serif;`,y.innerHTML=`
9
9
  <h2 style="margin:0 0 8px;font-size:1.3rem;">Verify your age with Signet</h2>
10
- <p style="margin:0 0 24px;color:${u};font-size:0.9rem;">Scan this QR code with your Signet app to prove you are ${au(t)}. No personal data is shared.</p>
10
+ <p style="margin:0 0 24px;color:${u};font-size:0.9rem;">Scan this QR code with your Signet app to prove you are ${uu(t)}. No personal data is shared.</p>
11
11
  <div id="signet-qr" style="display:flex;justify-content:center;margin-bottom:24px;"></div>
12
12
  <p style="margin:0 0 16px;color:${u};font-size:0.8rem;">Waiting for verification...</p>
13
13
  <button id="signet-cancel" style="background:none;border:1px solid ${u};color:${f};padding:10px 24px;border-radius:8px;cursor:pointer;font-size:0.9rem;">Cancel</button>
14
- `,document.body.appendChild(y),y.showModal();let m=y.querySelector("#signet-qr");if(m){let R=document.createElement("div");R.style.cssText=`width:200px;height:200px;background:${d?"#2a2a3e":"#f0f0f0"};border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:0.75rem;color:${u};word-break:break-all;padding:12px;`,R.textContent=`signet:verify:${a.slice(0,40)}...`,m.appendChild(R)}let S=new BroadcastChannel("signet-verify-"+o);y.querySelector("#signet-cancel")?.addEventListener("click",()=>{S.close(),y.close(),y.remove(),l.remove(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"cancelled"})}),S.onmessage=async R=>{let N=R.data;if(typeof N!="object"||N===null)return;let _=N;if(_.type!=="signet-verify-response"||_.requestId!==o||!_.credential||typeof _.credential!="object"||!Array.isArray(_.credential.tags))return;let M=_.credential,U=await lu(M),D=wr(M.tags,"age-range"),j=wr(M.tags,"tier"),Z=wr(M.tags,"entity-type"),L=wr(M.tags,"expires"),z=D?fu(D,r.requiredAgeRange):!1,$=await uu(M.pubkey,r.verifierCheckUrl),T=$?.confirmed??null,x=$?.method??null,g=r.acceptUnconfirmed||T===!0;y.close(),y.remove(),l.remove(),S.close();let p=j?parseInt(j,10):null,b=L?parseInt(L,10):null,E=Math.floor(Date.now()/1e3),k=b===null||!isNaN(b)&&b>E,w;U?k?z?g||(w=T===!1?"verifier-not-confirmed":"verifier-check-unavailable"):w="age-range-not-met":w="credential-expired":w="invalid-credential",c({verified:U&&k&&z&&g,ageRange:D||null,tier:p!==null&&!isNaN(p)?p:null,entityType:Z||null,credentialId:M.id,verifierPubkey:M.pubkey,verifierConfirmed:T,verifierMethod:x,issuedAt:M.created_at,expiresAt:b!==null&&!isNaN(b)?b:null,error:w})},setTimeout(()=>{y.close(),y.remove(),l.remove(),S.close(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"timeout"})},r.timeout)})}function jo(t){let e=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),n=zo(new TextEncoder().encode(e));return le(n)}async function hu(t,e){try{let n=Ut(e,t.pubkey),r=an(t.content,n),o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let i=o;if(i.kind!==13||typeof i.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(i.pubkey)||typeof i.created_at!="number"||!Array.isArray(i.tags)||typeof i.content!="string"||typeof i.id!="string"||!/^[0-9a-f]{64}$/i.test(i.id)||typeof i.sig!="string"||!/^[0-9a-f]{128}$/i.test(i.sig)||jo({pubkey:i.pubkey,created_at:i.created_at,kind:13,tags:i.tags,content:i.content})!==i.id.toLowerCase())return null;let a=Ve(i.sig),c=Ve(i.id),l=Ve(i.pubkey);if(!Ce.verify(a,c,l))return null;let d=Ut(e,i.pubkey),h=an(i.content,d),f=JSON.parse(h);if(typeof f!="object"||f===null)return null;let u=f;if(typeof u.pubkey!="string"||u.pubkey!==i.pubkey||typeof u.kind!="number"||typeof u.created_at!="number"||!Array.isArray(u.tags)||typeof u.content!="string")return null;let y=typeof u.id=="string"?u.id:jo({pubkey:u.pubkey,created_at:u.created_at,kind:u.kind,tags:u.tags,content:u.content});return{pubkey:u.pubkey,id:y,kind:u.kind,created_at:u.created_at,tags:u.tags,content:u.content}}catch{return null}}function gu(t){if(typeof t!="string")return;let e=t.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g,"").trim().slice(0,64);return e.length>0?e:void 0}async function Zo(t){if(!/^[0-9a-f]{64}$/i.test(t.requestId))throw new Error("invalid-request-id");if(!(t.sessionPrivKey instanceof Uint8Array)||t.sessionPrivKey.length!==32)throw new Error("invalid-session-privkey");if(!/^wss:\/\//i.test(t.relayUrl)&&!/^ws:\/\/(localhost|127\.0\.0\.1)([:\/]|$)/i.test(t.relayUrl))throw new Error("invalid-relay-url");if(typeof t.expectedOrigin!="string"||t.expectedOrigin.length===0)throw new Error("invalid-expected-origin");let e=le(Ce.getPublicKey(t.sessionPrivKey)),n=Math.max(5e3,Math.min(t.timeout??12e4,6e5)),r=t.requestId.toLowerCase(),o=t.expectedOrigin;return new Promise((i,s)=>{let a=`sa-${Math.random().toString(36).slice(2,12)}`,c=!1,l;try{l=new WebSocket(t.relayUrl)}catch{s(new Error("relay-error"));return}let d=f=>{if(!c){c=!0,clearTimeout(h);try{l.close()}catch{}f()}},h=setTimeout(()=>{d(()=>s(new Error("timeout")))},n);l.onopen=()=>{let f=Math.floor(Date.now()/1e3)-60;l.send(JSON.stringify(["REQ",a,{kinds:[1059],"#p":[e],since:f}]))},l.onmessage=async f=>{if(c)return;let u;try{u=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}if(!Array.isArray(u)||u[0]!=="EVENT"||u[1]!==a)return;let y=u[2];if(typeof y!="object"||y===null)return;let m=y;if(m.kind!==1059||typeof m.pubkey!="string"||typeof m.content!="string")return;let S=await hu({pubkey:m.pubkey,content:m.content},t.sessionPrivKey);if(!S||S.kind!==29999)return;let R=S.tags.find(g=>g[0]==="session");if(!R||R[1]!==r)return;let N=S.tags.find(g=>g[0]==="status");if(N?.[1]==="rejected"){d(()=>s(new Error("denied")));return}if(N?.[1]!=="approved"||Math.abs(Date.now()/1e3-S.created_at)>300)return;let M;try{let g=JSON.parse(S.content);if(typeof g!="object"||g===null)return;M=g}catch{return}if(M.type!=="signet-auth-response"||M.requestId!==r||typeof M.authEvent!="object"||M.authEvent===null)return;let U=M.authEvent;if(typeof U.id!="string"||!/^[0-9a-f]{64}$/i.test(U.id)||typeof U.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(U.pubkey)||typeof U.sig!="string"||!/^[0-9a-f]{128}$/i.test(U.sig)||U.kind!==21236||typeof U.created_at!="number"||!Array.isArray(U.tags)||typeof U.content!="string"||U.pubkey.toLowerCase()!==S.pubkey.toLowerCase()||jo({pubkey:U.pubkey,created_at:U.created_at,kind:21236,tags:U.tags,content:U.content})!==U.id.toLowerCase())return;let j=!1;try{let g=Ve(U.sig),p=Ve(U.id),b=Ve(U.pubkey);j=Ce.verify(g,p,b)}catch{j=!1}if(!j)return;let Z=U.tags,L=Z.find(g=>Array.isArray(g)&&g[0]==="challenge");if(!L||typeof L[1]!="string"||L[1].toLowerCase()!==r)return;let z=Z.find(g=>Array.isArray(g)&&g[0]==="origin");if(!z||z[1]!==o||Math.abs(Date.now()/1e3-U.created_at)>300)return;let T={id:U.id.toLowerCase(),pubkey:U.pubkey.toLowerCase(),kind:21236,created_at:U.created_at,tags:Z,content:U.content,sig:U.sig},x=gu(M.displayName);d(()=>i({pubkey:T.pubkey,authEvent:T,credential:M.credential,...x!==void 0?{displayName:x}:{},createdAt:T.created_at}))},l.onerror=()=>{d(()=>s(new Error("relay-error")))}})}typeof window<"u"&&(window.Signet={verifyAge:du,waitForAuthResponse:Zo});var Za=/^[0-9a-f]{64}$/i,pu=/^[0-9a-f]{128}$/i;function yu(t){let e=t.redirectCallback??`${t.origin}/`,n=new URLSearchParams({auth:"1",challenge:t.challenge,origin:t.origin,name:t.appName,callback:e,t:String(Math.floor(Date.now()/1e3))});return`${t.signetAppOrigin}/?${n.toString()}`}function xr(t){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};er(e);let n=yu(t);return window.location.href=n,new Promise(()=>{})}function bu(){if(typeof window>"u")return;let t=new URL(window.location.href),e=["pubkey","npub","signature","eventId","error","warnings","fromNP","display_name","t","bunker"],n=!1;for(let o of e)t.searchParams.has(o)&&(t.searchParams.delete(o),n=!0);if(!n)return;let r=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,r)}catch{}}function Ga(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search),e=t.get("error"),n=t.get("pubkey"),r=t.get("signature"),o=t.get("eventId");if(!e&&!n&&!r&&!o)return{kind:"no-callback"};let i=tr(),s=N=>(nr(),bu(),N);if(e==="denied")return s({kind:"denied"});if(!i)return s({kind:"invalid",reason:"no-pending-state"});if(i.origin!==window.location.origin)return s({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-i.createdAt>Rn)return s({kind:"invalid",reason:"pending-stale"});if(!n||!Za.test(n))return s({kind:"invalid",reason:"pubkey-malformed"});if(!r||!pu.test(r))return s({kind:"invalid",reason:"signature-malformed"});if(!o||!Za.test(o))return s({kind:"invalid",reason:"eventId-malformed"});let a,c=t.get("t");if(c&&/^\d+$/.test(c)){let N=Number(c);if(!Number.isFinite(N))return s({kind:"invalid",reason:"t-malformed"});a=N}else a=Math.floor(Date.now()/1e3),typeof console<"u"&&console.warn("signet-login: redirect callback missing `t` param \u2014 auth event created_at approximated. Server-side verification may reject. Upgrade signet-app to emit `t` in the redirect URL.");let l=n.toLowerCase(),d=r.toLowerCase(),f={id:o.toLowerCase(),pubkey:l,kind:21236,created_at:a,tags:[["challenge",i.challenge],["origin",i.origin],["app",i.appName]],content:"",sig:d},u=t.get("display_name")||void 0,y=new Ee(l,f),m={pubkey:l,method:"redirect",signer:y,authEvent:f};u&&(m.displayName=u);let S=t.get("bunker"),R;return S&&S.length>=9&&S.length<=8192&&S.slice(0,9).toLowerCase()==="bunker://"&&(R=S),s(R?{kind:"session",session:m,bunkerUri:R}:{kind:"session",session:m})}var bi=cl(Gc(),1);function yi(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ud(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Bt(t){return t==="dark"?!0:t==="light"?!1:typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function dd(t){let e=document.createElement("style");e.textContent="#signet-login-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(e);let n=Bt(t),r=n?"#1a1a2e":"#ffffff",o=n?"#e0e0e0":"#1a1a2e",i=document.createElement("dialog");return i.id="signet-login-dialog",i.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${r};color:${o};font-family:system-ui,-apple-system,sans-serif;`,document.body.appendChild(i),i.showModal(),{dialog:i,style:e}}function hd(t){try{t.dialog.close()}catch{}t.dialog.remove(),t.style.remove()}function ae(t,e=!1){return e?"background:#2c3e8f;color:white;border:0;padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;":`background:transparent;color:${t?"#e0e0e0":"#1a1a2e"};border:1px solid ${t?"#3a3a4e":"#d0d0d0"};padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;`}function gd(t,e,n){let r=Bt(n),o=r?"#888":"#666",i=cn(),s=rr();return t.dialog.innerHTML=`
15
- <h2 style="margin:0 0 8px;font-size:1.3rem;">Sign in to ${yi(e)}</h2>
14
+ `,document.body.appendChild(y),y.showModal();let m=y.querySelector("#signet-qr");if(m){let R=document.createElement("div");R.style.cssText=`width:200px;height:200px;background:${d?"#2a2a3e":"#f0f0f0"};border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:0.75rem;color:${u};word-break:break-all;padding:12px;`,R.textContent=`signet:verify:${a.slice(0,40)}...`,m.appendChild(R)}let S=new BroadcastChannel("signet-verify-"+o);y.querySelector("#signet-cancel")?.addEventListener("click",()=>{S.close(),y.close(),y.remove(),l.remove(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"cancelled"})}),S.onmessage=async R=>{let M=R.data;if(typeof M!="object"||M===null)return;let I=M;if(I.type!=="signet-verify-response"||I.requestId!==o||!I.credential||typeof I.credential!="object"||!Array.isArray(I.credential.tags))return;let _=I.credential,N=await hu(_),q=wr(_.tags,"age-range"),j=wr(_.tags,"tier"),Z=wr(_.tags,"entity-type"),L=wr(_.tags,"expires"),z=q?gu(q,r.requiredAgeRange):!1,$=await pu(_.pubkey,r.verifierCheckUrl),T=$?.confirmed??null,x=$?.method??null,g=r.acceptUnconfirmed||T===!0;y.close(),y.remove(),l.remove(),S.close();let p=j?parseInt(j,10):null,b=L?parseInt(L,10):null,E=Math.floor(Date.now()/1e3),k=b===null||!isNaN(b)&&b>E,w;N?k?z?g||(w=T===!1?"verifier-not-confirmed":"verifier-check-unavailable"):w="age-range-not-met":w="credential-expired":w="invalid-credential",c({verified:N&&k&&z&&g,ageRange:q||null,tier:p!==null&&!isNaN(p)?p:null,entityType:Z||null,credentialId:_.id,verifierPubkey:_.pubkey,verifierConfirmed:T,verifierMethod:x,issuedAt:_.created_at,expiresAt:b!==null&&!isNaN(b)?b:null,error:w})},setTimeout(()=>{y.close(),y.remove(),l.remove(),S.close(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"timeout"})},r.timeout)})}function Fo(t){let e=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),n=Xo(new TextEncoder().encode(e));return le(n)}async function bu(t,e){try{let n=Ut(e,t.pubkey),r=an(t.content,n),o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let i=o;if(i.kind!==13||typeof i.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(i.pubkey)||typeof i.created_at!="number"||!Array.isArray(i.tags)||typeof i.content!="string"||typeof i.id!="string"||!/^[0-9a-f]{64}$/i.test(i.id)||typeof i.sig!="string"||!/^[0-9a-f]{128}$/i.test(i.sig)||Fo({pubkey:i.pubkey,created_at:i.created_at,kind:13,tags:i.tags,content:i.content})!==i.id.toLowerCase())return null;let a=Ve(i.sig),c=Ve(i.id),l=Ve(i.pubkey);if(!Ce.verify(a,c,l))return null;let d=Ut(e,i.pubkey),h=an(i.content,d),f=JSON.parse(h);if(typeof f!="object"||f===null)return null;let u=f;if(typeof u.pubkey!="string"||u.pubkey!==i.pubkey||typeof u.kind!="number"||typeof u.created_at!="number"||!Array.isArray(u.tags)||typeof u.content!="string")return null;let y=typeof u.id=="string"?u.id:Fo({pubkey:u.pubkey,created_at:u.created_at,kind:u.kind,tags:u.tags,content:u.content});return{pubkey:u.pubkey,id:y,kind:u.kind,created_at:u.created_at,tags:u.tags,content:u.content}}catch{return null}}function mu(t){if(typeof t!="string")return;let e=t.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g,"").trim().slice(0,64);return e.length>0?e:void 0}async function Qo(t){if(!/^[0-9a-f]{64}$/i.test(t.requestId))throw new Error("invalid-request-id");if(!(t.sessionPrivKey instanceof Uint8Array)||t.sessionPrivKey.length!==32)throw new Error("invalid-session-privkey");if(!/^wss:\/\//i.test(t.relayUrl)&&!/^ws:\/\/(localhost|127\.0\.0\.1)([:\/]|$)/i.test(t.relayUrl))throw new Error("invalid-relay-url");if(typeof t.expectedOrigin!="string"||t.expectedOrigin.length===0)throw new Error("invalid-expected-origin");let e=le(Ce.getPublicKey(t.sessionPrivKey)),n=Math.max(5e3,Math.min(t.timeout??12e4,6e5)),r=t.requestId.toLowerCase(),o=t.expectedOrigin;return new Promise((i,s)=>{let a=`sa-${Math.random().toString(36).slice(2,12)}`,c=!1,l;try{l=new WebSocket(t.relayUrl)}catch{s(new Error("relay-error"));return}let d=f=>{if(!c){c=!0,clearTimeout(h);try{l.close()}catch{}f()}},h=setTimeout(()=>{d(()=>s(new Error("timeout")))},n);l.onopen=()=>{let f=Math.floor(Date.now()/1e3)-60;l.send(JSON.stringify(["REQ",a,{kinds:[1059],"#p":[e],since:f}]))},l.onmessage=async f=>{if(c)return;let u;try{u=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}if(!Array.isArray(u)||u[0]!=="EVENT"||u[1]!==a)return;let y=u[2];if(typeof y!="object"||y===null)return;let m=y;if(m.kind!==1059||typeof m.pubkey!="string"||typeof m.content!="string")return;let S=await bu({pubkey:m.pubkey,content:m.content},t.sessionPrivKey);if(!S||S.kind!==29999)return;let R=S.tags.find(g=>g[0]==="session");if(!R||R[1]!==r)return;let M=S.tags.find(g=>g[0]==="status");if(M?.[1]==="rejected"){d(()=>s(new Error("denied")));return}if(M?.[1]!=="approved"||Math.abs(Date.now()/1e3-S.created_at)>300)return;let _;try{let g=JSON.parse(S.content);if(typeof g!="object"||g===null)return;_=g}catch{return}if(_.type!=="signet-auth-response"||_.requestId!==r||typeof _.authEvent!="object"||_.authEvent===null)return;let N=_.authEvent;if(typeof N.id!="string"||!/^[0-9a-f]{64}$/i.test(N.id)||typeof N.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(N.pubkey)||typeof N.sig!="string"||!/^[0-9a-f]{128}$/i.test(N.sig)||N.kind!==21236||typeof N.created_at!="number"||!Array.isArray(N.tags)||typeof N.content!="string"||N.pubkey.toLowerCase()!==S.pubkey.toLowerCase()||Fo({pubkey:N.pubkey,created_at:N.created_at,kind:21236,tags:N.tags,content:N.content})!==N.id.toLowerCase())return;let j=!1;try{let g=Ve(N.sig),p=Ve(N.id),b=Ve(N.pubkey);j=Ce.verify(g,p,b)}catch{j=!1}if(!j)return;let Z=N.tags,L=Z.find(g=>Array.isArray(g)&&g[0]==="challenge");if(!L||typeof L[1]!="string"||L[1].toLowerCase()!==r)return;let z=Z.find(g=>Array.isArray(g)&&g[0]==="origin");if(!z||z[1]!==o||Math.abs(Date.now()/1e3-N.created_at)>300)return;let T={id:N.id.toLowerCase(),pubkey:N.pubkey.toLowerCase(),kind:21236,created_at:N.created_at,tags:Z,content:N.content,sig:N.sig},x=mu(_.displayName);d(()=>i({pubkey:T.pubkey,authEvent:T,credential:_.credential,...x!==void 0?{displayName:x}:{},createdAt:T.created_at}))},l.onerror=()=>{d(()=>s(new Error("relay-error")))}})}typeof window<"u"&&(window.Signet={verifyAge:yu,waitForAuthResponse:Qo});var Wa=/^[0-9a-f]{64}$/i,wu=/^[0-9a-f]{128}$/i;function xu(t){let e=t.redirectCallback??`${t.origin}/`,n=new URLSearchParams({auth:"1",challenge:t.challenge,origin:t.origin,name:t.appName,callback:e,t:String(Math.floor(Date.now()/1e3))});return`${t.signetAppOrigin}/?${n.toString()}`}function xr(t){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};er(e);let n=xu(t);return window.location.href=n,new Promise(()=>{})}function Eu(){if(typeof window>"u")return;let t=new URL(window.location.href),e=["pubkey","npub","signature","eventId","error","warnings","fromNP","display_name","t","bunker","avatar_hash","avatar_url","avatar_key"],n=!1;for(let o of e)t.searchParams.has(o)&&(t.searchParams.delete(o),n=!0);if(!n)return;let r=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,r)}catch{}}function Ya(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search),e=t.get("error"),n=t.get("pubkey"),r=t.get("signature"),o=t.get("eventId");if(!e&&!n&&!r&&!o)return{kind:"no-callback"};let i=tr(),s=q=>(nr(),Eu(),q);if(e==="denied")return s({kind:"denied"});if(!i)return s({kind:"invalid",reason:"no-pending-state"});if(i.origin!==window.location.origin)return s({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-i.createdAt>Rn)return s({kind:"invalid",reason:"pending-stale"});if(!n||!Wa.test(n))return s({kind:"invalid",reason:"pubkey-malformed"});if(!r||!wu.test(r))return s({kind:"invalid",reason:"signature-malformed"});if(!o||!Wa.test(o))return s({kind:"invalid",reason:"eventId-malformed"});let a,c=t.get("t");if(c&&/^\d+$/.test(c)){let q=Number(c);if(!Number.isFinite(q))return s({kind:"invalid",reason:"t-malformed"});a=q}else a=Math.floor(Date.now()/1e3),typeof console<"u"&&console.warn("signet-login: redirect callback missing `t` param \u2014 auth event created_at approximated. Server-side verification may reject. Upgrade signet-app to emit `t` in the redirect URL.");let l=n.toLowerCase(),d=r.toLowerCase(),h=o.toLowerCase(),f=[["challenge",i.challenge],["origin",i.origin]],u=t.get("avatar_hash"),y=t.get("avatar_url"),m=t.get("avatar_key");u&&/^[0-9a-f]{64}$/i.test(u)&&f.push(["avatar_hash",u]),y&&y.length<=500&&f.push(["avatar_url",y]),m&&/^[0-9a-f]{64}$/i.test(m)&&f.push(["avatar_key",m]);let S={id:h,pubkey:l,kind:21236,created_at:a,tags:f,content:"",sig:d},R=t.get("display_name")||void 0,M=new Ee(l,S),I={pubkey:l,method:"redirect",signer:M,authEvent:S};R&&(I.displayName=R);let _=t.get("bunker"),N;return _&&_.length>=9&&_.length<=8192&&_.slice(0,9).toLowerCase()==="bunker://"&&(N=_),s(N?{kind:"session",session:I,bunkerUri:N}:{kind:"session",session:I})}var Bi=fl(Yc(),1);function Si(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function pd(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Bt(t){return t==="dark"?!0:t==="light"?!1:typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function yd(t){let e=document.createElement("style");e.textContent="#signet-login-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(e);let n=Bt(t),r=n?"#1a1a2e":"#ffffff",o=n?"#e0e0e0":"#1a1a2e",i=document.createElement("dialog");return i.id="signet-login-dialog",i.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${r};color:${o};font-family:system-ui,-apple-system,sans-serif;`,document.body.appendChild(i),i.showModal(),{dialog:i,style:e}}function bd(t){try{t.dialog.close()}catch{}t.dialog.remove(),t.style.remove()}function ae(t,e=!1){return e?"background:#2c3e8f;color:white;border:0;padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;":`background:transparent;color:${t?"#e0e0e0":"#1a1a2e"};border:1px solid ${t?"#3a3a4e":"#d0d0d0"};padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;`}function md(t,e,n){let r=Bt(n),o=r?"#888":"#666",i=cn(),s=rr();return t.dialog.innerHTML=`
15
+ <h2 style="margin:0 0 8px;font-size:1.3rem;">Sign in to ${Si(e)}</h2>
16
16
  <p style="margin:0 0 24px;color:${o};font-size:0.9rem;">Choose how you want to sign in. Your keys never leave your control.</p>
17
17
  <div style="display:flex;flex-direction:column;">
18
18
  ${i?`<button data-choice="nip07" style="${ae(r,!0)}"><span style="font-size:1.2rem;">\u{1F310}</span><span><strong>Browser extension</strong><br><span style="font-size:0.8rem;opacity:0.8;">bark, Alby, nos2x</span></span></button>`:""}
@@ -24,7 +24,7 @@ Minimum version required to store current data is: `+i+`.
24
24
  <button data-choice="nsec" style="${ae(r)}"><span style="font-size:1.2rem;">\u26A0\uFE0F</span><span><strong>Paste private key</strong><br><span style="font-size:0.8rem;color:${o};">In-memory only \u2014 risky, last resort</span></span></button>
25
25
  </div>
26
26
  <button data-choice="cancel" style="background:transparent;color:${r?"#e0e0e0":"#1a1a2e"};border:1px solid ${r?"#3a3a4e":"#d0d0d0"};border-radius:8px;padding:12px;cursor:pointer;font-size:0.95rem;width:100%;margin-top:12px;text-align:center;">Cancel</button>
27
- `,new Promise(a=>{t.dialog.querySelectorAll("button[data-choice]").forEach(c=>{c.addEventListener("click",()=>{let l=c.dataset.choice;a(l)})})})}async function pd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#e0e0e0":"#1a1a2e";t.dialog.innerHTML=`
27
+ `,new Promise(a=>{t.dialog.querySelectorAll("button[data-choice]").forEach(c=>{c.addEventListener("click",()=>{let l=c.dataset.choice;a(l)})})})}async function wd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#e0e0e0":"#1a1a2e";t.dialog.innerHTML=`
28
28
  <h2 style="margin:0 0 8px;font-size:1.2rem;">Waiting for your extension</h2>
29
29
  <p style="margin:0 0 20px;color:${r};font-size:0.85rem;">Approve the sign-in prompt in bark, Alby, nos2x, or whichever NIP-07 extension you use. Cold-start can take a few seconds.</p>
30
30
  <div style="display:flex;align-items:center;justify-content:center;gap:14px;margin:0 0 24px;color:${o};">
@@ -36,19 +36,19 @@ Minimum version required to store current data is: `+i+`.
36
36
  <button data-action="cancel" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">Cancel</button>
37
37
  </div>
38
38
  <style>@keyframes signet-login-spin{to{transform:rotate(360deg)}}</style>
39
- `;let i=t.dialog.querySelector("#signet-login-nip07-elapsed"),s=0,a=window.setInterval(()=>{s+=1,i&&(i.textContent=`Waiting for your signer (${s}s)\u2026`)},1e3),c=new Promise(l=>{t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>l(null)),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>l(null))});try{let l=await Promise.race([ln(),c]);if(!l)return null;let d=await Promise.race([l.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]}),c]);if(!d){try{await l.close()}catch{}return null}return{pubkey:l.pubkey,authEvent:d}}catch(l){return i&&(i.textContent=`\u2717 ${l instanceof Error?l.message:String(l)}`,i.style.color="#d04848"),await Promise.race([new Promise(d=>setTimeout(d,2500)),c]),null}finally{window.clearInterval(a)}}async function yd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=Ce.utils.randomPrivateKey(),i=le(Ce.getPublicKey(o)),s=new URLSearchParams({auth:"1",challenge:e.challenge,origin:e.origin,name:e.appName,callback:e.redirectCallback??`${e.origin}/`,t:String(Math.floor(Date.now()/1e3)),relay:e.relayUrl,sessionPubkey:i}),a=`${e.signetAppOrigin}/?${s.toString()}`;t.dialog.innerHTML=`
39
+ `;let i=t.dialog.querySelector("#signet-login-nip07-elapsed"),s=0,a=window.setInterval(()=>{s+=1,i&&(i.textContent=`Waiting for your signer (${s}s)\u2026`)},1e3),c=new Promise(l=>{t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>l(null)),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>l(null))});try{let l=await Promise.race([ln(),c]);if(!l)return null;let d=await Promise.race([l.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]}),c]);if(!d){try{await l.close()}catch{}return null}return{pubkey:l.pubkey,authEvent:d}}catch(l){return i&&(i.textContent=`\u2717 ${l instanceof Error?l.message:String(l)}`,i.style.color="#d04848"),await Promise.race([new Promise(d=>setTimeout(d,2500)),c]),null}finally{window.clearInterval(a)}}async function xd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=Ce.utils.randomPrivateKey(),i=le(Ce.getPublicKey(o)),s=new URLSearchParams({auth:"1",challenge:e.challenge,origin:e.origin,name:e.appName,callback:e.redirectCallback??`${e.origin}/`,t:String(Math.floor(Date.now()/1e3)),relay:e.relayUrl,sessionPubkey:i}),a=`${e.signetAppOrigin}/?${s.toString()}`;t.dialog.innerHTML=`
40
40
  <h2 style="margin:0 0 8px;font-size:1.2rem;">Sign in with Signet</h2>
41
41
  <p style="margin:0 0 16px;color:${r};font-size:0.85rem;">Open the link on your phone, or scan the QR if rendered.</p>
42
42
  <div style="background:${n?"#0f0f1f":"#f5f5f8"};border-radius:8px;padding:16px;margin-bottom:16px;">
43
43
  <canvas id="signet-login-qr" width="200" height="200" style="display:block;width:200px;height:200px;margin:0 auto 12px;background:#ffffff;border-radius:6px;box-sizing:border-box;"></canvas>
44
- <a href="${yi(a)}" target="_blank" rel="noopener" style="display:block;color:#5b6dff;font-size:0.75rem;word-break:break-all;text-decoration:none;">${yi(a.slice(0,80))}\u2026</a>
44
+ <a href="${Si(a)}" target="_blank" rel="noopener" style="display:block;color:#5b6dff;font-size:0.75rem;word-break:break-all;text-decoration:none;">${Si(a.slice(0,80))}\u2026</a>
45
45
  </div>
46
46
  <p id="signet-login-status" style="margin:0 0 12px;color:${r};font-size:0.85rem;">Waiting for approval\u2026</p>
47
47
  <div style="display:flex;gap:8px;justify-content:space-between;">
48
48
  <button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
49
49
  <button data-action="cancel" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">Cancel</button>
50
50
  </div>
51
- `;let c=t.dialog.querySelector("#signet-login-qr");return c&&bi.default.toCanvas(c,a,{width:200,margin:1,errorCorrectionLevel:"M",color:{dark:"#0a0418",light:"#ffffff"}}).catch(()=>{}),new Promise(l=>{let d=!1,h=f=>{d||(d=!0,l(f))};t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{h(null)}),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>{h(null)}),Zo({requestId:e.challenge,relayUrl:e.relayUrl,sessionPrivKey:o,expectedOrigin:e.origin,timeout:e.timeout}).then(f=>{let u={id:f.authEvent.id,pubkey:f.authEvent.pubkey,kind:21236,created_at:f.authEvent.created_at,tags:f.authEvent.tags,content:f.authEvent.content,sig:f.authEvent.sig},y={pubkey:f.pubkey,authEvent:u};f.displayName&&(y.displayName=f.displayName),h(y)}).catch(f=>{let u=t.dialog.querySelector("#signet-login-status");u&&(u.textContent=`\u2717 ${f instanceof Error?f.message:String(f)}`,u.style.color="#d04848")})})}async function bd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#0f0f1f":"#f5f5f8",i=n?"#e0e0e0":"#1a1a2e";return t.dialog.innerHTML=`
51
+ `;let c=t.dialog.querySelector("#signet-login-qr");return c&&Bi.default.toCanvas(c,a,{width:200,margin:1,errorCorrectionLevel:"M",color:{dark:"#0a0418",light:"#ffffff"}}).catch(()=>{}),new Promise(l=>{let d=!1,h=f=>{d||(d=!0,l(f))};t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{h(null)}),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>{h(null)}),Qo({requestId:e.challenge,relayUrl:e.relayUrl,sessionPrivKey:o,expectedOrigin:e.origin,timeout:e.timeout}).then(f=>{let u={id:f.authEvent.id,pubkey:f.authEvent.pubkey,kind:21236,created_at:f.authEvent.created_at,tags:f.authEvent.tags,content:f.authEvent.content,sig:f.authEvent.sig},y={pubkey:f.pubkey,authEvent:u};f.displayName&&(y.displayName=f.displayName),h(y)}).catch(f=>{let u=t.dialog.querySelector("#signet-login-status");u&&(u.textContent=`\u2717 ${f instanceof Error?f.message:String(f)}`,u.style.color="#d04848")})})}async function Ed(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#0f0f1f":"#f5f5f8",i=n?"#e0e0e0":"#1a1a2e";return t.dialog.innerHTML=`
52
52
  <h2 style="margin:0 0 8px;font-size:1.2rem;">Paste bunker URI</h2>
53
53
  <p style="margin:0 0 16px;color:${r};font-size:0.85rem;">Connect to your NIP-46 bunker (Heartwood, nsecBunker, or any compatible signer).</p>
54
54
  <textarea id="signet-login-bunker-input" placeholder="bunker://..." rows="3" style="width:100%;background:${o};color:${i};border:1px solid ${n?"#3a3a4e":"#d0d0d0"};border-radius:8px;padding:10px;font-size:0.85rem;font-family:ui-monospace,monospace;box-sizing:border-box;resize:vertical;margin-bottom:12px;"></textarea>
@@ -57,7 +57,7 @@ Minimum version required to store current data is: `+i+`.
57
57
  <button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
58
58
  <button data-action="connect" style="${ae(n,!0)}width:auto;flex:1;padding:8px 16px;text-align:center;">Connect</button>
59
59
  </div>
60
- `,new Promise(s=>{let a=!1,c=f=>{a||(a=!0,s(f))},l=t.dialog.querySelector("#signet-login-bunker-input"),d=t.dialog.querySelector("#signet-login-bunker-status"),h=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{c(null)}),h?.addEventListener("click",async()=>{let f=l?.value.trim()??"";if(!f){d&&(d.textContent="Please paste a bunker URI.");return}d&&(d.textContent="Connecting\u2026",d.style.color=""),h.disabled=!0;try{let u=await fn({uri:f});c(u)}catch(u){d&&(d.textContent=`\u2717 ${u instanceof Error?u.message:String(u)}`,d.style.color="#d04848"),h.disabled=!1}})})}async function md(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=Ce.utils.randomPrivateKey(),i=le(Ce.getPublicKey(o)),s=le(Ce.utils.randomPrivateKey()).slice(0,32),a=Xs({clientPubkeyHex:i,relayUrl:e.relayUrl,secret:s,perms:["sign_event","nip44_encrypt","nip44_decrypt"],appName:e.appName,appUrl:e.origin});t.dialog.innerHTML=`
60
+ `,new Promise(s=>{let a=!1,c=f=>{a||(a=!0,s(f))},l=t.dialog.querySelector("#signet-login-bunker-input"),d=t.dialog.querySelector("#signet-login-bunker-status"),h=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{c(null)}),h?.addEventListener("click",async()=>{let f=l?.value.trim()??"";if(!f){d&&(d.textContent="Please paste a bunker URI.");return}d&&(d.textContent="Connecting\u2026",d.style.color=""),h.disabled=!0;try{let u=await fn({uri:f});c(u)}catch(u){d&&(d.textContent=`\u2717 ${u instanceof Error?u.message:String(u)}`,d.style.color="#d04848"),h.disabled=!1}})})}async function vd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=Ce.utils.randomPrivateKey(),i=le(Ce.getPublicKey(o)),s=le(Ce.utils.randomPrivateKey()).slice(0,32),a=Qs({clientPubkeyHex:i,relayUrl:e.relayUrl,secret:s,perms:["sign_event","nip44_encrypt","nip44_decrypt"],appName:e.appName,appUrl:e.origin});t.dialog.innerHTML=`
61
61
  <h2 style="margin:0 0 8px;font-size:1.2rem;">Connect a Nostr signer</h2>
62
62
  <p style="margin:0 0 16px;color:${r};font-size:0.85rem;">Scan or paste this into your signer (nsec.app, Amber, Keychat\u2026). The connection happens over your relay.</p>
63
63
  <div style="background:${n?"#0f0f1f":"#f5f5f8"};border-radius:8px;padding:16px;margin-bottom:16px;">
@@ -69,7 +69,7 @@ Minimum version required to store current data is: `+i+`.
69
69
  <button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
70
70
  <button data-action="cancel" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">Cancel</button>
71
71
  </div>
72
- `;let c=t.dialog.querySelector("#signet-login-nc-qr");c&&bi.default.toCanvas(c,a,{width:200,margin:1,errorCorrectionLevel:"M",color:{dark:"#0a0418",light:"#ffffff"}}).catch(()=>{});let l=t.dialog.querySelector('[data-action="copy"]');l?.addEventListener("click",()=>{navigator.clipboard?.writeText(a).then(()=>{l.textContent="Copied \u2713",window.setTimeout(()=>{l.textContent="Copy URI"},1500)})});let d=new AbortController,h=t.dialog.querySelector("#signet-login-nc-status");return new Promise(f=>{let u=!1,y=m=>{u||(u=!0,f(m))};t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{d.abort(),y(null)}),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>{d.abort(),y(null)}),Js({uri:a,clientSecretKey:o,abortSignal:d.signal}).then(m=>y(m)).catch(m=>{u||h&&(h.textContent=`\u2717 ${m instanceof Error?m.message:String(m)}`,h.style.color="#d04848")})})}async function wd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#0f0f1f":"#f5f5f8",i=n?"#e0e0e0":"#1a1a2e";return t.dialog.innerHTML=`
72
+ `;let c=t.dialog.querySelector("#signet-login-nc-qr");c&&Bi.default.toCanvas(c,a,{width:200,margin:1,errorCorrectionLevel:"M",color:{dark:"#0a0418",light:"#ffffff"}}).catch(()=>{});let l=t.dialog.querySelector('[data-action="copy"]');l?.addEventListener("click",()=>{navigator.clipboard?.writeText(a).then(()=>{l.textContent="Copied \u2713",window.setTimeout(()=>{l.textContent="Copy URI"},1500)})});let d=new AbortController,h=t.dialog.querySelector("#signet-login-nc-status");return new Promise(f=>{let u=!1,y=m=>{u||(u=!0,f(m))};t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{d.abort(),y(null)}),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>{d.abort(),y(null)}),Fs({uri:a,clientSecretKey:o,abortSignal:d.signal}).then(m=>y(m)).catch(m=>{u||h&&(h.textContent=`\u2717 ${m instanceof Error?m.message:String(m)}`,h.style.color="#d04848")})})}async function Sd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=n?"#0f0f1f":"#f5f5f8",i=n?"#e0e0e0":"#1a1a2e";return t.dialog.innerHTML=`
73
73
  <h2 style="margin:0 0 8px;font-size:1.2rem;">Paste private key</h2>
74
74
  <p style="margin:0 0 12px;color:#d04848;font-size:0.85rem;font-weight:600;">\u26A0\uFE0F Last-resort method \u2014 only paste keys you can afford to lose.</p>
75
75
  <p style="margin:0 0 16px;color:${r};font-size:0.8rem;line-height:1.4;">Held in memory for this session only. Cleared on page reload. Prefer a browser extension or bunker URI for any key with real value.</p>
@@ -79,7 +79,7 @@ Minimum version required to store current data is: `+i+`.
79
79
  <button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
80
80
  <button data-action="connect" style="${ae(n,!0)}width:auto;flex:1;padding:8px 16px;text-align:center;">Sign in</button>
81
81
  </div>
82
- `,new Promise(s=>{let a=!1,c=f=>{a||(a=!0,s(f))},l=t.dialog.querySelector("#signet-login-nsec-input"),d=t.dialog.querySelector("#signet-login-nsec-status"),h=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{l&&(l.value=""),c(null)}),h?.addEventListener("click",()=>{let f=l?.value??"";if(!f.trim()){d&&(d.textContent="Please paste an nsec.");return}try{let u=Fs(f);l&&(l.value=""),c(u)}catch(u){d&&(d.textContent=`\u2717 ${u instanceof Error?u.message:String(u)}`,d.style.color="#d04848")}})})}function xd(t){let e=t.challenge??ud();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("challenge-must-be-64-hex");let n=typeof window<"u"?window.location.origin:"http://localhost",r=Math.max(5e3,Math.min(t.timeout??ze.timeout,6e5)),o={appName:t.appName,challenge:e.toLowerCase(),origin:n,relayUrl:t.relayUrl??ze.relayUrl,theme:t.theme??ze.theme,timeout:r,signetAppOrigin:t.signetAppOrigin??ze.signetAppOrigin};return t.preferredMethod!==void 0&&(o.preferredMethod=t.preferredMethod),t.redirectCallback!==void 0&&(o.redirectCallback=t.redirectCallback),o}async function Wc(t){if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");let e=xd(t),n=dd(e.theme),r=!1,o=new Promise(i=>{n.dialog.addEventListener("cancel",()=>{r=!0,i(null)})});try{for(;;){let i=e.preferredMethod?e.preferredMethod:await Promise.race([gd(n,e.appName,e.theme),o]);if(r||i===null||i==="cancel")return null;if(i==="nip07"){let s=await Promise.race([pd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await ln();return{pubkey:s.pubkey,method:"nip07",signer:a,authEvent:s.authEvent}}if(i==="redirect")return await xr({appName:e.appName,challenge:e.challenge,origin:e.origin,signetAppOrigin:e.signetAppOrigin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="amber")return await oa({appName:e.appName,challenge:e.challenge,origin:e.origin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="qr"){let s=await Promise.race([yd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=new Ee(s.pubkey,s.authEvent),c={pubkey:s.pubkey,method:"redirect",signer:a,authEvent:s.authEvent};return s.displayName&&(c.displayName=s.displayName),c}if(i==="bunker"){let s=await Promise.race([bd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nostrconnect"){let s=await Promise.race([md(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nsec"){let s=await Promise.race([wd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"nsec",signer:s,authEvent:a}}}}finally{hd(n)}}function Yc(t){let e={};typeof window<"u"&&new URLSearchParams(window.location.search).forEach((o,i)=>{e[i]=o});let n=typeof window<"u"&&!!window.opener&&window.opener!==window;if(n){try{window.opener.postMessage({type:"signet-login-callback",params:e},"*")}catch{}if(t?.closeAfterPost??!0)try{window.close()}catch{}}return{params:e,isPopup:n}}async function Jc(t){if(t.mode==="redirect"){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let n=t.challenge??Ed();if(!/^[0-9a-f]{64}$/i.test(n))throw new Error("challenge-must-be-64-hex");if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");return xr({appName:t.appName,challenge:n.toLowerCase(),origin:window.location.origin,signetAppOrigin:t.signetAppOrigin??ze.signetAppOrigin,...t.redirectCallback!==void 0?{redirectCallback:t.redirectCallback}:{}})}let e=await Wc(t);return e?(t.persist!==!1&&Nr(e),e):null}function Ed(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}async function Xc(t){let e=ea();if(!e)return null;let n;try{n=JSON.parse(e.authEventJson)}catch{return He(),null}if(e.method==="nip07"){if(!cn()){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}try{let i=await ln();return i.pubkey!==e.pubkey?(He(),null):{pubkey:e.pubkey,method:"nip07",signer:i,authEvent:n}}catch{return He(),null}}if(e.method==="bunker"){if(t?.reconnectBunker===!1){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}if(!e.bunkerUri||!e.bunkerClientSkHex)return He(),null;try{let i=na(e.bunkerClientSkHex),s=await fn({uri:e.bunkerUri,clientSecretKey:i});return s.pubkey!==e.pubkey?(await s.close(),He(),null):{pubkey:e.pubkey,method:"bunker",signer:s,authEvent:n}}catch{return He(),null}}let r=new Ee(e.pubkey,n),o={pubkey:e.pubkey,method:e.method,signer:r,authEvent:n};return e.displayName&&(o.displayName=e.displayName),o}var Fc=Yc;async function Qc(){let t=ia();if(t.kind==="session")return Nr(t.session),t;if(t.kind!=="no-callback")return t;let e=Ga();if(e.kind!=="session")return e;if(e.bunkerUri)try{let n=await fn({uri:e.bunkerUri});if(n.pubkey.toLowerCase()===e.session.pubkey.toLowerCase()){let r={pubkey:e.session.pubkey,method:"bunker",signer:n,authEvent:e.session.authEvent};return e.session.displayName&&(r.displayName=e.session.displayName),Nr(r),{kind:"session",session:r}}try{await n.close()}catch{}}catch{}return Nr(e.session),e}async function el(t){if(t)try{await t.signer.close()}catch{}He()}function Nr(t){if(t.method==="nsec")return;let e={pubkey:t.pubkey,method:t.method,authEventJson:JSON.stringify(t.authEvent)};if(t.method==="bunker"){let n=t.signer;n.bunkerUri&&n.clientSecretKey instanceof Uint8Array&&(e.bunkerUri=n.bunkerUri,e.bunkerClientSkHex=ta(n.clientSecretKey))}t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.displayName!==void 0&&(e.displayName=t.displayName),Qs(e)}if(typeof window<"u"){let e=window.Signet??{};Object.assign(e,{login:Jc,restoreSession:Xc,logout:el,handleCallback:Fc,handleRedirectCallback:Qc}),window.Signet=e}return ll(vd);})();
82
+ `,new Promise(s=>{let a=!1,c=f=>{a||(a=!0,s(f))},l=t.dialog.querySelector("#signet-login-nsec-input"),d=t.dialog.querySelector("#signet-login-nsec-status"),h=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{l&&(l.value=""),c(null)}),h?.addEventListener("click",()=>{let f=l?.value??"";if(!f.trim()){d&&(d.textContent="Please paste an nsec.");return}try{let u=ea(f);l&&(l.value=""),c(u)}catch(u){d&&(d.textContent=`\u2717 ${u instanceof Error?u.message:String(u)}`,d.style.color="#d04848")}})})}function Bd(t){let e=t.challenge??pd();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("challenge-must-be-64-hex");let n=typeof window<"u"?window.location.origin:"http://localhost",r=Math.max(5e3,Math.min(t.timeout??ze.timeout,6e5)),o={appName:t.appName,challenge:e.toLowerCase(),origin:n,relayUrl:t.relayUrl??ze.relayUrl,theme:t.theme??ze.theme,timeout:r,signetAppOrigin:t.signetAppOrigin??ze.signetAppOrigin};return t.preferredMethod!==void 0&&(o.preferredMethod=t.preferredMethod),t.redirectCallback!==void 0&&(o.redirectCallback=t.redirectCallback),o}async function Jc(t){if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");let e=Bd(t),n=yd(e.theme),r=!1,o=new Promise(i=>{n.dialog.addEventListener("cancel",()=>{r=!0,i(null)})});try{for(;;){let i=e.preferredMethod?e.preferredMethod:await Promise.race([md(n,e.appName,e.theme),o]);if(r||i===null||i==="cancel")return null;if(i==="nip07"){let s=await Promise.race([wd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await ln();return{pubkey:s.pubkey,method:"nip07",signer:a,authEvent:s.authEvent}}if(i==="redirect")return await xr({appName:e.appName,challenge:e.challenge,origin:e.origin,signetAppOrigin:e.signetAppOrigin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="amber")return await sa({appName:e.appName,challenge:e.challenge,origin:e.origin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="qr"){let s=await Promise.race([xd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=new Ee(s.pubkey,s.authEvent),c={pubkey:s.pubkey,method:"redirect",signer:a,authEvent:s.authEvent};return s.displayName&&(c.displayName=s.displayName),c}if(i==="bunker"){let s=await Promise.race([Ed(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nostrconnect"){let s=await Promise.race([vd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nsec"){let s=await Promise.race([Sd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"nsec",signer:s,authEvent:a}}}}finally{bd(n)}}function Xc(t){let e={};typeof window<"u"&&new URLSearchParams(window.location.search).forEach((o,i)=>{e[i]=o});let n=typeof window<"u"&&!!window.opener&&window.opener!==window;if(n){try{window.opener.postMessage({type:"signet-login-callback",params:e},"*")}catch{}if(t?.closeAfterPost??!0)try{window.close()}catch{}}return{params:e,isPopup:n}}async function Fc(t){if(t.mode==="redirect"){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let n=t.challenge??kd();if(!/^[0-9a-f]{64}$/i.test(n))throw new Error("challenge-must-be-64-hex");if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");return xr({appName:t.appName,challenge:n.toLowerCase(),origin:window.location.origin,signetAppOrigin:t.signetAppOrigin??ze.signetAppOrigin,...t.redirectCallback!==void 0?{redirectCallback:t.redirectCallback}:{}})}let e=await Jc(t);return e?(t.persist!==!1&&Nr(e),e):null}function kd(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}async function Qc(t){let e=na();if(!e)return null;let n;try{n=JSON.parse(e.authEventJson)}catch{return He(),null}if(e.method==="nip07"){if(!cn()){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}try{let i=await ln();return i.pubkey!==e.pubkey?(He(),null):{pubkey:e.pubkey,method:"nip07",signer:i,authEvent:n}}catch{return He(),null}}if(e.method==="bunker"){if(t?.reconnectBunker===!1){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}if(!e.bunkerUri||!e.bunkerClientSkHex)return He(),null;try{let i=oa(e.bunkerClientSkHex),s=await fn({uri:e.bunkerUri,clientSecretKey:i});return s.pubkey!==e.pubkey?(await s.close(),He(),null):{pubkey:e.pubkey,method:"bunker",signer:s,authEvent:n}}catch{return He(),null}}let r=new Ee(e.pubkey,n),o={pubkey:e.pubkey,method:e.method,signer:r,authEvent:n};return e.displayName&&(o.displayName=e.displayName),o}var el=Xc;async function tl(){let t=aa();if(t.kind==="session")return Nr(t.session),t;if(t.kind!=="no-callback")return t;let e=Ya();if(e.kind!=="session")return e;if(e.bunkerUri)try{let n=await fn({uri:e.bunkerUri});if(n.pubkey.toLowerCase()===e.session.pubkey.toLowerCase()){let r={pubkey:e.session.pubkey,method:"bunker",signer:n,authEvent:e.session.authEvent};return e.session.displayName&&(r.displayName=e.session.displayName),Nr(r),{kind:"session",session:r}}try{await n.close()}catch{}}catch{}return Nr(e.session),e}async function nl(t){if(t)try{await t.signer.close()}catch{}He()}function Nr(t){if(t.method==="nsec")return;let e={pubkey:t.pubkey,method:t.method,authEventJson:JSON.stringify(t.authEvent)};if(t.method==="bunker"){let n=t.signer;n.bunkerUri&&n.clientSecretKey instanceof Uint8Array&&(e.bunkerUri=n.bunkerUri,e.bunkerClientSkHex=ra(n.clientSecretKey))}t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.displayName!==void 0&&(e.displayName=t.displayName),ta(e)}if(typeof window<"u"){let e=window.Signet??{};Object.assign(e,{login:Fc,restoreSession:Qc,logout:nl,handleCallback:el,handleRedirectCallback:tl}),window.Signet=e}return ul(Ad);})();
83
83
  /*! Bundled license information:
84
84
 
85
85
  @noble/hashes/utils.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "signet-login",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "description": "Sign in with Signet — drop-in login SDK for Nostr-aware websites. NIP-07, bunker URI, and Signet redirect/QR in one unified API.",
5
5
  "type": "module",
6
6
  "main": "./dist/signet-login.js",