@enbox/browser 0.3.49 → 0.3.51

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.
Files changed (33) hide show
  1. package/dist/browser.mjs +39 -14
  2. package/dist/browser.mjs.map +3 -3
  3. package/dist/esm/dweb-connect-client.js +64 -9
  4. package/dist/esm/dweb-connect-client.js.map +1 -1
  5. package/dist/esm/dweb-connect-messages.js +7 -1
  6. package/dist/esm/dweb-connect-messages.js.map +1 -1
  7. package/dist/esm/dweb-connect-wallet.js +48 -2
  8. package/dist/esm/dweb-connect-wallet.js.map +1 -1
  9. package/dist/esm/index.js +1 -1
  10. package/dist/esm/index.js.map +1 -1
  11. package/dist/esm/relay-connect-runner.js +35 -2
  12. package/dist/esm/relay-connect-runner.js.map +1 -1
  13. package/dist/esm/ui/connect-modal.js +171 -51
  14. package/dist/esm/ui/connect-modal.js.map +1 -1
  15. package/dist/types/dweb-connect-client.d.ts +9 -0
  16. package/dist/types/dweb-connect-client.d.ts.map +1 -1
  17. package/dist/types/dweb-connect-messages.d.ts +14 -1
  18. package/dist/types/dweb-connect-messages.d.ts.map +1 -1
  19. package/dist/types/dweb-connect-wallet.d.ts +23 -1
  20. package/dist/types/dweb-connect-wallet.d.ts.map +1 -1
  21. package/dist/types/index.d.ts +2 -2
  22. package/dist/types/index.d.ts.map +1 -1
  23. package/dist/types/relay-connect-runner.d.ts +11 -1
  24. package/dist/types/relay-connect-runner.d.ts.map +1 -1
  25. package/dist/types/ui/connect-modal.d.ts +8 -7
  26. package/dist/types/ui/connect-modal.d.ts.map +1 -1
  27. package/package.json +6 -6
  28. package/src/dweb-connect-client.ts +61 -7
  29. package/src/dweb-connect-messages.ts +16 -1
  30. package/src/dweb-connect-wallet.ts +50 -1
  31. package/src/index.ts +2 -0
  32. package/src/relay-connect-runner.ts +42 -2
  33. package/src/ui/connect-modal.ts +196 -61
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import{AuthManager as Mo,AuthSession as To,normalizeProtocolRequests as So,WalletConnect as Wo}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as No,ConnectProvider as Oo}from"@enbox/connect";import{DidDht as qt,DidWeb as It,UniversalResolver as it}from"@enbox/dids";function ne(e){let t=e.indexOf("://dweb/");if(t===-1)return null;let n=e.slice(0,t);if(n!=="http"&&n!=="https")return null;let r=e.slice(t+8);if(r.length===0)return null;let o=r.indexOf("/");return o===-1?[r,""]:o===0?null:[r.slice(0,o),r.slice(o+1)]}var Re=new it({didResolvers:[qt,It]}),at=/^http:/,ge=/\/$/,st="drl";async function lt(e){let{didDocument:t}=await Re.resolve(e),n=t?.service?.find(r=>r.type==="DecentralizedWebNode")?.serviceEndpoint;return n?(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.startsWith("http")):[]}async function ct(){if(!(typeof caches>"u"))return caches.open(st)}async function Bt(e,t,n,r){let o=e.request.url.replace(at,"https:").replace(ge,""),i=await ct(),s=await i?.match(o);if(s){if(!navigator.onLine)return s;let a=await r?.onCacheCheck?.(e,o);if(a){let d=s.headers.get("dwn-cache-time");if(d&&Date.now()<Number(d)+(Number(a.ttl)||0))return s}}try{if(n)return await Ht(e,t,o,n,i,r);{let a=await Re.resolve(t);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}}catch(a){return a instanceof Response?a:(console.log(`Error in DID URL fetch: ${a}`),new Response("DID URL fetch error",{status:500}))}}async function Ht(e,t,n,r,o,i){let s=await lt(t);if(!s?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let a;for(let d of s)try{let p=`${d.replace(ge,"")}/${t}/${r}`,u=await fetch(p,{headers:e.request.headers});if(u.ok)return await i?.onCacheCheck?.(e,n)&&o&&jt(n,p,u,o),u;console.log(`DWN endpoint error: ${u.status}`),a=new Response("DWeb Node request failed",{status:u.status})}catch(p){console.log(`DWN endpoint error: ${p}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function jt(e,t,n,r){try{let o=n.clone(),i=new Headers(o.headers);i.append("dwn-cache-time",Date.now().toString()),i.append("dwn-composed-url",t);let s=new Response(o.body,{headers:i});await r.put(e,s)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function Kt(e={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let t=self;t.skipWaiting(),t.addEventListener("activate",n=>{n.waitUntil(t.clients.claim())}),t.addEventListener("fetch",n=>{let r=ne(n.request.url);r&&n.respondWith(Bt(n,r[0],r[1],e))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let n=e.path||document?.currentScript?.src||import.meta.url;n&&navigator.serviceWorker.register(n,{type:"module"}).catch(r=>{console.error("DWeb networking feature installation failed: ",r)})}}else throw new Error("DWeb networking features are not available for install in this environment")}catch(t){console.error("Error in installing networking features:",t)}}var dt=`
1
+ import{Enbox as qo,defineProtocol as Io,repository as Ho}from"@enbox/api";import{AuthManager as jo,AuthSession as $o,normalizeProtocolRequests as Ko,WalletConnect as zo}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as Yo,ConnectProvider as Fo}from"@enbox/connect";import{DidDht as Qt,DidWeb as Jt,UniversalResolver as ut}from"@enbox/dids";function oe(e){let t=e.indexOf("://dweb/");if(t===-1)return null;let n=e.slice(0,t);if(n!=="http"&&n!=="https")return null;let r=e.slice(t+8);if(r.length===0)return null;let o=r.indexOf("/");return o===-1?[r,""]:o===0?null:[r.slice(0,o),r.slice(o+1)]}var Ne=new ut({didResolvers:[Qt,Jt]}),ft=/^http:/,ye=/\/$/,mt="drl";async function ht(e){let{didDocument:t}=await Ne.resolve(e),n=t?.service?.find(r=>r.type==="DecentralizedWebNode")?.serviceEndpoint;return n?(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.startsWith("http")):[]}async function gt(){if(!(typeof caches>"u"))return caches.open(mt)}async function Xt(e,t,n,r){let o=e.request.url.replace(ft,"https:").replace(ye,""),i=await gt(),s=await i?.match(o);if(s){if(!navigator.onLine)return s;let a=await r?.onCacheCheck?.(e,o);if(a){let d=s.headers.get("dwn-cache-time");if(d&&Date.now()<Number(d)+(Number(a.ttl)||0))return s}}try{if(n)return await Vt(e,t,o,n,i,r);{let a=await Ne.resolve(t);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}}catch(a){return a instanceof Response?a:(console.log(`Error in DID URL fetch: ${a}`),new Response("DID URL fetch error",{status:500}))}}async function Vt(e,t,n,r,o,i){let s=await ht(t);if(!s?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let a;for(let d of s)try{let p=`${d.replace(ye,"")}/${t}/${r}`,u=await fetch(p,{headers:e.request.headers});if(u.ok)return await i?.onCacheCheck?.(e,n)&&o&&Zt(n,p,u,o),u;console.log(`DWN endpoint error: ${u.status}`),a=new Response("DWeb Node request failed",{status:u.status})}catch(p){console.log(`DWN endpoint error: ${p}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function Zt(e,t,n,r){try{let o=n.clone(),i=new Headers(o.headers);i.append("dwn-cache-time",Date.now().toString()),i.append("dwn-composed-url",t);let s=new Response(o.body,{headers:i});await r.put(e,s)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function en(e={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let t=self;t.skipWaiting(),t.addEventListener("activate",n=>{n.waitUntil(t.clients.claim())}),t.addEventListener("fetch",n=>{let r=oe(n.request.url);r&&n.respondWith(Xt(n,r[0],r[1],e))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let n=e.path||document?.currentScript?.src||import.meta.url;n&&navigator.serviceWorker.register(n,{type:"module"}).catch(r=>{console.error("DWeb networking feature installation failed: ",r)})}}else throw new Error("DWeb networking features are not available for install in this environment")}catch(t){console.error("Error in installing networking features:",t)}}var wt=`
2
2
  .drl-loading-overlay {
3
3
  position: fixed;
4
4
  inset: 0;
@@ -103,7 +103,7 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
103
103
  opacity: 0;
104
104
  }
105
105
  }
106
- `,zt=`
106
+ `,tn=`
107
107
  <!DOCTYPE html>
108
108
  <html lang='en'>
109
109
  <head>
@@ -119,7 +119,7 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
119
119
  font-family: Arial, sans-serif;
120
120
  text-align: center;
121
121
  }
122
- ${dt}
122
+ ${wt}
123
123
  </style>
124
124
  </head>
125
125
  <body>
@@ -132,8 +132,8 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
132
132
  </div>
133
133
  </body>
134
134
  </html>
135
- `,we=!1,K=null,oe=null;function rt(){we||(oe=document.createElement("style"),oe.innerHTML=`
136
- ${dt}
135
+ `,Ee=!1,z=null,re=null;function pt(){Ee||(re=document.createElement("style"),re.innerHTML=`
136
+ ${wt}
137
137
 
138
138
  .drl-loading-overlay {
139
139
  opacity: 0;
@@ -145,13 +145,13 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
145
145
  opacity: 1;
146
146
  pointer-events: all;
147
147
  }
148
- `,document.head.append(oe),K=document.createElement("div"),K.classList.add("drl-loading-overlay"),K.innerHTML=`
148
+ `,document.head.append(re),z=document.createElement("div"),z.classList.add("drl-loading-overlay"),z.innerHTML=`
149
149
  <div class='drl-loading-spinner'>
150
150
  <div></div>
151
151
  Loading DRL
152
152
  </div>
153
153
  <span tabindex='0'></span>
154
- `,K.lastElementChild.addEventListener("click",Me),document.body.prepend(K),we=!0)}function $t(){we&&(oe?.remove(),oe=null,K?.remove(),K=null,we=!1)}function Me(){document.documentElement.removeAttribute("drl-link-loading"),he=null}var he=null,ve=!1,re=null,ie=null;function Gt(){ve||(re=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=ne(n);if(r){let o=r[0],i=r[1],s=t.target==="_blank";e.preventDefault();try{let a=null;s?(a=window.open("","_blank"),a&&a.document.write(zt)):(he=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await lt(o);if(!d.length)throw new Error("no valid DWN endpoints found");let p=`${d[0].replace(ge,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=p):he===i&&(window.location.href=p)}catch{throw he===i&&Me(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},ie=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(Y(),t?.src&&ne(t.src)){z=t,t.__src__=t.src;let n=t.src.replace(at,"https:").replace(ge,""),o=await(await ct())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",Y,{once:!0})}}else t===z&&Y()},document.addEventListener("click",re),document.addEventListener("pointercancel",Y),document.addEventListener("pointerdown",ie),ve=!0)}function Yt(){ve&&(re&&(document.removeEventListener("click",re),re=null),ie&&(document.removeEventListener("pointerdown",ie),ie=null),document.removeEventListener("pointercancel",Y),Y(),Me(),ve=!1)}var z=null;async function Y(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),z&&(z.src=z.__src__,delete z.__src__,z=null)}function Gn(e={}){e.didResolvers&&(Re=new it({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&Kt(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",rt,{once:!0}):rt()),e.links!==!1&&Gt())}function Yn(){typeof window<"u"&&typeof window.document<"u"&&(Yt(),$t())}async function Fn(){return typeof caches>"u"?!1:caches.delete(st)}import{ConnectClient as xn}from"@enbox/connect";function ae(e){let t=document.createElement("span");t.className="wallet-icon";let n=document.createElement("span");n.className="wallet-badge",n.textContent=e.name.charAt(0).toUpperCase(),t.appendChild(n);let r=Ft(e);if(r.length===0)return t;let o=document.createElement("img");o.className="wallet-img",o.alt="",o.width=28,o.height=28;let i=0;return o.addEventListener("error",()=>{i+=1,i<r.length?o.src=r[i]:o.remove()}),o.src=r[i],t.appendChild(o),t}function Ft(e){if(e.icon!==void 0)return[e.icon];let t;try{t=new URL(e.url).origin}catch{return[]}return[`${t}/favicon.svg`,`${t}/favicon.ico`,`${t}/favicon.png`]}import{assertX25519PublicJwk as Jt,CONNECT_DENIED_TOKEN as Qt,ConnectClient as Xt}from"@enbox/connect";var Te="/dweb-connect",se="enbox-connect-loaded",le="enbox-connect-request",ce="enbox-connect-response";function be(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var Vt=3e5,Zt=500,en="enbox-dweb-connect",tn="width=500,height=700,menubar=no,toolbar=no,location=no,status=no";function nn(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var $=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},F=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;nn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??Vt;let n=new URL(Te,t.walletUrl).toString(),r=window.open(n,en,tn);if(!r)throw new Error("[@enbox/browser] Popup blocked. Allow popups for this site to connect to a wallet.");this._popup=r,this._walletEpkPromise=new Promise((o,i)=>{this._resolveWalletEpk=o,this._rejectWalletEpk=i}),this._responsePromise=new Promise((o,i)=>{this._resolveResponse=o,this._rejectResponse=i}),this._responsePromise.catch(()=>{}),this._messageListener=o=>{this.onMessage(o)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.fail(new Error("[@enbox/browser] DWeb Connect timed out waiting for wallet response."))},this._timeoutMs),this._closedPollId=setInterval(()=>{this.onClosedPoll()},Zt)}async requestProfile(t){return{encryption:{mode:"ecdh-es",walletEpk:await this._walletEpkPromise,walletOrigin:this._walletOrigin},reply:{mode:"post_message"},state:t}}async deliverRequest(t){this._popup.postMessage({type:le,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}onMessage(t){let n=be(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===se){this.onLoadedBeacon(n);return}n.type===ce&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{Jt(t.walletEpk),n=t.walletEpk}catch{this.fail(new Error("[@enbox/browser] Wallet loaded beacon did not carry a valid X25519 public key."));return}if(t.walletOrigin!==this._walletOrigin){this.fail(new Error("[@enbox/browser] Wallet loaded beacon origin does not match the configured wallet origin."));return}this._walletEpkReceived=!0,this._resolveWalletEpk?.(n)}onResponseMessage(t){if(!this._settled){if(typeof t.payload!="string"){this.fail(new Error("[@enbox/browser] Wallet response message did not carry a ciphertext payload."));return}this._settled=!0,this.cleanup(),this._rejectWalletEpk?.(new Error("[@enbox/browser] Wallet responded before the handshake was established.")),this._resolveResponse?.(t.payload)}}onClosedPoll(){if(!(this._settled||this._popup.closed!==!0)){if(!this._walletEpkReceived){this.fail(new $);return}this._settled=!0,this.cleanup(),this._resolveResponse?.(Qt)}}fail(t){if(!this._settled){this._settled=!0,this.cleanup();try{this._popup.close()}catch{}this._rejectWalletEpk?.(t),this._rejectResponse?.(t)}}cleanup(){clearTimeout(this._timeoutId),clearInterval(this._closedPollId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}};function ye(){let e=Intl.DateTimeFormat().resolvedOptions(),t=Array.isArray(globalThis.navigator.languages)?globalThis.navigator.languages.filter(n=>typeof n=="string"&&n.length>0):void 0;return{origin:globalThis.location.origin,userAgent:globalThis.navigator.userAgent,platform:globalThis.navigator.platform,language:globalThis.navigator.language,...t&&t.length>0?{languages:t}:{},...e.timeZone?{timezone:e.timeZone}:{}}}async function on(e){let t=new F({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new Xt({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:ye(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof $)return;throw r}}var ft=[-1,10,16,26,18,24,16,18,22,22,26],mt=[-1,1,1,1,2,2,4,4,4,5,5],ht=[-1,26,44,70,100,134,172,196,242,292,346],rn=0,pt=10;function ut(e){return ht[e]-ft[e]*mt[e]}function De(e,t){let n=new TextEncoder().encode(e),r=0;for(let f=1;f<=pt;f++){let h=ut(f)*8;if(4+(f<=9?8:16)+n.length*8<=h){r=f;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${pt}-M capacity).`);let o=[],i=(f,h)=>{for(let P=h-1;P>=0;P--)o.push(f>>>P&1)};i(4,4),i(n.length,r<=9?8:16);for(let f of n)i(f,8);let s=ut(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let f=0;o.length<s;f++)i(a[f%2],8);let d=new Uint8Array(s/8);for(let f=0;f<o.length;f++)d[f>>3]|=o[f]<<7-(f&7);let p=an(d,r),u=17+4*r,v=Array.from({length:u},()=>new Array(u).fill(!1)),R=Array.from({length:u},()=>new Array(u).fill(!1));dn(v,R,r),fn(v,R,p);let C=t??-1;if(C===-1){let f=1/0;for(let h=0;h<8;h++){We(v,R,h),Oe(v,R,h);let P=mn(v);P<f&&(f=P,C=h),We(v,R,h)}}return We(v,R,C),Oe(v,R,C),{size:u,modules:v,version:r,mask:C}}function an(e,t){let n=mt[t],r=ft[t],o=ht[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],p=sn(r),u=0;for(let f=0;f<n;f++){let h=s-r+(f<i?0:1),P=e.slice(u,u+h);u+=h,a.push(P),d.push(ln(P,p))}let v=new Uint8Array(o),R=0,C=s-r+1;for(let f=0;f<C;f++)for(let h=0;h<n;h++)f<a[h].length&&(v[R++]=a[h][f]);for(let f=0;f<r;f++)for(let h=0;h<n;h++)v[R++]=d[h][f];return v}function Ne(e,t){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n&255}function sn(e){let t=new Uint8Array(e);t[e-1]=1;let n=1;for(let r=0;r<e;r++){for(let o=0;o<e;o++)t[o]=Ne(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Ne(n,2)}return t}function ln(e,t){let n=new Uint8Array(t.length);for(let r of e){let o=r^n[0];n.copyWithin(0,1),n[n.length-1]=0;for(let i=0;i<t.length;i++)n[i]^=Ne(t[i],o)}return n}var cn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function T(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function dn(e,t,n){let r=e.length;for(let i=0;i<r;i++)T(e,t,6,i,i%2===0),T(e,t,i,6,i%2===0);Se(e,t,3,3),Se(e,t,r-4,3),Se(e,t,3,r-4);let o=cn[n];for(let i=0;i<o.length;i++)for(let s=0;s<o.length;s++)i===0&&s===0||i===0&&s===o.length-1||i===o.length-1&&s===0||pn(e,t,o[i],o[s]);Oe(e,t,0),T(e,t,8,r-8,!0),n>=7&&un(e,t,n)}function Se(e,t,n,r){let o=e.length;for(let i=-4;i<=4;i++)for(let s=-4;s<=4;s++){let a=n+s,d=r+i;if(a<0||a>=o||d<0||d>=o)continue;let p=Math.max(Math.abs(s),Math.abs(i));T(e,t,a,d,p!==2&&p!==4)}}function pn(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)T(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function Oe(e,t,n){let r=e.length,o=rn<<3|n,i=o;for(let a=0;a<10;a++)i=i<<1^(i>>>9)*1335;let s=(o<<10|i)^21522;for(let a=0;a<=5;a++)T(e,t,8,a,(s>>>a&1)!==0);T(e,t,8,7,(s>>>6&1)!==0),T(e,t,8,8,(s>>>7&1)!==0),T(e,t,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)T(e,t,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)T(e,t,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)T(e,t,8,r-15+a,(s>>>a&1)!==0)}function un(e,t,n){let r=e.length,o=n;for(let s=0;s<12;s++)o=o<<1^(o>>>11)*7973;let i=n<<12|o;for(let s=0;s<18;s++){let a=(i>>>s&1)!==0,d=r-11+s%3,p=Math.floor(s/3);T(e,t,d,p,a),T(e,t,p,d,a)}}function fn(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){i===6&&(i=5);for(let s=0;s<r;s++)for(let a=0;a<2;a++){let d=i-a,u=(i+1&2)===0?r-1-s:s;!t[u][d]&&o<n.length*8&&(e[u][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function We(e,t,n){let r=e.length;for(let o=0;o<r;o++)for(let i=0;i<r;i++){if(t[o][i])continue;let s;switch(n){case 0:s=(i+o)%2===0;break;case 1:s=o%2===0;break;case 2:s=i%3===0;break;case 3:s=(i+o)%3===0;break;case 4:s=(Math.floor(i/3)+Math.floor(o/2))%2===0;break;case 5:s=i*o%2+i*o%3===0;break;case 6:s=(i*o%2+i*o%3)%2===0;break;default:s=((i+o)%2+i*o%3)%2===0;break}s&&(e[o][i]=!e[o][i])}}function mn(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[a][u]!==d?(d=e[a][u],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[u][a]!==d?(d=e[u][a],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let p=e[a][d];p===e[a][d+1]&&p===e[a+1][d]&&p===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((C,f)=>a[d+f]===C))return 0;let v=d>=4&&a.slice(d-4,d).every(C=>!C),R=d+11<=a.length&&a.slice(d+7,d+11).every(C=>!C);return(v?40:0)+(R?40:0)};for(let a=0;a<t;a++){let d=e[a],p=e.map(u=>u[a]);for(let u=0;u+7<=t;u++)n+=r(d,u),n+=r(p,u)}let o=0;for(let a of e)for(let d of a)d&&o++;let i=t*t,s=Math.ceil(Math.abs(o*20-i*10)/i)-1;return n+=s*10,n}var Le="http://www.w3.org/2000/svg";function Ae(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let u=0;u<e.size;u++)for(let v=0;v<e.size;v++)e.modules[u][v]&&(s+=`M${v+o} ${u+o}h1v1h-1z`);let a=document.createElementNS(Le,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(Le,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let p=document.createElementNS(Le,"path");return p.setAttribute("d",s),p.setAttribute("fill",n),a.appendChild(p),a}var gt="/.well-known/enbox-connect";async function xe(e){try{let t=new URL(gt,e).toString(),n=await fetch(t,{signal:AbortSignal.timeout(6e3)});if(!n.ok)return;let r=await n.json();return typeof r?.connectServerUrl!="string"?void 0:{connectServerUrl:r.connectServerUrl}}catch{return}}async function Ue(e){return await xe(e)!==void 0}import{DidJwk as hn}from"@enbox/dids";import{X25519 as gn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as wn,openResponse as vn,randomToken as wt,RelayClientTransport as bn,sealRequest as yn}from"@enbox/connect";var qe=6,J=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};async function Ie(e){let n=(e.createTransport??(h=>new bn(h)))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed}),r=await hn.create(),o=await gn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=wt(),a=wt(),d=await n.requestProfile(a),p={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:a,responseKey:i,reply:d.reply},u=await yn({request:p,signer:r,encryption:d.encryption}),v=await n.deliverRequest(u);v!==void 0&&e.onWalletUriReady(v);let C=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(C===wn)return;let f;for(let h=1;h<=qe;h++){let P=await(e.cancelled===void 0?e.requestPin(h,f):Promise.race([e.requestPin(h,f),e.cancelled]));try{let _=await vn({jwe:C,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:s,state:a},pin:P});if(_.delegatePortableDid===void 0)throw new Error("Connect: wallet response omitted `delegatePortableDid`.");return{delegatePortableDid:_.delegatePortableDid,delegateGrants:_.delegateGrants,connectedDid:_.providerDid,sessionRevocations:_.sessionRevocations}}catch(_){let S=_ instanceof Error?_:new Error(String(_));if(S.message.startsWith("Connect:"))throw S;f=S}}throw new Error(`[@enbox/browser] The pairing code did not match after ${qe} attempts.`)}var xt="enbox:connect:lastChoice",En=3e4,Cn=1e4,Ee=4,_n=4,vt=3,Be={background:"--ec-bg",surface:"--ec-surface",text:"--ec-text",textMuted:"--ec-muted",border:"--ec-border",accent:"--ec-accent",accentContrast:"--ec-accent-contrast",danger:"--ec-danger",success:"--ec-success"};async function Et(e){return(await xe(e))?.connectServerUrl}async function kn(e){let t=new F({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new xn({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:ye(),permissionRequests:e.permissionRequests})}function Pn(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function Rn(){return{runRelay:Ie,runPopup:kn,discoverConnectServerUrl:Et,validateWalletUrl:Ue,isMobile:Pn,storage:typeof localStorage>"u"?void 0:localStorage}}function Mn(e){try{let t=e?.getItem(xt);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&typeof n.walletUrl=="string")return{method:n.method,walletUrl:n.walletUrl}}catch{}}function Tn(e,t){try{e?.setItem(xt,JSON.stringify(t))}catch{}}function Sn(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new J))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function je(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");let t={...Rn(),...e.deps},n=Ln(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=r?Mn(t.storage):void 0,d=e.walletUrl!==void 0,p=e.walletUrl??(a!==void 0&&(d||Wn(n,a.walletUrl))?a.walletUrl:void 0)??n[0]?.url,u=e.preferredMethod??a?.method??"phone";return new Promise((v,R)=>{let C=document.createElement("div");C.id="enbox-connect-modal";let f=C.attachShadow({mode:"open"}),h=document.createElement("style");h.textContent=An,f.appendChild(h);let P=document.createElement("div");P.className="overlay";let _=document.createElement("div");_.className="modal",_.setAttribute("role","dialog"),_.setAttribute("aria-modal","true"),_.setAttribute("aria-label",`Connect to ${o}`);let S=e.theme??{},Q=S.appearance??"auto";Q!=="auto"&&_.setAttribute("data-appearance",Q);let Ce=window.matchMedia?.("(prefers-color-scheme: dark)"),_t=S.accent!==void 0||S.accentContrast!==void 0||S.light!==void 0||S.dark!==void 0,ze=()=>{let l=Q==="auto"?Ce?.matches===!0?"dark":"light":Q,c={accent:S.accent,accentContrast:S.accentContrast,...S[l]};for(let x of Object.keys(Be)){let w=c[x];typeof w=="string"&&w.trim()!==""?_.style.setProperty(Be[x],w):_.style.removeProperty(Be[x])}},$e=()=>ze();_t&&(ze(),Q==="auto"&&Ce?.addEventListener?.("change",$e));let D=!1,X,A,_e=!1,V,Ge=new Map,G=[],Ye=l=>n.find(c=>c.url===l)??{name:Nn(l)??l,url:l},kt=()=>{if(p===void 0){G=n.slice(0,vt);return}if(G.some(c=>c.url===p))return;let l=Ye(p);G=[l,...n.filter(c=>c.url!==l.url)].slice(0,vt)},pe=l=>{p=l,ee(),Z()},Pt=()=>{X?.cancel(),clearTimeout(A),document.removeEventListener("keydown",et),Ce?.removeEventListener?.("change",$e);try{document.body.removeChild(C)}catch{}},ue=l=>{D||(D=!0,Pt(),l())},Fe=l=>{r&&Tn(t.storage,{method:u,walletUrl:p??""}),St(),setTimeout(()=>ue(()=>v(l)),1200)},ke=()=>ue(()=>R(new Error("[@enbox/browser] Connect cancelled.")));_.appendChild(On(o,e.appIcon,ke));let U=document.createElement("div");U.className="stage",U.setAttribute("aria-live","polite"),_.appendChild(U);let q=document.createElement("div");q.className="footer",_.appendChild(q);let W=(...l)=>{U.replaceChildren(...l),U.classList.remove("fade-in"),U.offsetWidth,U.classList.add("fade-in")},Je=l=>{W(y("div","spinner"),y("p","stage-caption",l))},Rt=l=>{let c=p!==void 0?Ye(p):void 0,x=c?.name??"your wallet";if(s){let b=document.createElement("a");b.className="deep-link",b.href=l.walletUri,c!==void 0&&b.appendChild(ae(c)),b.appendChild(y("span","deep-link-label",`Continue in ${x}`)),W(b,y("p","stage-caption",`${x} opens to approve this connection.`),y("p","stage-subline","Come back here when you\u2019re done."));return}let w=document.createElement("div");if(w.className="qr-box",w.replaceChildren(Ae(De(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let b=y("div","qr-logo");b.appendChild(ae(c)),w.appendChild(b)}W(w,y("p","stage-caption","Scan with your phone\u2019s camera"),y("p","stage-subline",`${x} stays on your phone.`))},Mt=()=>{let l=document.createElement("div");l.className="claimed-pulse",W(l,y("p","stage-caption","Phone connected \u2014 finish there"),y("p","stage-subline","Approve the request on your phone, then come back here."))},Tt=(l,c)=>new Promise(x=>{V=x;let w=document.createElement("div");w.className="pin-row",c!==void 0&&w.classList.add("shake");let b=[];for(let k=0;k<Ee;k++){let E=document.createElement("input");E.className="pin-input",E.type="text",E.inputMode="numeric",E.maxLength=1,E.setAttribute("aria-label",`Code digit ${k+1}`),b.push(E),w.appendChild(E)}let I=()=>{let k=b.map(E=>E.value).join("");if(k.length===Ee&&V!==void 0){let E=V;V=void 0,Je("Checking the code\u2026"),E(k)}};b.forEach((k,E)=>{k.addEventListener("input",()=>{k.value=k.value.replace(/\D/g,"").slice(0,1),k.value!==""&&E+1<b.length&&b[E+1].focus(),I()}),k.addEventListener("keydown",M=>{M.key==="Backspace"&&k.value===""&&E>0&&b[E-1].focus()}),k.addEventListener("paste",M=>{let B=(M.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Ee);B.length!==0&&(M.preventDefault(),B.split("").forEach((te,H)=>{b[H]!==void 0&&(b[H].value=te)}),b[Math.min(B.length,Ee)-1]?.focus(),I())})}),W(y("p","stage-caption","Enter the code shown on your phone"),w,...c!==void 0?[y("p","stage-error","That code doesn\u2019t match \u2014 check your phone.")]:[y("p","stage-subline",l===1?"Phone connected.":"")]),b[0].focus()}),St=()=>{let l=y("div","check");l.textContent="\u2713",W(l,y("p","stage-caption","You\u2019re connected."))},Qe=()=>{W(y("p","stage-caption","No problem \u2014 nothing was shared."),de("Start over",()=>{Z()}),He("Close",()=>ue(()=>v(void 0))))},fe=(l,c)=>{W(y("p","stage-caption",l),de("Start over",()=>{Z()}),He("Close",()=>ue(()=>R(c??new Error(`[@enbox/browser] ${l}`)))))},Wt=()=>{W(y("p","stage-caption","This wallet can\u2019t connect by phone here."),y("p","stage-subline","You can continue in this browser instead."),de("Use this browser",()=>{me()}))},Lt=()=>{W(y("p","stage-caption","Connect with a wallet in this browser"),y("p","stage-subline","Your wallet opens in a small window to approve this connection."),de("Open wallet window",()=>{me()}))},Nt=()=>{W(y("div","spinner"),y("p","stage-caption","Finish in the wallet window"),y("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},Xe=l=>{W(y("p","stage-caption",l?"Your browser blocked the wallet window.":"The wallet window was closed."),de(l?"Open it now":"Reopen window",()=>{me()}),...s?[]:[He("Use your phone instead",()=>{Ze("phone")})])},Ot=async l=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let c=Ge.get(l);return c===void 0&&(c=t.discoverConnectServerUrl(l),Ge.set(l,c)),c},Dt=l=>{clearTimeout(A);let c=Math.max(Cn,l*1e3-En);A=setTimeout(()=>{!D&&V===void 0&&u==="phone"&&Ve()},c)},Ve=async()=>{if(X?.cancel(),clearTimeout(A),p===void 0){fe("No wallet is configured.");return}u="phone",ee(),Je("Getting things ready\u2026");let l=new URL(p).origin,c=await Ot(l);if(c===void 0){Wt();return}let x=Sn();X=x;try{let w=await t.runRelay({connectServerUrl:c,walletUri:new URL(i,l).toString(),appName:o,appIcon:e.appIcon,clientMetadata:ye(),permissionRequests:e.permissionRequests,timeoutMs:e.timeout,cancelled:x.cancelled,onWalletUriReady:b=>{x.active&&!D&&(Rt(b),Dt(b.expiresIn))},onClaimed:()=>{x.active&&!D&&(clearTimeout(A),Mt())},requestPin:(b,I)=>(clearTimeout(A),Tt(b,I))});if(!x.active||D)return;w===void 0?Qe():Fe(w)}catch(w){if(!x.active||D||w instanceof J)return;let b=w instanceof Error?w:new Error(String(w));fe(/timed out/i.test(b.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",b)}},me=()=>{if(X?.cancel(),clearTimeout(A),p===void 0){fe("No wallet is configured.");return}if(_e)return;u="browser",ee();let l;try{l=t.runPopup({walletUrl:p,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout})}catch(c){let x=c instanceof Error&&/popup blocked/i.test(c.message);Xe(x);return}_e=!0,Nt(),l.then(c=>{D||(c===void 0?Qe():Fe(c))}).catch(c=>{if(D)return;if(c instanceof $){Xe(!1);return}let x=c instanceof Error?c:new Error(String(c));fe(/timed out/i.test(x.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",x)}).finally(()=>{_e=!1})},Z=async()=>{u==="browser"?(X?.cancel(),clearTimeout(A),ee(),Lt()):await Ve()},Ze=async l=>{u=l,await Z()},ee=()=>{if(q.replaceChildren(),!d){kt();let c=At();c.label!==void 0&&q.appendChild(c.label),q.appendChild(c.row),q.appendChild(c.panel)}let l=document.createElement("div");if(l.className="footer-row",u==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="No phone? Use this browser \u2192",c.addEventListener("click",()=>{me()}),l.appendChild(c)}else if(!s){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="Use your phone instead \u2192",c.addEventListener("click",()=>{Ze("phone")}),l.appendChild(c)}l.childElementCount>0&&q.appendChild(l)},At=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let m of G){let g=document.createElement("button");g.className="row-tile",g.title=m.description??m.name,g.setAttribute("role","radio");let L=m.url===p;g.setAttribute("aria-checked",L?"true":"false"),L&&g.classList.add("selected"),g.appendChild(ae(m)),g.appendChild(y("span","row-tile-name",m.name)),g.addEventListener("click",()=>{m.url!==p&&pe(m.url)}),l.appendChild(g)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let x=n.filter(m=>!G.some(g=>g.url===m.url)),w=document.createElement("button");w.className="row-tile more-tile",w.title="All wallets",w.setAttribute("aria-expanded","false"),w.appendChild(y("span","more-count",x.length>0?`+${x.length}`:"\u22EF")),w.appendChild(y("span","row-tile-name","More")),w.addEventListener("click",()=>{c.hidden=!c.hidden,w.setAttribute("aria-expanded",c.hidden?"false":"true"),c.hidden||te()}),l.appendChild(w);let b=G.length>0?y("div","wallet-row-label","Connecting with"):void 0,I=[],k=document.createElement("div");if(k.className="wallet-empty",k.textContent="No other wallets match your search.",k.hidden=!0,x.length>_n){let m=document.createElement("input");m.type="search",m.className="wallet-search",m.placeholder="Search wallets\u2026",m.setAttribute("aria-label","Search wallets"),m.addEventListener("input",()=>{let g=m.value.trim().toLowerCase(),L=0;for(let{wallet:nt,el:Ut}of I){let ot=g===""||nt.name.toLowerCase().includes(g)||nt.url.toLowerCase().includes(g);Ut.hidden=!ot,ot&&(L+=1)}k.hidden=L>0,te()}),c.appendChild(m)}let E=document.createElement("div");E.className="wallet-scroll-wrap",E.hidden=x.length===0;let M=document.createElement("div");M.className="wallet-scroll";let B=document.createElement("div");B.className="wallet-grid";let te=()=>{let m=M.scrollHeight-M.clientHeight>1,g=M.scrollTop+M.clientHeight>=M.scrollHeight-1;E.classList.toggle("scroll-hint",m&&!g)};M.addEventListener("scroll",te);for(let m of x){let g=document.createElement("button");g.className="wallet-tile",g.title=m.description??m.name,g.appendChild(ae(m));let L=document.createElement("span");L.className="wallet-tile-name",L.textContent=m.name,g.appendChild(L),g.addEventListener("click",()=>{pe(m.url)}),I.push({wallet:m,el:g}),B.appendChild(g)}M.appendChild(B),M.appendChild(k),E.appendChild(M),c.appendChild(E);let H=document.createElement("div");H.className="wallet-custom";let N=document.createElement("input");N.className="url-input",N.type="url",N.placeholder="https://your-wallet.example";let O=document.createElement("button");O.className="url-go",O.textContent="Use";let j=document.createElement("div");j.className="url-error",j.hidden=!0;let Pe=!1,tt=async()=>{let m=N.value.trim();if(m==="")return;let g;try{g=new URL(m.includes("://")?m:`https://${m}`).origin}catch{N.classList.add("invalid");return}if(Pe){pe(g);return}O.disabled=!0,O.textContent="Checking\u2026",j.hidden=!0;let L=await t.validateWalletUrl(g);if(O.disabled=!1,L){O.textContent="Use",pe(g);return}Pe=!0,O.textContent="Use anyway",N.classList.add("invalid"),j.textContent=`Couldn't verify a wallet at ${g}.`,j.hidden=!1};return N.addEventListener("input",()=>{Pe=!1,O.textContent="Use",N.classList.remove("invalid"),j.hidden=!0}),N.addEventListener("keydown",m=>{m.key==="Enter"&&tt()}),O.addEventListener("click",()=>{tt()}),H.appendChild(N),H.appendChild(O),c.appendChild(H),c.appendChild(j),{label:b,row:l,panel:c}};P.addEventListener("click",l=>{l.target===P&&ke()});let et=l=>{if(l.key==="Escape"){ke();return}l.key==="Tab"&&Dn(f,l)};document.addEventListener("keydown",et),P.appendChild(_),f.appendChild(P),document.body.appendChild(C),ee(),Z()})}function Wn(e,t){return e.some(n=>n.url===t)}function Ln(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Nn(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function y(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function de(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function He(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function On(e,t,n){let r=document.createElement("div");r.className="header";let o=document.createElement("div");if(o.className="header-identity",t!==void 0){let a=document.createElement("img");a.className="header-icon",a.src=t,a.alt="",a.width=24,a.height=24,a.addEventListener("error",()=>a.remove()),o.appendChild(a)}let i=document.createElement("h2");i.textContent=`Connect to ${e}`,o.appendChild(i);let s=document.createElement("button");return s.className="close-btn",s.setAttribute("aria-label","Close"),s.textContent="\xD7",s.addEventListener("click",n),r.appendChild(o),r.appendChild(s),r}function Dn(e,t){let n=Array.from(e.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(n.length===0)return;let r=n[0],o=n[n.length-1],i=e.activeElement;t.shiftKey&&(i===r||i===null)?(t.preventDefault(),o.focus()):!t.shiftKey&&i===o&&(t.preventDefault(),r.focus())}var bt=`
154
+ `,z.lastElementChild.addEventListener("click",Oe),document.body.prepend(z),Ee=!0)}function nn(){Ee&&(re?.remove(),re=null,z?.remove(),z=null,Ee=!1)}function Oe(){document.documentElement.removeAttribute("drl-link-loading"),be=null}var be=null,xe=!1,ie=null,ae=null;function on(){xe||(ie=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=oe(n);if(r){let o=r[0],i=r[1],s=t.target==="_blank";e.preventDefault();try{let a=null;s?(a=window.open("","_blank"),a&&a.document.write(tn)):(be=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await ht(o);if(!d.length)throw new Error("no valid DWN endpoints found");let p=`${d[0].replace(ye,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=p):be===i&&(window.location.href=p)}catch{throw be===i&&Oe(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},ae=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(J(),t?.src&&oe(t.src)){G=t,t.__src__=t.src;let n=t.src.replace(ft,"https:").replace(ye,""),o=await(await gt())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",J,{once:!0})}}else t===G&&J()},document.addEventListener("click",ie),document.addEventListener("pointercancel",J),document.addEventListener("pointerdown",ae),xe=!0)}function rn(){xe&&(ie&&(document.removeEventListener("click",ie),ie=null),ae&&(document.removeEventListener("pointerdown",ae),ae=null),document.removeEventListener("pointercancel",J),J(),Oe(),xe=!1)}var G=null;async function J(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),G&&(G.src=G.__src__,delete G.__src__,G=null)}function ao(e={}){e.didResolvers&&(Ne=new ut({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&en(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",pt,{once:!0}):pt()),e.links!==!1&&on())}function so(){typeof window<"u"&&typeof window.document<"u"&&(rn(),nn())}async function lo(){return typeof caches>"u"?!1:caches.delete(mt)}import{ConnectClient as On}from"@enbox/connect";function se(e){let t=document.createElement("span");t.className="wallet-icon";let n=document.createElement("span");n.className="wallet-badge",n.textContent=e.name.charAt(0).toUpperCase(),t.appendChild(n);let r=an(e);if(r.length===0)return t;let o=document.createElement("img");o.className="wallet-img",o.alt="",o.width=28,o.height=28;let i=0;return o.addEventListener("error",()=>{i+=1,i<r.length?o.src=r[i]:o.remove()}),o.src=r[i],t.appendChild(o),t}function an(e){if(e.icon!==void 0)return[e.icon];let t;try{t=new URL(e.url).origin}catch{return[]}return[`${t}/favicon.svg`,`${t}/favicon.ico`,`${t}/favicon.png`]}import{assertX25519PublicJwk as sn,CONNECT_DENIED_TOKEN as ln,ConnectClient as cn}from"@enbox/connect";var Ae="/dweb-connect",le="enbox-connect-loaded",ce="enbox-connect-request",X="enbox-connect-response",de="enbox-connect-ack";function Ce(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var dn=3e5,pn=500,un=1500,fn="enbox-dweb-connect",vt=500,bt=700;function mn(){let e=`width=${vt},height=${bt},menubar=no,toolbar=no,location=no,status=no`,t=window.outerWidth>0?window.outerWidth:window.screen?.availWidth??0,n=window.outerHeight>0?window.outerHeight:window.screen?.availHeight??0;if(t===0||n===0)return e;let r=Math.max(0,Math.round((window.screenX??0)+(t-vt)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-bt)/2));return`${e},left=${r},top=${o}`}function hn(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var Y=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},V=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;hn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??dn;let n=new URL(Ae,t.walletUrl).toString(),r=window.open(n,fn,mn());if(!r)throw new Error("[@enbox/browser] Popup blocked. Allow popups for this site to connect to a wallet.");this._popup=r,this._walletEpkPromise=new Promise((o,i)=>{this._resolveWalletEpk=o,this._rejectWalletEpk=i}),this._responsePromise=new Promise((o,i)=>{this._resolveResponse=o,this._rejectResponse=i}),this._responsePromise.catch(()=>{}),this._messageListener=o=>{this.onMessage(o)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.fail(new Error("[@enbox/browser] DWeb Connect timed out waiting for wallet response."))},this._timeoutMs),this._closedPollId=setInterval(()=>{this.onClosedPoll()},pn)}async requestProfile(t){return{encryption:{mode:"ecdh-es",walletEpk:await this._walletEpkPromise,walletOrigin:this._walletOrigin},reply:{mode:"post_message"},state:t}}async deliverRequest(t){this._popup.postMessage({type:ce,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:de},this._walletOrigin)}onMessage(t){let n=Ce(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===le){this.onLoadedBeacon(n);return}n.type===X&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{sn(t.walletEpk),n=t.walletEpk}catch{this.fail(new Error("[@enbox/browser] Wallet loaded beacon did not carry a valid X25519 public key."));return}if(t.walletOrigin!==this._walletOrigin){this.fail(new Error("[@enbox/browser] Wallet loaded beacon origin does not match the configured wallet origin."));return}this._walletEpkReceived=!0,this._resolveWalletEpk?.(n)}onResponseMessage(t){if(!this._settled){if(typeof t.payload!="string"){this.fail(new Error("[@enbox/browser] Wallet response message did not carry a ciphertext payload."));return}this._settled=!0,this.cleanup(),this._rejectWalletEpk?.(new Error("[@enbox/browser] Wallet responded before the handshake was established.")),this._resolveResponse?.(t.payload)}}onClosedPoll(){if(!(this._settled||this._popup.closed!==!0)){if(!this._walletEpkReceived){this.fail(new Y);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse?.(ln))},un)}}fail(t){if(!this._settled){this._settled=!0,this.cleanup();try{this._popup.close()}catch{}this._rejectWalletEpk?.(t),this._rejectResponse?.(t)}}cleanup(){clearTimeout(this._timeoutId),clearInterval(this._closedPollId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}};function _e(){let e=Intl.DateTimeFormat().resolvedOptions(),t=Array.isArray(globalThis.navigator.languages)?globalThis.navigator.languages.filter(n=>typeof n=="string"&&n.length>0):void 0;return{origin:globalThis.location.origin,userAgent:globalThis.navigator.userAgent,platform:globalThis.navigator.platform,language:globalThis.navigator.language,...t&&t.length>0?{languages:t}:{},...e.timeZone?{timezone:e.timeZone}:{}}}async function gn(e){let t=new V({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new cn({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof Y)return;throw r}}var xt=[-1,10,16,26,18,24,16,18,22,22,26],Ct=[-1,1,1,1,2,2,4,4,4,5,5],_t=[-1,26,44,70,100,134,172,196,242,292,346],wn=0,yt=10;function Et(e){return _t[e]-xt[e]*Ct[e]}function Be(e,t){let n=new TextEncoder().encode(e),r=0;for(let f=1;f<=yt;f++){let g=Et(f)*8;if(4+(f<=9?8:16)+n.length*8<=g){r=f;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${yt}-M capacity).`);let o=[],i=(f,g)=>{for(let P=g-1;P>=0;P--)o.push(f>>>P&1)};i(4,4),i(n.length,r<=9?8:16);for(let f of n)i(f,8);let s=Et(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let f=0;o.length<s;f++)i(a[f%2],8);let d=new Uint8Array(s/8);for(let f=0;f<o.length;f++)d[f>>3]|=o[f]<<7-(f&7);let p=vn(d,r),u=17+4*r,y=Array.from({length:u},()=>new Array(u).fill(!1)),M=Array.from({length:u},()=>new Array(u).fill(!1));xn(y,M,r),kn(y,M,p);let x=t??-1;if(x===-1){let f=1/0;for(let g=0;g<8;g++){Ue(y,M,g),He(y,M,g);let P=Pn(y);P<f&&(f=P,x=g),Ue(y,M,g)}}return Ue(y,M,x),He(y,M,x),{size:u,modules:y,version:r,mask:x}}function vn(e,t){let n=Ct[t],r=xt[t],o=_t[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],p=bn(r),u=0;for(let f=0;f<n;f++){let g=s-r+(f<i?0:1),P=e.slice(u,u+g);u+=g,a.push(P),d.push(yn(P,p))}let y=new Uint8Array(o),M=0,x=s-r+1;for(let f=0;f<x;f++)for(let g=0;g<n;g++)f<a[g].length&&(y[M++]=a[g][f]);for(let f=0;f<r;f++)for(let g=0;g<n;g++)y[M++]=d[g][f];return y}function Ie(e,t){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n&255}function bn(e){let t=new Uint8Array(e);t[e-1]=1;let n=1;for(let r=0;r<e;r++){for(let o=0;o<e;o++)t[o]=Ie(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Ie(n,2)}return t}function yn(e,t){let n=new Uint8Array(t.length);for(let r of e){let o=r^n[0];n.copyWithin(0,1),n[n.length-1]=0;for(let i=0;i<t.length;i++)n[i]^=Ie(t[i],o)}return n}var En=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function T(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function xn(e,t,n){let r=e.length;for(let i=0;i<r;i++)T(e,t,6,i,i%2===0),T(e,t,i,6,i%2===0);De(e,t,3,3),De(e,t,r-4,3),De(e,t,3,r-4);let o=En[n];for(let i=0;i<o.length;i++)for(let s=0;s<o.length;s++)i===0&&s===0||i===0&&s===o.length-1||i===o.length-1&&s===0||Cn(e,t,o[i],o[s]);He(e,t,0),T(e,t,8,r-8,!0),n>=7&&_n(e,t,n)}function De(e,t,n,r){let o=e.length;for(let i=-4;i<=4;i++)for(let s=-4;s<=4;s++){let a=n+s,d=r+i;if(a<0||a>=o||d<0||d>=o)continue;let p=Math.max(Math.abs(s),Math.abs(i));T(e,t,a,d,p!==2&&p!==4)}}function Cn(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)T(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function He(e,t,n){let r=e.length,o=wn<<3|n,i=o;for(let a=0;a<10;a++)i=i<<1^(i>>>9)*1335;let s=(o<<10|i)^21522;for(let a=0;a<=5;a++)T(e,t,8,a,(s>>>a&1)!==0);T(e,t,8,7,(s>>>6&1)!==0),T(e,t,8,8,(s>>>7&1)!==0),T(e,t,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)T(e,t,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)T(e,t,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)T(e,t,8,r-15+a,(s>>>a&1)!==0)}function _n(e,t,n){let r=e.length,o=n;for(let s=0;s<12;s++)o=o<<1^(o>>>11)*7973;let i=n<<12|o;for(let s=0;s<18;s++){let a=(i>>>s&1)!==0,d=r-11+s%3,p=Math.floor(s/3);T(e,t,d,p,a),T(e,t,p,d,a)}}function kn(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){i===6&&(i=5);for(let s=0;s<r;s++)for(let a=0;a<2;a++){let d=i-a,u=(i+1&2)===0?r-1-s:s;!t[u][d]&&o<n.length*8&&(e[u][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function Ue(e,t,n){let r=e.length;for(let o=0;o<r;o++)for(let i=0;i<r;i++){if(t[o][i])continue;let s;switch(n){case 0:s=(i+o)%2===0;break;case 1:s=o%2===0;break;case 2:s=i%3===0;break;case 3:s=(i+o)%3===0;break;case 4:s=(Math.floor(i/3)+Math.floor(o/2))%2===0;break;case 5:s=i*o%2+i*o%3===0;break;case 6:s=(i*o%2+i*o%3)%2===0;break;default:s=((i+o)%2+i*o%3)%2===0;break}s&&(e[o][i]=!e[o][i])}}function Pn(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[a][u]!==d?(d=e[a][u],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[u][a]!==d?(d=e[u][a],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let p=e[a][d];p===e[a][d+1]&&p===e[a+1][d]&&p===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((x,f)=>a[d+f]===x))return 0;let y=d>=4&&a.slice(d-4,d).every(x=>!x),M=d+11<=a.length&&a.slice(d+7,d+11).every(x=>!x);return(y?40:0)+(M?40:0)};for(let a=0;a<t;a++){let d=e[a],p=e.map(u=>u[a]);for(let u=0;u+7<=t;u++)n+=r(d,u),n+=r(p,u)}let o=0;for(let a of e)for(let d of a)d&&o++;let i=t*t,s=Math.ceil(Math.abs(o*20-i*10)/i)-1;return n+=s*10,n}var qe="http://www.w3.org/2000/svg";function je(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let u=0;u<e.size;u++)for(let y=0;y<e.size;y++)e.modules[u][y]&&(s+=`M${y+o} ${u+o}h1v1h-1z`);let a=document.createElementNS(qe,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(qe,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let p=document.createElementNS(qe,"path");return p.setAttribute("d",s),p.setAttribute("fill",n),a.appendChild(p),a}var kt="/.well-known/enbox-connect";async function ke(e){try{let t=new URL(kt,e).toString(),n=await fetch(t,{signal:AbortSignal.timeout(6e3)});if(!n.ok)return;let r=await n.json();return typeof r?.connectServerUrl!="string"?void 0:{connectServerUrl:r.connectServerUrl}}catch{return}}async function $e(e){return await ke(e)!==void 0}import{DidJwk as Mn}from"@enbox/dids";import{X25519 as Rn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Tn,openResponse as Sn,randomToken as Pt,RelayClientTransport as Wn,sealRequest as Ln}from"@enbox/connect";var Ke=6,Z=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function Nn(e){return new Promise(t=>{if(typeof document>"u"){setTimeout(t,e);return}let n=()=>{clearTimeout(o),document.removeEventListener("visibilitychange",r),t()},r=()=>{document.visibilityState==="visible"&&n()},o=setTimeout(n,e);document.addEventListener("visibilitychange",r)})}async function ze(e){let n=(e.createTransport??(g=>new Wn({...g,sleep:Nn})))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed}),r=await Mn.create(),o=await Rn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=Pt(),a=Pt(),d=await n.requestProfile(a),p={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:a,responseKey:i,reply:d.reply},u=await Ln({request:p,signer:r,encryption:d.encryption}),y=await n.deliverRequest(u);y!==void 0&&e.onWalletUriReady(y);let x=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(x===Tn)return;let f;for(let g=1;g<=Ke;g++){let P=await(e.cancelled===void 0?e.requestPin(g,f):Promise.race([e.requestPin(g,f),e.cancelled]));try{let C=await Sn({jwe:x,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:s,state:a},pin:P});if(C.delegatePortableDid===void 0)throw new Error("Connect: wallet response omitted `delegatePortableDid`.");return n.confirmComplete?.().catch(()=>{}),{delegatePortableDid:C.delegatePortableDid,delegateGrants:C.delegateGrants,connectedDid:C.providerDid,sessionRevocations:C.sessionRevocations}}catch(C){let L=C instanceof Error?C:new Error(String(C));if(L.message.startsWith("Connect:"))throw L;f=L}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ke} attempts.`)}var St="enbox:connect:lastChoice",An=12e4,Dn=1e4,Pe=4,Un=4,Mt=3,Ge={background:"--ec-bg",surface:"--ec-surface",text:"--ec-text",textMuted:"--ec-muted",border:"--ec-border",accent:"--ec-accent",accentContrast:"--ec-accent-contrast",danger:"--ec-danger",success:"--ec-success"};async function Wt(e){return(await ke(e))?.connectServerUrl}async function qn(e){let t=new V({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new On({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests})}function In(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function Hn(){return{runRelay:ze,runPopup:qn,discoverConnectServerUrl:Wt,validateWalletUrl:$e,isMobile:In,storage:typeof localStorage>"u"?void 0:localStorage}}function Bn(e){try{let t=e?.getItem(St);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&typeof n.walletUrl=="string")return{method:n.method,walletUrl:n.walletUrl}}catch{}}function jn(e,t){try{e?.setItem(St,JSON.stringify(t))}catch{}}function $n(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new Z))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Ye(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");let t={...Hn(),...e.deps},n=zn(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=r?Bn(t.storage):void 0,d=e.walletUrl!==void 0,p=e.walletUrl??(a!==void 0&&(d||Kn(n,a.walletUrl))?a.walletUrl:void 0)??n[0]?.url,u=e.preferredMethod??a?.method??"phone";return new Promise((y,M)=>{let x=document.createElement("div");x.id="enbox-connect-modal";let f=x.attachShadow({mode:"open"}),g=document.createElement("style");g.textContent=Qn,f.appendChild(g);let P=document.createElement("div");P.className="overlay";let C=document.createElement("div");C.className="modal",C.setAttribute("role","dialog"),C.setAttribute("aria-modal","true"),C.setAttribute("aria-label",`Connect to ${o}`);let L=e.theme??{},ee=L.appearance??"auto";ee!=="auto"&&C.setAttribute("data-appearance",ee);let Re=window.matchMedia?.("(prefers-color-scheme: dark)"),Nt=L.accent!==void 0||L.accentContrast!==void 0||L.light!==void 0||L.dark!==void 0,Qe=()=>{let c=ee==="auto"?Re?.matches===!0?"dark":"light":ee,l={accent:L.accent,accentContrast:L.accentContrast,...L[c]};for(let w of Object.keys(Ge)){let m=l[w];typeof m=="string"&&m.trim()!==""?C.style.setProperty(Ge[w],m):C.style.removeProperty(Ge[w])}},Je=()=>Qe();Nt&&(Qe(),ee==="auto"&&Re?.addEventListener?.("change",Je));let N=!1,q,Xe,ue,Te=!1,I,Ve=new Map,F=[],fe=c=>n.find(l=>l.url===c)??{name:Gn(c)??c,url:c},Ot=()=>{if(p===void 0){F=n.slice(0,Mt);return}if(F.some(l=>l.url===p))return;let c=fe(p);F=[c,...n.filter(l=>l.url!==c.url)].slice(0,Mt)},me=c=>{p=c,ne(),te()},At=()=>{q?.cancel(),j(),document.removeEventListener("keydown",at),document.removeEventListener("visibilitychange",st),Re?.removeEventListener?.("change",Je);try{document.body.removeChild(x)}catch{}},he=c=>{N||(N=!0,At(),c())},Ze=c=>{r&&jn(t.storage,{method:u,walletUrl:p??""}),Bt(),setTimeout(()=>he(()=>y(c)),1200)},Se=()=>he(()=>M(new Error("[@enbox/browser] Connect cancelled.")));C.appendChild(Yn(o,e.appIcon,Se));let H=document.createElement("div");H.className="stage",H.setAttribute("aria-live","polite"),C.appendChild(H);let B=document.createElement("div");B.className="footer",C.appendChild(B);let S=(...c)=>{H.replaceChildren(...c),H.classList.remove("fade-in"),H.offsetWidth,H.classList.add("fade-in")},et=c=>{S(v("div","spinner"),v("p","stage-caption",c))},Dt=c=>{let l=q;setTimeout(()=>{N||l!==q||l?.active!==!0||I!==void 0||qt(c)},0)},tt=(c,l,w)=>{let m=document.createElement("a");return m.className=w,m.href=c.walletUri,m.target="_blank",m.rel="noopener noreferrer",m.addEventListener("click",()=>{Dt(l)}),m},Ut=c=>{let l=p!==void 0?fe(p):void 0,w=l?.name??"your wallet",m=tt(c,w,"qr-box qr-link");if(m.setAttribute("aria-label",`Open ${w} on this device`),m.replaceChildren(je(Be(c.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),l!==void 0){let _=v("div","qr-logo");_.appendChild(se(l)),m.appendChild(_)}if(s){let _=tt(c,w,"deep-link");l!==void 0&&_.appendChild(se(l)),_.appendChild(v("span","deep-link-label",`Continue in ${w}`)),m.classList.add("compact"),S(_,v("p","stage-subline",`${w} opens in a new tab \u2014 approve there, then come back for your code.`),v("div","stage-divider","or scan with another phone"),m);return}S(m,v("p","stage-caption","Scan with your phone\u2019s camera"),v("p","stage-subline",`${w} stays on your phone \u2014 or click the code to open it here.`))},qt=c=>{S(v("div","spinner"),v("p","stage-caption",`Finish in ${c}`),v("p","stage-subline",s?`Approve the connection in the ${c} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),Me("Start over",()=>{We()}))},It=()=>{let c=p!==void 0?fe(p).name:"your wallet",l=document.createElement("div");l.className="claimed-pulse",S(l,v("p","stage-caption",`Request received \u2014 approve in ${c}`),v("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},Ht=(c,l)=>new Promise(w=>{I=w;let m=p!==void 0?fe(p).name:"your wallet",_=document.createElement("div");_.className="pin-row",l!==void 0&&_.classList.add("shake");let R=[];for(let k=0;k<Pe;k++){let E=document.createElement("input");E.className="pin-input",E.type="text",E.inputMode="numeric",E.maxLength=1,E.setAttribute("aria-label",`Code digit ${k+1}`),R.push(E),_.appendChild(E)}let D=()=>{let k=R.map(E=>E.value).join("");if(k.length===Pe&&I!==void 0){let E=I;I=void 0,et("Checking the code\u2026"),E(k)}};R.forEach((k,E)=>{k.addEventListener("input",()=>{k.value=k.value.replace(/\D/g,"").slice(0,1),k.value!==""&&E+1<R.length&&R[E+1].focus(),D()}),k.addEventListener("keydown",U=>{U.key==="Backspace"&&k.value===""&&E>0&&R[E-1].focus()}),k.addEventListener("paste",U=>{let $=(U.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Pe);$.length!==0&&(U.preventDefault(),$.split("").forEach((Q,W)=>{R[W]!==void 0&&(R[W].value=Q)}),R[Math.min($.length,Pe)-1]?.focus(),D())})}),S(v("p","stage-caption",`Enter the code shown in ${m}`),_,...l!==void 0?[v("p","stage-error",`That code doesn\u2019t match \u2014 check ${m}.`)]:[v("p","stage-subline",c===1?"This confirms you\u2019re the one approving.":"")]),R[0].focus()}),Bt=()=>{let c=v("div","check");c.textContent="\u2713",S(c,v("p","stage-caption","You\u2019re connected."))},nt=()=>{S(v("p","stage-caption","No problem \u2014 nothing was shared."),pe("Start over",()=>{te()}),Me("Close",()=>he(()=>y(void 0))))},ge=(c,l)=>{S(v("p","stage-caption",c),pe("Start over",()=>{te()}),Me("Close",()=>he(()=>M(l??new Error(`[@enbox/browser] ${c}`)))))},jt=()=>{S(v("p","stage-caption","This wallet can\u2019t connect by phone here."),v("p","stage-subline","You can continue in this browser instead."),pe("Use this browser",()=>{ve()}))},we=s?"tab":"window",$t=()=>{S(v("p","stage-caption","Connect with a wallet in this browser"),v("p","stage-subline",s?"Your wallet opens in a new tab to approve this connection \u2014 no code needed.":"Your wallet opens in a small window to approve this connection."),pe(s?"Open wallet":"Open wallet window",()=>{ve()}))},Kt=()=>{S(v("div","spinner"),v("p","stage-caption",`Finish in the wallet ${we}`),v("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},ot=c=>{S(v("p","stage-caption",c?`Your browser blocked the wallet ${we}.`:`The wallet ${we} was closed.`),pe(c?"Open it now":`Reopen ${we}`,()=>{ve()}),Me(s?"Use a code instead":"Use your phone instead",()=>{it("phone")}))},zt=async c=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let l=Ve.get(c);return l===void 0&&(l=t.discoverConnectServerUrl(c),Ve.set(c,l)),l},j=()=>{clearTimeout(Xe),ue=void 0},rt=()=>{!N&&I===void 0&&u==="phone"&&We()},Gt=c=>{j();let l=Math.max(Dn,c*1e3-An);ue=Date.now()+l,Xe=setTimeout(rt,l)},We=async()=>{if(q?.cancel(),j(),p===void 0){ge("No wallet is configured.");return}u="phone",ne(),et("Getting things ready\u2026");let c=new URL(p).origin,l=await zt(c);if(l===void 0){jt();return}let w=$n();q=w;try{let m=await t.runRelay({connectServerUrl:l,walletUri:new URL(i,c).toString(),appName:o,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests,timeoutMs:e.timeout,cancelled:w.cancelled,onWalletUriReady:_=>{w.active&&!N&&(Ut(_),Gt(_.expiresIn))},onClaimed:()=>{w.active&&!N&&(j(),It())},requestPin:(_,R)=>(j(),Ht(_,R))});if(!w.active||N)return;m===void 0?nt():Ze(m)}catch(m){if(!w.active||N||m instanceof Z)return;let _=m instanceof Error?m:new Error(String(m));ge(/timed out/i.test(_.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",_)}},ve=()=>{if(q?.cancel(),j(),p===void 0){ge("No wallet is configured.");return}if(Te)return;u="browser",ne();let c;try{c=t.runPopup({walletUrl:p,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout})}catch(l){let w=l instanceof Error&&/popup blocked/i.test(l.message);ot(w);return}Te=!0,Kt(),c.then(l=>{N||(l===void 0?nt():Ze(l))}).catch(l=>{if(N)return;if(l instanceof Y){ot(!1);return}let w=l instanceof Error?l:new Error(String(l));ge(/timed out/i.test(w.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",w)}).finally(()=>{Te=!1})},te=async()=>{u==="browser"?(q?.cancel(),j(),ne(),$t()):await We()},it=async c=>{u=c,await te()},ne=()=>{if(B.replaceChildren(),!d){Ot();let l=Yt();l.label!==void 0&&B.appendChild(l.label),B.appendChild(l.row),B.appendChild(l.panel)}let c=document.createElement("div");if(c.className="footer-row",u==="phone"){let l=document.createElement("button");l.className="footer-link method-link",l.textContent=s?"Or connect without a code \u2192":"No phone? Use this browser \u2192",l.addEventListener("click",()=>{ve()}),c.appendChild(l)}else{let l=document.createElement("button");l.className="footer-link method-link",l.textContent=s?"Use a code instead \u2192":"Use your phone instead \u2192",l.addEventListener("click",()=>{it("phone")}),c.appendChild(l)}c.childElementCount>0&&B.appendChild(c)},Yt=()=>{let c=document.createElement("div");c.className="wallet-row",c.setAttribute("role","radiogroup"),c.setAttribute("aria-label","Wallet");for(let h of F){let b=document.createElement("button");b.className="row-tile",b.title=h.description??h.name,b.setAttribute("role","radio");let O=h.url===p;b.setAttribute("aria-checked",O?"true":"false"),O&&b.classList.add("selected"),b.appendChild(se(h)),b.appendChild(v("span","row-tile-name",h.name)),b.addEventListener("click",()=>{h.url!==p&&me(h.url)}),c.appendChild(b)}let l=document.createElement("div");l.className="wallet-panel",l.hidden=!0;let w=n.filter(h=>!F.some(b=>b.url===h.url)),m=document.createElement("button");m.className="row-tile more-tile",m.title="All wallets",m.setAttribute("aria-expanded","false"),m.appendChild(v("span","more-count",w.length>0?`+${w.length}`:"\u22EF")),m.appendChild(v("span","row-tile-name","More")),m.addEventListener("click",()=>{l.hidden=!l.hidden,m.setAttribute("aria-expanded",l.hidden?"false":"true"),l.hidden||$()}),c.appendChild(m);let _=F.length>0?v("div","wallet-row-label","Connecting with"):void 0,R=[],D=document.createElement("div");if(D.className="wallet-empty",D.textContent="No other wallets match your search.",D.hidden=!0,w.length>Un){let h=document.createElement("input");h.type="search",h.className="wallet-search",h.placeholder="Search wallets\u2026",h.setAttribute("aria-label","Search wallets"),h.addEventListener("input",()=>{let b=h.value.trim().toLowerCase(),O=0;for(let{wallet:ct,el:Ft}of R){let dt=b===""||ct.name.toLowerCase().includes(b)||ct.url.toLowerCase().includes(b);Ft.hidden=!dt,dt&&(O+=1)}D.hidden=O>0,$()}),l.appendChild(h)}let k=document.createElement("div");k.className="wallet-scroll-wrap",k.hidden=w.length===0;let E=document.createElement("div");E.className="wallet-scroll";let U=document.createElement("div");U.className="wallet-grid";let $=()=>{let h=E.scrollHeight-E.clientHeight>1,b=E.scrollTop+E.clientHeight>=E.scrollHeight-1;k.classList.toggle("scroll-hint",h&&!b)};E.addEventListener("scroll",$);for(let h of w){let b=document.createElement("button");b.className="wallet-tile",b.title=h.description??h.name,b.appendChild(se(h));let O=document.createElement("span");O.className="wallet-tile-name",O.textContent=h.name,b.appendChild(O),b.addEventListener("click",()=>{me(h.url)}),R.push({wallet:h,el:b}),U.appendChild(b)}E.appendChild(U),E.appendChild(D),k.appendChild(E),l.appendChild(k);let Q=document.createElement("div");Q.className="wallet-custom";let W=document.createElement("input");W.className="url-input",W.type="url",W.placeholder="https://your-wallet.example";let A=document.createElement("button");A.className="url-go",A.textContent="Use";let K=document.createElement("div");K.className="url-error",K.hidden=!0;let Le=!1,lt=async()=>{let h=W.value.trim();if(h==="")return;let b;try{b=new URL(h.includes("://")?h:`https://${h}`).origin}catch{W.classList.add("invalid");return}if(Le){me(b);return}A.disabled=!0,A.textContent="Checking\u2026",K.hidden=!0;let O=await t.validateWalletUrl(b);if(A.disabled=!1,O){A.textContent="Use",me(b);return}Le=!0,A.textContent="Use anyway",W.classList.add("invalid"),K.textContent=`Couldn't verify a wallet at ${b}.`,K.hidden=!1};return W.addEventListener("input",()=>{Le=!1,A.textContent="Use",W.classList.remove("invalid"),K.hidden=!0}),W.addEventListener("keydown",h=>{h.key==="Enter"&&lt()}),A.addEventListener("click",()=>{lt()}),Q.appendChild(W),Q.appendChild(A),l.appendChild(Q),l.appendChild(K),{label:_,row:c,panel:l}};P.addEventListener("click",c=>{c.target===P&&Se()});let at=c=>{if(c.key==="Escape"){Se();return}c.key==="Tab"&&Fn(f,c)};document.addEventListener("keydown",at);let st=()=>{if(!(document.visibilityState!=="visible"||N)){if(ue!==void 0&&Date.now()>=ue){rt();return}I!==void 0&&Array.from(f.querySelectorAll(".pin-input")).find(l=>l.value==="")?.focus()}};document.addEventListener("visibilitychange",st),P.appendChild(C),f.appendChild(P),document.body.appendChild(x),ne(),te()})}function Kn(e,t){return e.some(n=>n.url===t)}function zn(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Gn(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function v(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function pe(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Me(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function Yn(e,t,n){let r=document.createElement("div");r.className="header";let o=document.createElement("div");if(o.className="header-identity",t!==void 0){let a=document.createElement("img");a.className="header-icon",a.src=t,a.alt="",a.width=24,a.height=24,a.addEventListener("error",()=>a.remove()),o.appendChild(a)}let i=document.createElement("h2");i.textContent=`Connect to ${e}`,o.appendChild(i);let s=document.createElement("button");return s.className="close-btn",s.setAttribute("aria-label","Close"),s.textContent="\xD7",s.addEventListener("click",n),r.appendChild(o),r.appendChild(s),r}function Fn(e,t){let n=Array.from(e.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(n.length===0)return;let r=n[0],o=n[n.length-1],i=e.activeElement;t.shiftKey&&(i===r||i===null)?(t.preventDefault(),o.focus()):!t.shiftKey&&i===o&&(t.preventDefault(),r.focus())}var Rt=`
155
155
  --ec-bg: #ffffff;
156
156
  --ec-surface: #f5f6f8;
157
157
  --ec-text: #17171f;
@@ -160,7 +160,7 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
160
160
  --ec-accent: #0a62d0;
161
161
  --ec-accent-contrast: #ffffff;
162
162
  --ec-danger: #c0392b;
163
- --ec-success: #1e9e5a;`,yt=`
163
+ --ec-success: #1e9e5a;`,Tt=`
164
164
  --ec-bg: #181822;
165
165
  --ec-surface: #23232f;
166
166
  --ec-text: #e9e9f0;
@@ -169,7 +169,7 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
169
169
  --ec-accent: #58a6ff;
170
170
  --ec-accent-contrast: #0b1526;
171
171
  --ec-danger: #ff7a7a;
172
- --ec-success: #43d17c;`,An=`
172
+ --ec-success: #43d17c;`,Qn=`
173
173
  * { box-sizing: border-box; margin: 0; padding: 0; }
174
174
 
175
175
  /* Keep the hidden attribute authoritative: author display values (e.g.
@@ -204,7 +204,7 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
204
204
  50% { transform: scale(1); opacity: 1; }
205
205
  }
206
206
 
207
- .modal {${bt}
207
+ .modal {${Rt}
208
208
  --ec-accent-soft: color-mix(in srgb, var(--ec-accent) 14%, transparent);
209
209
  background: var(--ec-bg);
210
210
  color: var(--ec-text);
@@ -220,12 +220,12 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
220
220
  flex-direction: column;
221
221
  }
222
222
  @media (prefers-color-scheme: dark) {
223
- .modal {${yt}
223
+ .modal {${Tt}
224
224
  }
225
225
  }
226
- .modal[data-appearance='light'] {${bt}
226
+ .modal[data-appearance='light'] {${Rt}
227
227
  }
228
- .modal[data-appearance='dark'] {${yt}
228
+ .modal[data-appearance='dark'] {${Tt}
229
229
  }
230
230
 
231
231
  button, input { font-family: inherit; }
@@ -288,6 +288,31 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
288
288
  .qr-logo .wallet-icon { width: 30px; height: 30px; }
289
289
  .qr-logo .wallet-badge { border-radius: 8px; font-size: 15px; }
290
290
 
291
+ /* The QR card doubles as the same-device handoff link. */
292
+ a.qr-box { display: block; cursor: pointer; }
293
+ .qr-box.qr-link:hover {
294
+ border-color: var(--ec-accent);
295
+ box-shadow: 0 0 0 3px var(--ec-accent-soft);
296
+ }
297
+ .qr-box.compact { width: 160px; height: 160px; }
298
+ .qr-box.compact .qr-logo { width: 36px; height: 36px; }
299
+ .qr-box.compact .qr-logo .wallet-icon { width: 24px; height: 24px; }
300
+
301
+ .stage-divider {
302
+ display: flex;
303
+ align-items: center;
304
+ gap: 10px;
305
+ width: 100%;
306
+ color: var(--ec-muted);
307
+ font-size: 12px;
308
+ }
309
+ .stage-divider::before, .stage-divider::after {
310
+ content: '';
311
+ flex: 1;
312
+ height: 1px;
313
+ background: var(--ec-border);
314
+ }
315
+
291
316
  .claimed-pulse {
292
317
  width: 64px; height: 64px; border-radius: 50%;
293
318
  background: var(--ec-accent-soft); position: relative;
@@ -511,5 +536,5 @@ import{Enbox as _o,defineProtocol as ko,repository as Po}from"@enbox/api";import
511
536
  .overlay, .modal, .stage.fade-in > *, .pin-row.shake { animation: none; }
512
537
  .claimed-pulse::after { animation: none; }
513
538
  }
514
- `;var Ct=[{name:"Enbox",url:"https://enbox-wallet.pages.dev",description:"Manage your digital identity and data"},{name:"Prism",url:"https://prism-wallet.pages.dev",description:"A clear view into your digital identity"},{name:"Matcha",url:"https://matcha-wallet.pages.dev",description:"A fresh approach to digital identity"},{name:"Onyx",url:"https://onyx-wallet.pages.dev",description:"A refined home for your digital identity"},{name:"Taffy",url:"https://taffy-wallet.pages.dev",description:"A playful take on your digital identity"},{name:"Astoria",url:"https://astoria-wallet.pages.dev",description:"A grand home for your digital identity"}];function Un(e={}){let{wallets:t=Ct,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:p,theme:u}=e;return{async requestAccess(v){return je({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:p,timeout:r,theme:u,permissionRequests:v.permissionRequests})}}}import{X25519 as qn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as In,ConnectProvider as Bn}from"@enbox/connect";var Hn=3e5,Ke=class e{constructor(t){this._requestReceived=!1;this._dappOrigin=t.dappOrigin,this._dappWindow=t.dappWindow,this._recipientPrivateKey=t.recipientPrivateKey,this._requestPromise=new Promise((n,r)=>{this._resolveRequest=n,this._rejectRequest=r}),this._requestPromise.catch(()=>{}),this._messageListener=n=>{this.onMessage(n)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.close(),this._rejectRequest?.(new Error("[@enbox/browser] Timed out waiting for the connect request from the dapp."))},t.timeoutMs)}static async create(t={}){if(typeof window>"u")throw new Error("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let n=t.dappWindow??window.opener;if(!n)throw new Error("[@enbox/browser] No opener window: the DWeb Connect page must be opened as a popup by the dapp.");let r=jn(t.dappOrigin),o=await qn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??Hn});return n.postMessage({type:se,walletEpk:i,walletOrigin:globalThis.location.origin},r),s}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(t){this._dappWindow.postMessage({type:ce,payload:t},this._dappOrigin),this.close()}deny(){this.sendResponse(In)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=be(t,this._dappOrigin,this._dappWindow);if(n!==void 0&&!(n.type!==le||this._requestReceived)){if(this._requestReceived=!0,typeof n.jwe!="string"){this.settleRequest(new Error("[@enbox/browser] Connect request message did not carry a ciphertext payload."));return}this.openRequest(n.jwe)}}async openRequest(t){try{let n=await Bn.openRequest({jwe:t,decryption:{mode:"ecdh-es",recipientPrivateKey:this._recipientPrivateKey,walletOrigin:globalThis.location.origin}});if(n.reply.mode!=="post_message"){this.settleRequest(new Error("[@enbox/browser] Connect request over the popup channel must use the `post_message` reply mode."));return}this.settleRequest(n)}catch(n){this.settleRequest(n instanceof Error?n:new Error(String(n)))}}settleRequest(t){if(clearTimeout(this._timeoutId),t instanceof Error){this.close(),this._rejectRequest?.(t);return}this._resolveRequest?.(t)}};function jn(e){if(e!==void 0)return new URL(e).origin;if(document.referrer)return new URL(document.referrer).origin;throw new Error("[@enbox/browser] Unable to determine the dapp origin: no `dappOrigin` option was provided and `document.referrer` is empty.")}import{TypedRecord as $o}from"@enbox/api";import{BrowserStorage as Yo}from"@enbox/auth/browser";import{DwnInterface as Jo}from"@enbox/agent";import{DateSort as Xo,DwnInterfaceName as Vo,DwnMethodName as Zo}from"@enbox/dwn-sdk-js";export{Mo as AuthManager,To as AuthSession,Un as BrowserConnectHandler,Yo as BrowserStorage,No as CONNECT_DENIED_TOKEN,Oo as ConnectProvider,Ct as DEFAULT_WALLETS,se as DWEB_CONNECT_LOADED_MESSAGE_TYPE,Te as DWEB_CONNECT_PATH,le as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,ce as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,Xo as DateSort,Jo as DwnInterface,Vo as DwnInterfaceName,Zo as DwnMethodName,_o as Enbox,qe as MAX_PIN_ATTEMPTS,F as PopupClientTransport,$ as PopupWindowClosedError,J as RelayConnectCancelledError,$o as TypedRecord,gt as WALLET_WELL_KNOWN_PATH,Wo as WalletConnect,Ke as WalletPostMessageTransport,Gn as activatePolyfills,jt as cacheResponse,Fn as clearDrlCache,on as connectViaPopup,Yn as deactivatePolyfills,ko as defineProtocol,Et as discoverWalletConnectServerUrl,De as encodeQr,Ht as fetchResource,xe as fetchWalletWellKnown,lt as getDwnEndpoints,Bt as handleEvent,So as normalizeProtocolRequests,ne as parseDrlUrl,Ue as probeWalletWellKnown,Ae as qrToSvg,Po as repository,je as runConnectModal,Ie as runRelayConnect};
539
+ `;var Lt=[{name:"Enbox",url:"https://enbox-wallet.pages.dev",description:"Manage your digital identity and data"},{name:"Prism",url:"https://prism-wallet.pages.dev",description:"A clear view into your digital identity"},{name:"Matcha",url:"https://matcha-wallet.pages.dev",description:"A fresh approach to digital identity"},{name:"Onyx",url:"https://onyx-wallet.pages.dev",description:"A refined home for your digital identity"},{name:"Taffy",url:"https://taffy-wallet.pages.dev",description:"A playful take on your digital identity"},{name:"Astoria",url:"https://astoria-wallet.pages.dev",description:"A grand home for your digital identity"}];function Jn(e={}){let{wallets:t=Lt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:p,theme:u}=e;return{async requestAccess(y){return Ye({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:p,timeout:r,theme:u,permissionRequests:y.permissionRequests})}}}import{X25519 as Xn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Vn,ConnectProvider as Zn}from"@enbox/connect";var eo=3e5,to=5e3,Fe=class e{constructor(t){this._requestReceived=!1;this._dappOrigin=t.dappOrigin,this._dappWindow=t.dappWindow,this._recipientPrivateKey=t.recipientPrivateKey,this._requestPromise=new Promise((n,r)=>{this._resolveRequest=n,this._rejectRequest=r}),this._requestPromise.catch(()=>{}),this._messageListener=n=>{this.onMessage(n)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.close(),this._rejectRequest?.(new Error("[@enbox/browser] Timed out waiting for the connect request from the dapp."))},t.timeoutMs)}static async create(t={}){if(typeof window>"u")throw new Error("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let n=t.dappWindow??window.opener;if(!n)throw new Error("[@enbox/browser] No opener window: the DWeb Connect page must be opened as a popup by the dapp.");let r=no(t.dappOrigin),o=await Xn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??eo});return n.postMessage({type:le,walletEpk:i,walletOrigin:globalThis.location.origin},r),s}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(t){this._dappWindow.postMessage({type:X,payload:t},this._dappOrigin),this.close()}async sendResponseAwaitingAck(t,n={}){let r=new Promise(s=>{this._resolveAck=s});this._dappWindow.postMessage({type:X,payload:t},this._dappOrigin);let o=setTimeout(()=>{this._resolveAck?.(!1)},n.timeoutMs??to),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(Vn)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=Ce(t,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===de){this._resolveAck?.(!0);return}if(!(n.type!==ce||this._requestReceived)){if(this._requestReceived=!0,typeof n.jwe!="string"){this.settleRequest(new Error("[@enbox/browser] Connect request message did not carry a ciphertext payload."));return}this.openRequest(n.jwe)}}}async openRequest(t){try{let n=await Zn.openRequest({jwe:t,decryption:{mode:"ecdh-es",recipientPrivateKey:this._recipientPrivateKey,walletOrigin:globalThis.location.origin}});if(n.reply.mode!=="post_message"){this.settleRequest(new Error("[@enbox/browser] Connect request over the popup channel must use the `post_message` reply mode."));return}this.settleRequest(n)}catch(n){this.settleRequest(n instanceof Error?n:new Error(String(n)))}}settleRequest(t){if(clearTimeout(this._timeoutId),t instanceof Error){this.close(),this._rejectRequest?.(t);return}this._resolveRequest?.(t)}};function no(e){if(e!==void 0)return new URL(e).origin;if(document.referrer)return new URL(document.referrer).origin;throw new Error("[@enbox/browser] Unable to determine the dapp origin: no `dappOrigin` option was provided and `document.referrer` is empty.")}import{TypedRecord as ir}from"@enbox/api";import{BrowserStorage as sr}from"@enbox/auth/browser";import{DwnInterface as cr}from"@enbox/agent";import{DateSort as pr,DwnInterfaceName as ur,DwnMethodName as fr}from"@enbox/dwn-sdk-js";export{jo as AuthManager,$o as AuthSession,Jn as BrowserConnectHandler,sr as BrowserStorage,Yo as CONNECT_DENIED_TOKEN,Fo as ConnectProvider,Lt as DEFAULT_WALLETS,de as DWEB_CONNECT_ACK_MESSAGE_TYPE,le as DWEB_CONNECT_LOADED_MESSAGE_TYPE,Ae as DWEB_CONNECT_PATH,ce as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,X as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,pr as DateSort,cr as DwnInterface,ur as DwnInterfaceName,fr as DwnMethodName,qo as Enbox,Ke as MAX_PIN_ATTEMPTS,V as PopupClientTransport,Y as PopupWindowClosedError,Z as RelayConnectCancelledError,ir as TypedRecord,kt as WALLET_WELL_KNOWN_PATH,zo as WalletConnect,Fe as WalletPostMessageTransport,ao as activatePolyfills,Zt as cacheResponse,lo as clearDrlCache,gn as connectViaPopup,so as deactivatePolyfills,Io as defineProtocol,Wt as discoverWalletConnectServerUrl,Be as encodeQr,Vt as fetchResource,ke as fetchWalletWellKnown,ht as getDwnEndpoints,Xt as handleEvent,Ko as normalizeProtocolRequests,oe as parseDrlUrl,$e as probeWalletWellKnown,je as qrToSvg,Ho as repository,Ye as runConnectModal,ze as runRelayConnect};
515
540
  //# sourceMappingURL=browser.mjs.map