@enbox/browser 0.3.42 → 0.3.44

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 (48) hide show
  1. package/dist/browser.mjs +144 -154
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/browser-connect-handler.js +17 -20
  4. package/dist/esm/browser-connect-handler.js.map +1 -1
  5. package/dist/esm/dweb-connect-client.js +1 -1
  6. package/dist/esm/dweb-connect-client.js.map +1 -1
  7. package/dist/esm/index.js +21 -1
  8. package/dist/esm/index.js.map +1 -1
  9. package/dist/esm/relay-connect-runner.js +127 -0
  10. package/dist/esm/relay-connect-runner.js.map +1 -0
  11. package/dist/esm/ui/connect-modal.js +961 -0
  12. package/dist/esm/ui/connect-modal.js.map +1 -0
  13. package/dist/esm/ui/qr.js +468 -0
  14. package/dist/esm/ui/qr.js.map +1 -0
  15. package/dist/esm/ui/wallet-icon.js +55 -0
  16. package/dist/esm/ui/wallet-icon.js.map +1 -0
  17. package/dist/esm/ui/wallet-well-known.js +61 -0
  18. package/dist/esm/ui/wallet-well-known.js.map +1 -0
  19. package/dist/types/browser-connect-handler.d.ts +32 -7
  20. package/dist/types/browser-connect-handler.d.ts.map +1 -1
  21. package/dist/types/dweb-connect-client.d.ts +3 -1
  22. package/dist/types/dweb-connect-client.d.ts.map +1 -1
  23. package/dist/types/index.d.ts +14 -2
  24. package/dist/types/index.d.ts.map +1 -1
  25. package/dist/types/relay-connect-runner.d.ts +76 -0
  26. package/dist/types/relay-connect-runner.d.ts.map +1 -0
  27. package/dist/types/ui/connect-modal.d.ts +108 -0
  28. package/dist/types/ui/connect-modal.d.ts.map +1 -0
  29. package/dist/types/ui/qr.d.ts +55 -0
  30. package/dist/types/ui/qr.d.ts.map +1 -0
  31. package/dist/types/ui/wallet-icon.d.ts +13 -0
  32. package/dist/types/ui/wallet-icon.d.ts.map +1 -0
  33. package/dist/types/ui/wallet-well-known.d.ts +33 -0
  34. package/dist/types/ui/wallet-well-known.d.ts.map +1 -0
  35. package/package.json +9 -6
  36. package/src/browser-connect-handler.ts +51 -21
  37. package/src/dweb-connect-client.ts +1 -1
  38. package/src/index.ts +32 -2
  39. package/src/relay-connect-runner.ts +201 -0
  40. package/src/ui/connect-modal.ts +1167 -0
  41. package/src/ui/qr.ts +549 -0
  42. package/src/ui/wallet-icon.ts +63 -0
  43. package/src/ui/wallet-well-known.ts +57 -0
  44. package/dist/esm/ui/wallet-selector.js +0 -585
  45. package/dist/esm/ui/wallet-selector.js.map +0 -1
  46. package/dist/types/ui/wallet-selector.d.ts +0 -44
  47. package/dist/types/ui/wallet-selector.d.ts.map +0 -1
  48. package/src/ui/wallet-selector.ts +0 -658
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import{AuthManager as rt,AuthSession as it,normalizeProtocolRequests as st,WalletConnect as at}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as ct,ConnectProvider as dt}from"@enbox/connect";import{DidDht as V,DidWeb as X,UniversalResolver as H}from"@enbox/dids";function v(n){let e=n.indexOf("://dweb/");if(e===-1)return null;let t=n.slice(0,e);if(t!=="http"&&t!=="https")return null;let o=n.slice(e+8);if(o.length===0)return null;let r=o.indexOf("/");return r===-1?[o,""]:r===0?null:[o.slice(0,r),o.slice(r+1)]}var M=new H({didResolvers:[V,X]}),j=/^http:/,T=/\/$/,B="drl";async function z(n){let{didDocument:e}=await M.resolve(n),t=e?.service?.find(o=>o.type==="DecentralizedWebNode")?.serviceEndpoint;return t?(Array.isArray(t)?t:[t]).filter(o=>typeof o=="string"&&o.startsWith("http")):[]}async function F(){if(!(typeof caches>"u"))return caches.open(B)}async function Z(n,e,t,o){let r=n.request.url.replace(j,"https:").replace(T,""),i=await F(),a=await i?.match(r);if(a){if(!navigator.onLine)return a;let s=await o?.onCacheCheck?.(n,r);if(s){let l=a.headers.get("dwn-cache-time");if(l&&Date.now()<Number(l)+(Number(s.ttl)||0))return a}}try{if(t)return await ee(n,e,r,t,i,o);{let s=await M.resolve(e);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}}catch(s){return s instanceof Response?s:(console.log(`Error in DID URL fetch: ${s}`),new Response("DID URL fetch error",{status:500}))}}async function ee(n,e,t,o,r,i){let a=await z(e);if(!a?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let s;for(let l of a)try{let c=`${l.replace(T,"")}/${e}/${o}`,d=await fetch(c,{headers:n.request.headers});if(d.ok)return await i?.onCacheCheck?.(n,t)&&r&&te(t,c,d,r),d;console.log(`DWN endpoint error: ${d.status}`),s=new Response("DWeb Node request failed",{status:d.status})}catch(c){console.log(`DWN endpoint error: ${c}`),s=new Response("DWeb Node request failed",{status:500})}return s}async function te(n,e,t,o){try{let r=t.clone(),i=new Headers(r.headers);i.append("dwn-cache-time",Date.now().toString()),i.append("dwn-composed-url",e);let a=new Response(r.body,{headers:i});await o.put(n,a)}catch(r){console.log(`Failed to cache DRL response: ${r}`)}}async function ne(n={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let e=self;e.skipWaiting(),e.addEventListener("activate",t=>{t.waitUntil(e.clients.claim())}),e.addEventListener("fetch",t=>{let o=v(t.request.url);o&&t.respondWith(Z(t,o[0],o[1],n))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let t=n.path||document?.currentScript?.src||import.meta.url;t&&navigator.serviceWorker.register(t,{type:"module"}).catch(o=>{console.error("DWeb networking feature installation failed: ",o)})}}else throw new Error("DWeb networking features are not available for install in this environment")}catch(e){console.error("Error in installing networking features:",e)}}var K=`
1
+ import{Enbox as no,defineProtocol as oo,repository as ro}from"@enbox/api";import{AuthManager as so,AuthSession as ao,normalizeProtocolRequests as lo,WalletConnect as co}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as uo,ConnectProvider as fo}from"@enbox/connect";import{DidDht as yt,DidWeb as Et,UniversalResolver as Ge}from"@enbox/dids";function X(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 be=new Ge({didResolvers:[yt,Et]}),Ye=/^http:/,ce=/\/$/,Fe="drl";async function Je(e){let{didDocument:t}=await be.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 Qe(){if(!(typeof caches>"u"))return caches.open(Fe)}async function xt(e,t,n,r){let o=e.request.url.replace(Ye,"https:").replace(ce,""),i=await Qe(),a=await i?.match(o);if(a){if(!navigator.onLine)return a;let s=await r?.onCacheCheck?.(e,o);if(s){let l=a.headers.get("dwn-cache-time");if(l&&Date.now()<Number(l)+(Number(s.ttl)||0))return a}}try{if(n)return await Ct(e,t,o,n,i,r);{let s=await be.resolve(t);return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json"}})}}catch(s){return s instanceof Response?s:(console.log(`Error in DID URL fetch: ${s}`),new Response("DID URL fetch error",{status:500}))}}async function Ct(e,t,n,r,o,i){let a=await Je(t);if(!a?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let s;for(let l of a)try{let d=`${l.replace(ce,"")}/${t}/${r}`,p=await fetch(d,{headers:e.request.headers});if(p.ok)return await i?.onCacheCheck?.(e,n)&&o&&_t(n,d,p,o),p;console.log(`DWN endpoint error: ${p.status}`),s=new Response("DWeb Node request failed",{status:p.status})}catch(d){console.log(`DWN endpoint error: ${d}`),s=new Response("DWeb Node request failed",{status:500})}return s}async function _t(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 a=new Response(o.body,{headers:i});await r.put(e,a)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function Pt(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=X(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 Xe=`
2
2
  .drl-loading-overlay {
3
3
  position: fixed;
4
4
  inset: 0;
@@ -103,7 +103,7 @@ import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import
103
103
  opacity: 0;
104
104
  }
105
105
  }
106
- `,oe=`
106
+ `,Rt=`
107
107
  <!DOCTYPE html>
108
108
  <html lang='en'>
109
109
  <head>
@@ -119,7 +119,7 @@ import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import
119
119
  font-family: Arial, sans-serif;
120
120
  text-align: center;
121
121
  }
122
- ${K}
122
+ ${Xe}
123
123
  </style>
124
124
  </head>
125
125
  <body>
@@ -132,8 +132,8 @@ import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import
132
132
  </div>
133
133
  </body>
134
134
  </html>
135
- `,k=!1,m=null,E=null;function I(){k||(E=document.createElement("style"),E.innerHTML=`
136
- ${K}
135
+ `,de=!1,q=null,V=null;function Ke(){de||(V=document.createElement("style"),V.innerHTML=`
136
+ ${Xe}
137
137
 
138
138
  .drl-loading-overlay {
139
139
  opacity: 0;
@@ -145,13 +145,13 @@ import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import
145
145
  opacity: 1;
146
146
  pointer-events: all;
147
147
  }
148
- `,document.head.append(E),m=document.createElement("div"),m.classList.add("drl-loading-overlay"),m.innerHTML=`
148
+ `,document.head.append(V),q=document.createElement("div"),q.classList.add("drl-loading-overlay"),q.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
- `,m.lastElementChild.addEventListener("click",S),document.body.prepend(m),k=!0)}function re(){k&&(E?.remove(),E=null,m?.remove(),m=null,k=!1)}function S(){document.documentElement.removeAttribute("drl-link-loading"),P=null}var P=null,W=!1,b=null,y=null;function ie(){W||(b=async n=>{let e=n.target?.closest("a");if(e){let t=e.href,o=v(t);if(o){let r=o[0],i=o[1],a=e.target==="_blank";n.preventDefault();try{let s=null;a?(s=window.open("","_blank"),s&&s.document.write(oe)):(P=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let l=await z(r);if(!l.length)throw new Error("no valid DWN endpoints found");let c=`${l[0].replace(T,"")}/${r}/${i}`;a?s&&!s.closed&&(s.location.href=c):P===i&&(window.location.href=c)}catch{throw P===i&&S(),new Error(`DID endpoint resolution failed for the DRL: ${t}`)}}}},y=async n=>{let e=n.composedPath()[0];if(n.pointerType==="mouse"&&n.button===2||n.pointerType==="touch"&&n.isPrimary){if(g(),e?.src&&v(e.src)){f=e,e.__src__=e.src;let t=e.src.replace(j,"https:").replace(T,""),r=await(await F())?.match(t);if(r){let i=r.headers.get("dwn-composed-url");i&&(e.src=i)}e.addEventListener("pointerup",g,{once:!0})}}else e===f&&g()},document.addEventListener("click",b),document.addEventListener("pointercancel",g),document.addEventListener("pointerdown",y),W=!0)}function se(){W&&(b&&(document.removeEventListener("click",b),b=null),y&&(document.removeEventListener("pointerdown",y),y=null),document.removeEventListener("pointercancel",g),g(),S(),W=!1)}var f=null;async function g(n){n?.type==="pointerup"&&await new Promise(e=>requestAnimationFrame(()=>e())),f&&(f.src=f.__src__,delete f.__src__,f=null)}function De(n={}){n.didResolvers&&(M=new H({didResolvers:n.didResolvers})),n.serviceWorker!==!1&&ne(n),typeof window<"u"&&typeof window.document<"u"&&(n.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",I,{once:!0}):I()),n.links!==!1&&ie())}function qe(){typeof window<"u"&&typeof window.document<"u"&&(se(),re())}async function Ae(){return typeof caches>"u"?!1:caches.delete(B)}import{assertX25519PublicJwk as ae,CONNECT_DENIED_TOKEN as le,ConnectClient as ce}from"@enbox/connect";var D="/dweb-connect",x="enbox-connect-loaded",_="enbox-connect-request",C="enbox-connect-response";function O(n,e,t){if(n.origin!==e||n.source!==t)return;let o=n.data;if(!(typeof o!="object"||o===null))return o}var de=3e5,pe=500,ue="enbox-dweb-connect",me="width=500,height=700,menubar=no,toolbar=no,location=no,status=no";function fe(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var R=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},L=class{constructor(e){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;fe(),this._walletOrigin=new URL(e.walletUrl).origin,this._timeoutMs=e.timeoutMs??de;let t=new URL(D,e.walletUrl).toString(),o=window.open(t,ue,me);if(!o)throw new Error("[@enbox/browser] Popup blocked. Allow popups for this site to connect to a wallet.");this._popup=o,this._walletEpkPromise=new Promise((r,i)=>{this._resolveWalletEpk=r,this._rejectWalletEpk=i}),this._responsePromise=new Promise((r,i)=>{this._resolveResponse=r,this._rejectResponse=i}),this._responsePromise.catch(()=>{}),this._messageListener=r=>{this.onMessage(r)},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()},pe)}async requestProfile(e){return{encryption:{mode:"ecdh-es",walletEpk:await this._walletEpkPromise,walletOrigin:this._walletOrigin},reply:{mode:"post_message"},state:e}}async deliverRequest(e){this._popup.postMessage({type:_,jwe:e},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}onMessage(e){let t=O(e,this._walletOrigin,this._popup);if(t!==void 0){if(t.type===x){this.onLoadedBeacon(t);return}t.type===C&&this.onResponseMessage(t)}}onLoadedBeacon(e){if(this._settled||this._walletEpkReceived)return;let t;try{ae(e.walletEpk),t=e.walletEpk}catch{this.fail(new Error("[@enbox/browser] Wallet loaded beacon did not carry a valid X25519 public key."));return}if(e.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?.(t)}onResponseMessage(e){if(!this._settled){if(typeof e.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?.(e.payload)}}onClosedPoll(){if(!(this._settled||this._popup.closed!==!0)){if(!this._walletEpkReceived){this.fail(new R);return}this._settled=!0,this.cleanup(),this._resolveResponse?.(le)}}fail(e){if(!this._settled){this._settled=!0,this.cleanup();try{this._popup.close()}catch{}this._rejectWalletEpk?.(e),this._rejectResponse?.(e)}}cleanup(){clearTimeout(this._timeoutId),clearInterval(this._closedPollId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}};function ge(){let n=Intl.DateTimeFormat().resolvedOptions(),e=Array.isArray(globalThis.navigator.languages)?globalThis.navigator.languages.filter(t=>typeof t=="string"&&t.length>0):void 0;return{origin:globalThis.location.origin,userAgent:globalThis.navigator.userAgent,platform:globalThis.navigator.platform,language:globalThis.navigator.language,...e&&e.length>0?{languages:e}:{},...n.timeZone?{timezone:n.timeZone}:{}}}async function q(n){let e=new L({walletUrl:n.walletUrl,timeoutMs:n.timeout}),t=new ce({transport:e});try{return await t.connect({appName:n.appName??globalThis.location.host,appIcon:n.appIcon,clientMetadata:ge(),permissionRequests:n.permissionRequests})}catch(o){if(o instanceof R)return;throw o}}var Y="/.well-known/enbox-connect";async function J(n){try{let e=new URL(Y,n).toString(),t=await fetch(e,{signal:AbortSignal.timeout(6e3)});return t.ok?typeof(await t.json())?.connectServerUrl=="string":!1}catch{return!1}}function A(n,e={}){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] Wallet selector is only available in browser environments.");let t=e.validateWalletUrl??J;return new Promise((o,r)=>{let i=document.createElement("div");i.id="enbox-wallet-selector";let a=i.attachShadow({mode:"open"}),s,l=()=>{s!==void 0&&(document.removeEventListener("keydown",s),s=void 0);try{document.body.removeChild(i)}catch{}},c=w=>{l(),o(w)},d=()=>{l(),r(new Error("[@enbox/browser] Wallet selection cancelled."))},p=window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1,N=document.createElement("style");N.textContent=Re(p),a.appendChild(N);let h=document.createElement("div");h.className="overlay";let u=document.createElement("div");u.className="modal",u.appendChild(he(d));let $=n[0];$!==void 0&&u.appendChild(we($,c)),u.appendChild(ve(n,c)),u.appendChild(xe()),u.appendChild(_e(t,c)),h.addEventListener("click",w=>{w.target===h&&d()}),s=w=>{w.key==="Escape"&&d()},document.addEventListener("keydown",s),h.appendChild(u),a.appendChild(h),document.body.appendChild(i),a.querySelector(".wallet-search")?.focus()})}function he(n){let e=document.createElement("div");e.className="header";let t=document.createElement("h2");t.textContent="Connect a wallet";let o=document.createElement("button");return o.className="close-btn",o.setAttribute("aria-label","Close"),o.innerHTML="&times;",o.addEventListener("click",n),e.appendChild(t),e.appendChild(o),e}function we(n,e){let t=document.createElement("button");t.className="quick-connect";let o=document.createElement("span");o.className="quick-bolt",o.textContent="\u26A1";let r=document.createElement("span");r.className="quick-text";let i=document.createElement("span");i.className="quick-label",i.textContent="Quick connect";let a=document.createElement("span");return a.className="quick-sub",a.textContent=`Connect with ${n.name}`,r.appendChild(i),r.appendChild(a),t.appendChild(o),t.appendChild(r),t.addEventListener("click",()=>e(n.url)),t}function ve(n,e){let t=document.createElement("div");t.className="grid-section";let o=document.createElement("input");o.type="search",o.className="wallet-search",o.placeholder="Search wallets\u2026";let r=document.createElement("div");r.className="wallet-grid";let i=document.createElement("div");i.className="grid-empty",i.textContent="No wallets match your search.",i.style.display="none";let a=n.map(s=>{let l=Ee(s,e);return r.appendChild(l),{name:s.name.toLowerCase(),tile:l}});return o.addEventListener("input",()=>{let s=o.value.trim().toLowerCase(),l=0;for(let{name:c,tile:d}of a){let p=c.includes(s);d.style.display=p?"":"none",p&&(l+=1)}i.style.display=l===0?"":"none"}),t.appendChild(o),t.appendChild(r),t.appendChild(i),t}function Ee(n,e){let t=document.createElement("button");t.className="wallet-item",t.title=n.description??n.name,t.appendChild(be(n));let o=document.createElement("span");return o.className="wallet-name",o.textContent=n.name,t.appendChild(o),t.addEventListener("click",()=>e(n.url)),t}function be(n){let e=document.createElement("span");e.className="wallet-icon";let t=document.createElement("span");t.className="wallet-badge",t.textContent=n.name.charAt(0).toUpperCase(),e.appendChild(t);let o=ye(n);if(o.length===0)return e;let r=document.createElement("img");r.className="wallet-img",r.alt="",r.width=40,r.height=40;let i=0;return r.addEventListener("error",()=>{i+=1,i<o.length?r.src=o[i]:r.remove()}),r.src=o[i],e.appendChild(r),e}function ye(n){if(n.icon!==void 0)return[n.icon];let e;try{e=new URL(n.url).origin}catch{return[]}return[`${e}/favicon.svg`,`${e}/favicon.ico`,`${e}/favicon.png`]}function xe(){let n=document.createElement("div");n.className="separator";let e=document.createElement("div");e.className="sep-line";let t=document.createElement("span");t.textContent="or";let o=document.createElement("div");return o.className="sep-line",n.appendChild(e),n.appendChild(t),n.appendChild(o),n}function _e(n,e){let t=document.createElement("div");t.className="custom-section";let o=document.createElement("label");o.className="custom-label",o.textContent="Have a wallet URL?";let r=document.createElement("div");r.className="input-group";let i=document.createElement("input");i.type="url",i.placeholder="https://your-wallet.example",i.className="url-input";let a=document.createElement("button");a.className="go-btn",a.textContent="Connect",a.disabled=!0;let s=document.createElement("div");s.className="url-error",s.style.display="none";let l=!1,c=()=>{l=!1,a.textContent="Connect",s.style.display="none",a.disabled=!G(i.value)},d=async()=>{if(!G(i.value))return;let p=Ce(i.value);if(l){e(p);return}if(a.disabled=!0,a.textContent="Verifying\u2026",s.style.display="none",await n(p)){e(p);return}l=!0,a.disabled=!1,a.textContent="Connect anyway",s.textContent=`Couldn't verify an Enbox wallet at ${p}.`,s.style.display=""};return i.addEventListener("input",c),i.addEventListener("keydown",p=>{p.key==="Enter"&&d()}),a.addEventListener("click",()=>void d()),r.appendChild(i),r.appendChild(a),t.appendChild(o),t.appendChild(r),t.appendChild(s),t}function G(n){try{let e=new URL(n.includes("://")?n:`https://${n}`);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function Ce(n){let e=n.includes("://")?n:`https://${n}`;return new URL(e).origin}function Re(n){let e=n?"#1a1a2e":"#ffffff",t=n?"#e0e0e0":"#1a1a2e",o=n?"#888":"#666",r=n?"#333":"#e0e0e0",i=n?"#16213e":"#f8f9fa",a=n?"#0f3460":"#e9ecef",s=n?"#4a9eff":"#0066cc";return`
154
+ `,q.lastElementChild.addEventListener("click",ve),document.body.prepend(q),de=!0)}function Mt(){de&&(V?.remove(),V=null,q?.remove(),q=null,de=!1)}function ve(){document.documentElement.removeAttribute("drl-link-loading"),le=null}var le=null,pe=!1,Z=null,ee=null;function kt(){pe||(Z=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=X(n);if(r){let o=r[0],i=r[1],a=t.target==="_blank";e.preventDefault();try{let s=null;a?(s=window.open("","_blank"),s&&s.document.write(Rt)):(le=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let l=await Je(o);if(!l.length)throw new Error("no valid DWN endpoints found");let d=`${l[0].replace(ce,"")}/${o}/${i}`;a?s&&!s.closed&&(s.location.href=d):le===i&&(window.location.href=d)}catch{throw le===i&&ve(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},ee=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(z(),t?.src&&X(t.src)){I=t,t.__src__=t.src;let n=t.src.replace(Ye,"https:").replace(ce,""),o=await(await Qe())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",z,{once:!0})}}else t===I&&z()},document.addEventListener("click",Z),document.addEventListener("pointercancel",z),document.addEventListener("pointerdown",ee),pe=!0)}function Tt(){pe&&(Z&&(document.removeEventListener("click",Z),Z=null),ee&&(document.removeEventListener("pointerdown",ee),ee=null),document.removeEventListener("pointercancel",z),z(),ve(),pe=!1)}var I=null;async function z(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),I&&(I.src=I.__src__,delete I.__src__,I=null)}function Pn(e={}){e.didResolvers&&(be=new Ge({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&Pt(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ke,{once:!0}):Ke()),e.links!==!1&&kt())}function Rn(){typeof window<"u"&&typeof window.document<"u"&&(Tt(),Mt())}async function Mn(){return typeof caches>"u"?!1:caches.delete(Fe)}import{ConnectClient as nn}from"@enbox/connect";function Ve(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=St(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 St(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 Wt,CONNECT_DENIED_TOKEN as Nt,ConnectClient as Lt}from"@enbox/connect";var ye="/dweb-connect",te="enbox-connect-loaded",ne="enbox-connect-request",oe="enbox-connect-response";function ue(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var Ot=3e5,Dt=500,Ut="enbox-dweb-connect",At="width=500,height=700,menubar=no,toolbar=no,location=no,status=no";function qt(){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"}},K=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;qt(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??Ot;let n=new URL(ye,t.walletUrl).toString(),r=window.open(n,Ut,At);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()},Dt)}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:ne,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}onMessage(t){let n=ue(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===te){this.onLoadedBeacon(n);return}n.type===oe&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{Wt(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?.(Nt)}}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 fe(){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 It(e){let t=new K({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new Lt({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:fe(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof $)return;throw r}}var tt=[-1,10,16,26,18,24,16,18,22,22,26],nt=[-1,1,1,1,2,2,4,4,4,5,5],ot=[-1,26,44,70,100,134,172,196,242,292,346],$t=0,Ze=10;function et(e){return ot[e]-tt[e]*nt[e]}function Re(e,t){let n=new TextEncoder().encode(e),r=0;for(let u=1;u<=Ze;u++){let f=et(u)*8;if(4+(u<=9?8:16)+n.length*8<=f){r=u;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${Ze}-M capacity).`);let o=[],i=(u,f)=>{for(let R=f-1;R>=0;R--)o.push(u>>>R&1)};i(4,4),i(n.length,r<=9?8:16);for(let u of n)i(u,8);let a=et(r)*8;i(0,Math.min(4,a-o.length)),i(0,(8-o.length%8)%8);let s=[236,17];for(let u=0;o.length<a;u++)i(s[u%2],8);let l=new Uint8Array(a/8);for(let u=0;u<o.length;u++)l[u>>3]|=o[u]<<7-(u&7);let d=Bt(l,r),p=17+4*r,h=Array.from({length:p},()=>new Array(p).fill(!1)),P=Array.from({length:p},()=>new Array(p).fill(!1));Kt(h,P,r),Ft(h,P,d);let y=t??-1;if(y===-1){let u=1/0;for(let f=0;f<8;f++){xe(h,P,f),Pe(h,P,f);let R=Jt(h);R<u&&(u=R,y=f),xe(h,P,f)}}return xe(h,P,y),Pe(h,P,y),{size:p,modules:h,version:r,mask:y}}function Bt(e,t){let n=nt[t],r=tt[t],o=ot[t],i=n-o%n,a=Math.floor(o/n),s=[],l=[],d=jt(r),p=0;for(let u=0;u<n;u++){let f=a-r+(u<i?0:1),R=e.slice(p,p+f);p+=f,s.push(R),l.push(Ht(R,d))}let h=new Uint8Array(o),P=0,y=a-r+1;for(let u=0;u<y;u++)for(let f=0;f<n;f++)u<s[f].length&&(h[P++]=s[f][u]);for(let u=0;u<r;u++)for(let f=0;f<n;f++)h[P++]=l[f][u];return h}function _e(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 jt(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]=_e(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=_e(n,2)}return t}function Ht(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]^=_e(t[i],o)}return n}var zt=[[],[],[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 Kt(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);Ee(e,t,3,3),Ee(e,t,r-4,3),Ee(e,t,3,r-4);let o=zt[n];for(let i=0;i<o.length;i++)for(let a=0;a<o.length;a++)i===0&&a===0||i===0&&a===o.length-1||i===o.length-1&&a===0||Gt(e,t,o[i],o[a]);Pe(e,t,0),T(e,t,8,r-8,!0),n>=7&&Yt(e,t,n)}function Ee(e,t,n,r){let o=e.length;for(let i=-4;i<=4;i++)for(let a=-4;a<=4;a++){let s=n+a,l=r+i;if(s<0||s>=o||l<0||l>=o)continue;let d=Math.max(Math.abs(a),Math.abs(i));T(e,t,s,l,d!==2&&d!==4)}}function Gt(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 Pe(e,t,n){let r=e.length,o=$t<<3|n,i=o;for(let s=0;s<10;s++)i=i<<1^(i>>>9)*1335;let a=(o<<10|i)^21522;for(let s=0;s<=5;s++)T(e,t,8,s,(a>>>s&1)!==0);T(e,t,8,7,(a>>>6&1)!==0),T(e,t,8,8,(a>>>7&1)!==0),T(e,t,7,8,(a>>>8&1)!==0);for(let s=9;s<15;s++)T(e,t,14-s,8,(a>>>s&1)!==0);for(let s=0;s<8;s++)T(e,t,r-1-s,8,(a>>>s&1)!==0);for(let s=8;s<15;s++)T(e,t,8,r-15+s,(a>>>s&1)!==0)}function Yt(e,t,n){let r=e.length,o=n;for(let a=0;a<12;a++)o=o<<1^(o>>>11)*7973;let i=n<<12|o;for(let a=0;a<18;a++){let s=(i>>>a&1)!==0,l=r-11+a%3,d=Math.floor(a/3);T(e,t,l,d,s),T(e,t,d,l,s)}}function Ft(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){i===6&&(i=5);for(let a=0;a<r;a++)for(let s=0;s<2;s++){let l=i-s,p=(i+1&2)===0?r-1-a:a;!t[p][l]&&o<n.length*8&&(e[p][l]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function xe(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 a;switch(n){case 0:a=(i+o)%2===0;break;case 1:a=o%2===0;break;case 2:a=i%3===0;break;case 3:a=(i+o)%3===0;break;case 4:a=(Math.floor(i/3)+Math.floor(o/2))%2===0;break;case 5:a=i*o%2+i*o%3===0;break;case 6:a=(i*o%2+i*o%3)%2===0;break;default:a=((i+o)%2+i*o%3)%2===0;break}a&&(e[o][i]=!e[o][i])}}function Jt(e){let t=e.length,n=0;for(let s=0;s<t;s++){let l=!1,d=0;for(let p=0;p<t;p++)p===0||e[s][p]!==l?(l=e[s][p],d=1):(d++,d===5?n+=3:d>5&&(n+=1))}for(let s=0;s<t;s++){let l=!1,d=0;for(let p=0;p<t;p++)p===0||e[p][s]!==l?(l=e[p][s],d=1):(d++,d===5?n+=3:d>5&&(n+=1))}for(let s=0;s<t-1;s++)for(let l=0;l<t-1;l++){let d=e[s][l];d===e[s][l+1]&&d===e[s+1][l]&&d===e[s+1][l+1]&&(n+=3)}let r=(s,l)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((y,u)=>s[l+u]===y))return 0;let h=l>=4&&s.slice(l-4,l).every(y=>!y),P=l+11<=s.length&&s.slice(l+7,l+11).every(y=>!y);return(h?40:0)+(P?40:0)};for(let s=0;s<t;s++){let l=e[s],d=e.map(p=>p[s]);for(let p=0;p+7<=t;p++)n+=r(l,p),n+=r(d,p)}let o=0;for(let s of e)for(let l of s)l&&o++;let i=t*t,a=Math.ceil(Math.abs(o*20-i*10)/i)-1;return n+=a*10,n}var Ce="http://www.w3.org/2000/svg";function Me(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,a="";for(let p=0;p<e.size;p++)for(let h=0;h<e.size;h++)e.modules[p][h]&&(a+=`M${h+o} ${p+o}h1v1h-1z`);let s=document.createElementNS(Ce,"svg");s.setAttribute("viewBox",`0 0 ${i} ${i}`),s.setAttribute("shape-rendering","crispEdges"),s.setAttribute("role","img");let l=document.createElementNS(Ce,"rect");l.setAttribute("width",String(i)),l.setAttribute("height",String(i)),l.setAttribute("fill",r),s.appendChild(l);let d=document.createElementNS(Ce,"path");return d.setAttribute("d",a),d.setAttribute("fill",n),s.appendChild(d),s}var rt="/.well-known/enbox-connect";async function me(e){try{let t=new URL(rt,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 ke(e){return await me(e)!==void 0}import{DidJwk as Qt}from"@enbox/dids";import{X25519 as Xt}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Vt,openResponse as Zt,randomToken as it,RelayClientTransport as en,sealRequest as tn}from"@enbox/connect";var Te=6,G=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};async function Se(e){let n=(e.createTransport??(f=>new en(f)))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs}),r=await Qt.create(),o=await Xt.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},a=it(),s=it(),l=await n.requestProfile(s),d={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,supportedDidMethods:["did:dht","did:jwk"],nonce:a,state:s,responseKey:i,reply:l.reply},p=await tn({request:d,signer:r,encryption:l.encryption}),h=await n.deliverRequest(p);h!==void 0&&e.onWalletUriReady(h);let y=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(y===Vt)return;let u;for(let f=1;f<=Te;f++){let R=await(e.cancelled===void 0?e.requestPin(f,u):Promise.race([e.requestPin(f,u),e.cancelled]));try{let M=await Zt({jwe:y,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:a,state:s},pin:R});if(M.delegatePortableDid===void 0)throw new Error("Connect: wallet response omitted `delegatePortableDid`.");return{delegatePortableDid:M.delegatePortableDid,delegateGrants:M.delegateGrants,connectedDid:M.providerDid,sessionRevocations:M.sessionRevocations}}catch(M){let S=M instanceof Error?M:new Error(String(M));if(S.message.startsWith("Connect:"))throw S;u=S}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Te} attempts.`)}var st="enbox:connect:lastChoice",on=3e4,rn=1e4,he=4;async function at(e){return(await me(e))?.connectServerUrl}async function sn(e){let t=new K({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new nn({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:fe(),permissionRequests:e.permissionRequests})}function an(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function ln(){return{runRelay:Se,runPopup:sn,discoverConnectServerUrl:at,validateWalletUrl:ke,isMobile:an,storage:typeof localStorage>"u"?void 0:localStorage}}function cn(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 dn(e,t){try{e?.setItem(st,JSON.stringify(t))}catch{}}function pn(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new G))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Ne(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");let t={...ln(),...e.deps},n=e.wallets??[],r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",a=t.isMobile(),s=r?cn(t.storage):void 0,l=e.walletUrl!==void 0,d=e.walletUrl??(s!==void 0&&(l||un(n,s.walletUrl))?s.walletUrl:void 0)??n[0]?.url,p=e.preferredMethod??s?.method??"phone";return new Promise((h,P)=>{let y=document.createElement("div");y.id="enbox-connect-modal";let u=y.attachShadow({mode:"open"}),f=window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1,R=document.createElement("style");R.textContent=hn(f),u.appendChild(R);let M=document.createElement("div");M.className="overlay";let S=document.createElement("div");S.className="modal",S.setAttribute("role","dialog"),S.setAttribute("aria-modal","true"),S.setAttribute("aria-label",`Connect to ${o}`);let O=!1,Y,U,ge=!1,F,Oe=new Map,ct=()=>{Y?.cancel(),clearTimeout(U),document.removeEventListener("keydown",Be);try{document.body.removeChild(y)}catch{}},ie=c=>{O||(O=!0,ct(),c())},De=c=>{r&&dn(t.storage,{method:p,walletUrl:d??""}),ut(),setTimeout(()=>ie(()=>h(c)),1200)},we=()=>ie(()=>P(new Error("[@enbox/browser] Connect cancelled.")));S.appendChild(fn(o,e.appIcon,we));let A=document.createElement("div");A.className="stage",A.setAttribute("aria-live","polite"),S.appendChild(A);let B=document.createElement("div");B.className="footer",S.appendChild(B);let W=(...c)=>{A.replaceChildren(...c),A.classList.remove("fade-in"),A.offsetWidth,A.classList.add("fade-in")},Ue=c=>{W(x("div","spinner"),x("p","stage-caption",c))},dt=c=>{if(a){let w=document.createElement("a");w.className="deep-link",w.href=c.walletUri,w.textContent="Continue in your wallet",W(w,x("p","stage-caption","Your wallet opens to approve this connection."),x("p","stage-subline","Come back here when you\u2019re done."));return}let m=document.createElement("div");m.className="qr-box",m.replaceChildren(Me(Re(c.walletUri),{dark:f?"#e8e8f0":"#14141f",light:"transparent",quietZone:2})),W(m,x("p","stage-caption","Scan with your phone\u2019s camera"),x("p","stage-subline","Your wallet stays on your phone, so you can approve things anywhere."))},pt=(c,m)=>new Promise(w=>{F=w;let b=document.createElement("div");b.className="pin-row",m!==void 0&&b.classList.add("shake");let E=[];for(let C=0;C<he;C++){let g=document.createElement("input");g.className="pin-input",g.type="text",g.inputMode="numeric",g.maxLength=1,g.setAttribute("aria-label",`Code digit ${C+1}`),E.push(g),b.appendChild(g)}let L=()=>{let C=E.map(g=>g.value).join("");if(C.length===he&&F!==void 0){let g=F;F=void 0,Ue("Checking the code\u2026"),g(C)}};E.forEach((C,g)=>{C.addEventListener("input",()=>{C.value=C.value.replace(/\D/g,"").slice(0,1),C.value!==""&&g+1<E.length&&E[g+1].focus(),L()}),C.addEventListener("keydown",k=>{k.key==="Backspace"&&C.value===""&&g>0&&E[g-1].focus()}),C.addEventListener("paste",k=>{let N=(k.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,he);N.length!==0&&(k.preventDefault(),N.split("").forEach((J,Q)=>{E[Q]!==void 0&&(E[Q].value=J)}),E[Math.min(N.length,he)-1]?.focus(),L())})}),W(x("p","stage-caption","Enter the code shown on your phone"),b,...m!==void 0?[x("p","stage-error","That code doesn\u2019t match \u2014 check your phone.")]:[x("p","stage-subline",c===1?"Phone connected.":"")]),E[0].focus()}),ut=()=>{let c=x("div","check");c.textContent="\u2713",W(c,x("p","stage-caption","You\u2019re connected."))},Ae=()=>{W(x("p","stage-caption","No problem \u2014 nothing was shared."),re("Start over",()=>{j()}),We("Close",()=>ie(()=>h(void 0))))},se=(c,m)=>{W(x("p","stage-caption",c),re("Start over",()=>{j()}),We("Close",()=>ie(()=>P(m??new Error(`[@enbox/browser] ${c}`)))))},ft=()=>{W(x("p","stage-caption","This wallet can\u2019t connect by phone here."),x("p","stage-subline","You can continue in this browser instead."),re("Use this browser",()=>{ae()}))},mt=()=>{W(x("p","stage-caption","Connect with a wallet in this browser"),x("p","stage-subline","Your wallet opens in a small window to approve this connection."),re("Open wallet window",()=>{ae()}))},ht=()=>{W(x("div","spinner"),x("p","stage-caption","Finish in the wallet window"),x("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},qe=c=>{W(x("p","stage-caption",c?"Your browser blocked the wallet window.":"The wallet window was closed."),re(c?"Open it now":"Reopen window",()=>{ae()}),...a?[]:[We("Use your phone instead",()=>{$e("phone")})])},gt=async c=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let m=Oe.get(c);return m===void 0&&(m=t.discoverConnectServerUrl(c),Oe.set(c,m)),m},wt=c=>{clearTimeout(U);let m=Math.max(rn,c*1e3-on);U=setTimeout(()=>{!O&&F===void 0&&p==="phone"&&Ie()},m)},Ie=async()=>{if(Y?.cancel(),clearTimeout(U),d===void 0){se("No wallet is configured.");return}p="phone",H(),Ue("Getting things ready\u2026");let c=new URL(d).origin,m=await gt(c);if(m===void 0){ft();return}let w=pn();Y=w;try{let b=await t.runRelay({connectServerUrl:m,walletUri:new URL(i,c).toString(),appName:o,appIcon:e.appIcon,clientMetadata:fe(),permissionRequests:e.permissionRequests,timeoutMs:e.timeout,cancelled:w.cancelled,onWalletUriReady:E=>{w.active&&!O&&(dt(E),wt(E.expiresIn))},requestPin:(E,L)=>(clearTimeout(U),pt(E,L))});if(!w.active||O)return;b===void 0?Ae():De(b)}catch(b){if(!w.active||O||b instanceof G)return;let E=b instanceof Error?b:new Error(String(b));se(/timed out/i.test(E.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",E)}},ae=()=>{if(Y?.cancel(),clearTimeout(U),d===void 0){se("No wallet is configured.");return}if(ge)return;p="browser",H();let c;try{c=t.runPopup({walletUrl:d,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout})}catch(m){let w=m instanceof Error&&/popup blocked/i.test(m.message);qe(w);return}ge=!0,ht(),c.then(m=>{O||(m===void 0?Ae():De(m))}).catch(m=>{if(O)return;if(m instanceof $){qe(!1);return}let w=m instanceof Error?m:new Error(String(m));se(/timed out/i.test(w.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",w)}).finally(()=>{ge=!1})},j=async()=>{p==="browser"?(Y?.cancel(),clearTimeout(U),H(),mt()):await Ie()},$e=async c=>{p=c,await j()},H=()=>{if(B.replaceChildren(),p==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="No phone handy? Use this browser \u2192",c.addEventListener("click",()=>{ae()}),B.appendChild(c)}else if(!a){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="Use your phone instead \u2192",c.addEventListener("click",()=>{$e("phone")}),B.appendChild(c)}!l&&n.length>0&&B.appendChild(bt())},bt=()=>{let c=document.createElement("div");c.className="wallet-switcher";let m=n.find(v=>v.url===d),w=document.createElement("button");w.className="footer-link wallet-toggle",w.setAttribute("aria-expanded","false"),w.textContent=`Wallet: ${m?.name??d??"Choose"} \u25BE`;let b=document.createElement("div");b.className="wallet-panel",b.hidden=!0;let E=[],L=document.createElement("div");if(L.className="wallet-empty",L.textContent="No wallets match your search.",L.hidden=!0,n.length>5){let v=document.createElement("input");v.type="search",v.className="wallet-search",v.placeholder="Search wallets\u2026",v.addEventListener("input",()=>{let _=v.value.trim().toLowerCase(),D=0;for(let{wallet:He,el:vt}of E){let ze=_===""||He.name.toLowerCase().includes(_)||He.url.toLowerCase().includes(_);vt.hidden=!ze,ze&&(D+=1)}L.hidden=D>0}),b.appendChild(v)}for(let v of n){let _=document.createElement("button");_.className="wallet-row",_.appendChild(Ve(v));let D=document.createElement("span");D.className="wallet-row-name",D.textContent=v.name,_.appendChild(D),v.url===d&&_.classList.add("selected"),_.addEventListener("click",()=>{d=v.url,H(),j()}),E.push({wallet:v,el:_}),b.appendChild(_)}b.appendChild(L);let C=document.createElement("div");C.className="wallet-custom";let g=document.createElement("input");g.className="url-input",g.type="url",g.placeholder="https://your-wallet.example";let k=document.createElement("button");k.className="url-go",k.textContent="Use";let N=document.createElement("div");N.className="url-error",N.hidden=!0;let J=!1,Q=v=>{d=v,H(),j()},je=async()=>{let v=g.value.trim();if(v==="")return;let _;try{_=new URL(v.includes("://")?v:`https://${v}`).origin}catch{g.classList.add("invalid");return}if(J){Q(_);return}k.disabled=!0,k.textContent="Checking\u2026",N.hidden=!0;let D=await t.validateWalletUrl(_);if(k.disabled=!1,D){k.textContent="Use",Q(_);return}J=!0,k.textContent="Use anyway",g.classList.add("invalid"),N.textContent=`Couldn't verify a wallet at ${_}.`,N.hidden=!1};return g.addEventListener("input",()=>{J=!1,k.textContent="Use",g.classList.remove("invalid"),N.hidden=!0}),g.addEventListener("keydown",v=>{v.key==="Enter"&&je()}),k.addEventListener("click",()=>{je()}),C.appendChild(g),C.appendChild(k),b.appendChild(C),b.appendChild(N),w.addEventListener("click",()=>{b.hidden=!b.hidden,w.setAttribute("aria-expanded",b.hidden?"false":"true")}),c.appendChild(w),c.appendChild(b),c};M.addEventListener("click",c=>{c.target===M&&we()});let Be=c=>{if(c.key==="Escape"){we();return}c.key==="Tab"&&mn(u,c)};document.addEventListener("keydown",Be),M.appendChild(S),u.appendChild(M),document.body.appendChild(y),H(),j()})}function un(e,t){return e.some(n=>n.url===t)}function x(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function re(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function We(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function fn(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 s=document.createElement("img");s.className="header-icon",s.src=t,s.alt="",s.width=24,s.height=24,s.addEventListener("error",()=>s.remove()),o.appendChild(s)}let i=document.createElement("h2");i.textContent=`Connect to ${e}`,o.appendChild(i);let a=document.createElement("button");return a.className="close-btn",a.setAttribute("aria-label","Close"),a.textContent="\xD7",a.addEventListener("click",n),r.appendChild(o),r.appendChild(a),r}function mn(e,t){let n=Array.from(e.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')).filter(a=>!a.hasAttribute("disabled")&&a.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())}function hn(e){let t=e?"#1a1a2e":"#ffffff",n=e?"#e0e0e0":"#1a1a2e",r=e?"#888":"#666",o=e?"#333":"#e0e0e0",i=e?"#16213e":"#f8f9fa",a=e?"#4a9eff":"#0066cc",s=e?"rgba(74, 158, 255, 0.16)":"rgba(0, 102, 204, 0.1)",l=e?"#ff6b6b":"#c0392b";return`
155
155
  * { box-sizing: border-box; margin: 0; padding: 0; }
156
156
 
157
157
  .overlay {
@@ -166,206 +166,196 @@ import{Enbox as et,defineProtocol as tt,repository as nt}from"@enbox/api";import
166
166
  animation: fadeIn 0.15s ease-out;
167
167
  }
168
168
 
169
- @keyframes fadeIn {
170
- from { opacity: 0; }
171
- to { opacity: 1; }
172
- }
173
-
174
- @keyframes slideUp {
175
- from { transform: translateY(20px); opacity: 0; }
176
- to { transform: translateY(0); opacity: 1; }
177
- }
169
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
170
+ @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
171
+ @keyframes stageIn { from { opacity: 0; } to { opacity: 1; } }
172
+ @keyframes shake {
173
+ 0%, 100% { transform: translateX(0); }
174
+ 20%, 60% { transform: translateX(-6px); }
175
+ 40%, 80% { transform: translateX(6px); }
176
+ }
177
+ @keyframes spin { to { transform: rotate(360deg); } }
178
178
 
179
179
  .modal {
180
- background: ${e};
181
- color: ${t};
180
+ background: ${t};
181
+ color: ${n};
182
182
  border-radius: 16px;
183
- width: 420px;
183
+ width: 400px;
184
184
  max-width: 92vw;
185
- max-height: 86vh;
185
+ max-height: 88vh;
186
186
  overflow-y: auto;
187
- padding: 24px;
187
+ padding: 20px 24px 16px;
188
188
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
189
189
  animation: slideUp 0.2s ease-out;
190
- }
191
-
192
- .header {
193
190
  display: flex;
194
- justify-content: space-between;
195
- align-items: center;
196
- margin-bottom: 18px;
191
+ flex-direction: column;
197
192
  }
198
193
 
199
- h2 { font-size: 18px; font-weight: 600; }
194
+ .header { display: flex; justify-content: space-between; align-items: center; }
195
+ .header-identity { display: flex; align-items: center; gap: 10px; min-width: 0; }
196
+ .header-icon { border-radius: 6px; }
197
+ h2 { font-size: 16px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
200
198
 
201
199
  .close-btn {
202
- background: none;
203
- border: none;
204
- font-size: 24px;
205
- cursor: pointer;
206
- color: ${o};
207
- padding: 4px 8px;
208
- border-radius: 8px;
209
- line-height: 1;
200
+ background: none; border: none; font-size: 24px; cursor: pointer;
201
+ color: ${r}; padding: 4px 8px; border-radius: 8px; line-height: 1;
210
202
  }
211
- .close-btn:hover { color: ${t}; background: ${i}; }
203
+ .close-btn:hover { color: ${n}; background: ${i}; }
212
204
 
213
- .quick-connect {
205
+ .stage {
206
+ min-height: 300px;
214
207
  display: flex;
208
+ flex-direction: column;
215
209
  align-items: center;
210
+ justify-content: center;
216
211
  gap: 12px;
212
+ text-align: center;
213
+ padding: 16px 0;
214
+ }
215
+ .stage.fade-in > * { animation: stageIn 0.15s ease-out; }
216
+
217
+ .qr-box {
218
+ width: 216px;
219
+ height: 216px;
220
+ padding: 12px;
221
+ border-radius: 12px;
222
+ background: ${e?"#10192e":"#ffffff"};
223
+ border: 1px solid ${o};
224
+ }
225
+ .qr-box svg { width: 100%; height: 100%; display: block; }
226
+
227
+ .stage-caption { font-size: 15px; font-weight: 600; }
228
+ .stage-subline { font-size: 13px; color: ${r}; max-width: 300px; line-height: 1.45; }
229
+ .stage-error { font-size: 13px; color: ${l}; }
230
+
231
+ .deep-link {
232
+ display: block;
217
233
  width: 100%;
218
- text-align: left;
219
234
  padding: 14px 16px;
220
- margin-bottom: 18px;
221
- border: none;
222
235
  border-radius: 12px;
223
- cursor: pointer;
236
+ background: ${a};
224
237
  color: #fff;
225
- background: linear-gradient(135deg, ${s}, ${n?"#7b5cff":"#5b8def"});
226
- transition: filter 0.15s;
238
+ font-weight: 600;
239
+ font-size: 15px;
240
+ text-decoration: none;
227
241
  }
228
- .quick-connect:hover { filter: brightness(1.08); }
229
- .quick-bolt { font-size: 22px; line-height: 1; }
230
- .quick-text { display: flex; flex-direction: column; gap: 2px; }
231
- .quick-label { font-weight: 600; font-size: 15px; }
232
- .quick-sub { font-size: 12px; opacity: 0.85; }
233
242
 
234
- .wallet-search {
235
- width: 100%;
236
- padding: 10px 14px;
237
- margin-bottom: 12px;
238
- border: 1px solid ${r};
239
- border-radius: 10px;
240
- font-size: 14px;
243
+ .pin-row { display: flex; gap: 10px; }
244
+ .pin-row.shake { animation: shake 0.4s ease-in-out; }
245
+ .pin-input {
246
+ width: 48px; height: 56px;
247
+ text-align: center;
248
+ font-size: 24px; font-weight: 600;
249
+ color: ${n};
241
250
  background: ${i};
242
- color: ${t};
251
+ border: 1px solid ${o};
252
+ border-radius: 10px;
243
253
  outline: none;
244
254
  }
245
- .wallet-search:focus { border-color: ${s}; }
246
- .wallet-search::placeholder { color: ${o}; }
255
+ .pin-input:focus { border-color: ${a}; }
247
256
 
248
- .wallet-grid {
249
- display: grid;
250
- grid-template-columns: repeat(3, 1fr);
251
- gap: 10px;
252
- max-height: 216px;
253
- overflow-y: auto;
254
- padding: 2px;
257
+ .check {
258
+ width: 56px; height: 56px;
259
+ display: flex; align-items: center; justify-content: center;
260
+ border-radius: 50%;
261
+ background: ${e?"#43d17c":"#1e9e5a"};
262
+ color: #fff;
263
+ font-size: 28px;
255
264
  }
256
265
 
257
- .wallet-item {
258
- display: flex;
259
- flex-direction: column;
260
- align-items: center;
261
- justify-content: center;
262
- gap: 8px;
263
- padding: 14px 8px;
264
- background: ${i};
265
- border: 1px solid ${r};
266
- border-radius: 12px;
267
- cursor: pointer;
268
- color: ${t};
269
- transition: background 0.15s, border-color 0.15s;
266
+ .spinner {
267
+ width: 32px; height: 32px;
268
+ border-radius: 50%;
269
+ border: 3px solid ${o};
270
+ border-top-color: ${a};
271
+ animation: spin 0.8s linear infinite;
270
272
  }
271
- .wallet-item:hover { background: ${a}; border-color: ${s}; }
272
273
 
273
- .wallet-icon {
274
- position: relative;
275
- width: 40px;
276
- height: 40px;
277
- display: flex;
278
- align-items: center;
279
- justify-content: center;
280
- }
281
- .wallet-badge {
282
- position: absolute;
283
- inset: 0;
284
- display: flex;
285
- align-items: center;
286
- justify-content: center;
274
+ .stage-btn {
275
+ padding: 10px 20px;
276
+ border: none;
287
277
  border-radius: 10px;
288
278
  background: ${a};
289
- color: ${t};
290
- font-size: 18px;
291
- font-weight: 600;
292
- }
293
- .wallet-img {
294
- position: relative;
295
- width: 40px;
296
- height: 40px;
297
- border-radius: 10px;
298
- object-fit: cover;
299
- background: ${e};
300
- }
301
-
302
- .wallet-name {
303
- font-size: 13px;
279
+ color: #fff;
280
+ font-size: 14px;
304
281
  font-weight: 500;
305
- max-width: 100%;
306
- overflow: hidden;
307
- text-overflow: ellipsis;
308
- white-space: nowrap;
309
- }
310
-
311
- .grid-empty {
312
- grid-column: 1 / -1;
313
- padding: 16px;
314
- text-align: center;
315
- color: ${o};
316
- font-size: 13px;
282
+ cursor: pointer;
317
283
  }
284
+ .stage-btn:hover { filter: brightness(1.1); }
318
285
 
319
- .separator {
286
+ .footer {
287
+ border-top: 1px solid ${o};
288
+ padding-top: 10px;
320
289
  display: flex;
290
+ flex-direction: column;
291
+ gap: 6px;
321
292
  align-items: center;
322
- gap: 12px;
323
- margin: 20px 0;
324
- color: ${o};
325
- font-size: 13px;
326
293
  }
327
- .sep-line { flex: 1; height: 1px; background: ${r}; }
328
294
 
329
- .custom-label {
330
- display: block;
295
+ .footer-link {
296
+ background: none;
297
+ border: none;
298
+ color: ${r};
331
299
  font-size: 13px;
332
- color: ${o};
333
- margin-bottom: 8px;
300
+ cursor: pointer;
301
+ padding: 4px 8px;
302
+ border-radius: 8px;
334
303
  }
304
+ .footer-link:hover { color: ${n}; background: ${i}; }
305
+ .method-link { color: ${a}; }
335
306
 
336
- .input-group { display: flex; gap: 8px; }
307
+ .wallet-switcher { width: 100%; display: flex; flex-direction: column; align-items: center; }
308
+ .wallet-panel { width: 100%; padding: 6px 0; display: flex; flex-direction: column; gap: 4px; }
309
+ .wallet-row {
310
+ width: 100%;
311
+ text-align: left;
312
+ padding: 8px 12px;
313
+ background: ${i};
314
+ border: 1px solid ${o};
315
+ border-radius: 10px;
316
+ color: ${n};
317
+ font-size: 13px;
318
+ cursor: pointer;
319
+ }
320
+ .wallet-row:hover, .wallet-row.selected { border-color: ${a}; }
337
321
 
322
+ .wallet-icon { position: relative; width: 28px; height: 28px; flex-shrink: 0; display: inline-flex; }
323
+ .wallet-badge {
324
+ width: 28px; height: 28px; border-radius: 8px; display: inline-flex;
325
+ align-items: center; justify-content: center; font-size: 13px;
326
+ font-weight: 600; background: ${s}; color: ${a};
327
+ }
328
+ .wallet-img { position: absolute; inset: 0; width: 28px; height: 28px; border-radius: 8px; object-fit: cover; }
329
+ .wallet-row-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
330
+ .wallet-search {
331
+ width: 100%; box-sizing: border-box; padding: 8px 10px; margin-bottom: 4px;
332
+ border-radius: 8px; border: 1px solid ${o}; background: transparent;
333
+ color: inherit; font: inherit;
334
+ }
335
+ .wallet-search:focus { outline: none; border-color: ${a}; }
336
+ .wallet-empty { padding: 8px 10px; font-size: 12px; opacity: 0.7; }
337
+ .url-error { padding: 4px 2px 0; font-size: 12px; color: ${l}; }
338
+ .wallet-custom { display: flex; gap: 6px; margin-top: 4px; }
338
339
  .url-input {
339
340
  flex: 1;
340
- padding: 10px 14px;
341
- border: 1px solid ${r};
341
+ padding: 8px 12px;
342
+ border: 1px solid ${o};
342
343
  border-radius: 10px;
343
- font-size: 14px;
344
+ font-size: 13px;
344
345
  background: ${i};
345
- color: ${t};
346
+ color: ${n};
346
347
  outline: none;
347
348
  }
348
- .url-input:focus { border-color: ${s}; }
349
- .url-input::placeholder { color: ${o}; }
350
-
351
- .go-btn {
352
- padding: 10px 18px;
349
+ .url-input:focus { border-color: ${a}; }
350
+ .url-input.invalid { border-color: ${l}; }
351
+ .url-go {
352
+ padding: 8px 14px;
353
353
  border: none;
354
354
  border-radius: 10px;
355
- background: ${s};
355
+ background: ${a};
356
356
  color: #fff;
357
- font-size: 14px;
358
- font-weight: 500;
357
+ font-size: 13px;
359
358
  cursor: pointer;
360
- white-space: nowrap;
361
- }
362
- .go-btn:disabled { opacity: 0.4; cursor: not-allowed; }
363
- .go-btn:not(:disabled):hover { filter: brightness(1.1); }
364
-
365
- .url-error {
366
- margin-top: 8px;
367
- font-size: 12px;
368
- color: ${n?"#ff6b6b":"#c0392b"};
369
359
  }
370
- `}var Q=[{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"}];function Pe(n={}){let{wallets:e=Q,walletUrl:t,timeout:o,appName:r,appIcon:i}=n;return{async requestAccess(a){let s=t;return s||(s=await A(e)),q({walletUrl:s,permissionRequests:a.permissionRequests,timeout:o,appName:r,appIcon:i})}}}import{X25519 as Te}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as ke,ConnectProvider as We}from"@enbox/connect";var Oe=3e5,U=class n{constructor(e){this._requestReceived=!1;this._dappOrigin=e.dappOrigin,this._dappWindow=e.dappWindow,this._recipientPrivateKey=e.recipientPrivateKey,this._requestPromise=new Promise((t,o)=>{this._resolveRequest=t,this._rejectRequest=o}),this._requestPromise.catch(()=>{}),this._messageListener=t=>{this.onMessage(t)},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."))},e.timeoutMs)}static async create(e={}){if(typeof window>"u")throw new Error("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let t=e.dappWindow??window.opener;if(!t)throw new Error("[@enbox/browser] No opener window: the DWeb Connect page must be opened as a popup by the dapp.");let o=Le(e.dappOrigin),r=await Te.generateKey(),i={kty:"OKP",crv:"X25519",x:r.x},a=new n({dappOrigin:o,dappWindow:t,recipientPrivateKey:r,timeoutMs:e.timeoutMs??Oe});return t.postMessage({type:x,walletEpk:i,walletOrigin:globalThis.location.origin},o),a}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(e){this._dappWindow.postMessage({type:C,payload:e},this._dappOrigin),this.close()}deny(){this.sendResponse(ke)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(e){let t=O(e,this._dappOrigin,this._dappWindow);if(t!==void 0&&!(t.type!==_||this._requestReceived)){if(this._requestReceived=!0,typeof t.jwe!="string"){this.settleRequest(new Error("[@enbox/browser] Connect request message did not carry a ciphertext payload."));return}this.openRequest(t.jwe)}}async openRequest(e){try{let t=await We.openRequest({jwe:e,decryption:{mode:"ecdh-es",recipientPrivateKey:this._recipientPrivateKey,walletOrigin:globalThis.location.origin}});if(t.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(t)}catch(t){this.settleRequest(t instanceof Error?t:new Error(String(t)))}}settleRequest(e){if(clearTimeout(this._timeoutId),e instanceof Error){this.close(),this._rejectRequest?.(e);return}this._resolveRequest?.(e)}};function Le(n){if(n!==void 0)return new URL(n).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.")}export{rt as AuthManager,it as AuthSession,Pe as BrowserConnectHandler,ct as CONNECT_DENIED_TOKEN,dt as ConnectProvider,Q as DEFAULT_WALLETS,x as DWEB_CONNECT_LOADED_MESSAGE_TYPE,D as DWEB_CONNECT_PATH,_ as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,C as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,et as Enbox,L as PopupClientTransport,R as PopupWindowClosedError,Y as WALLET_WELL_KNOWN_PATH,at as WalletConnect,U as WalletPostMessageTransport,De as activatePolyfills,te as cacheResponse,Ae as clearDrlCache,q as connectViaPopup,qe as deactivatePolyfills,tt as defineProtocol,ee as fetchResource,z as getDwnEndpoints,Z as handleEvent,st as normalizeProtocolRequests,v as parseDrlUrl,J as probeWalletWellKnown,nt as repository,A as showWalletSelector};
360
+ `}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"}];function gn(e={}){let{wallets:t=lt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:a,rememberChoice:s,connectServerUrl:l,relayWalletPath:d}=e;return{async requestAccess(p){return Ne({wallets:t,walletUrl:n,preferredMethod:a,rememberChoice:s,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:l,relayWalletPath:d,timeout:r,permissionRequests:p.permissionRequests})}}}import{X25519 as wn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as bn,ConnectProvider as vn}from"@enbox/connect";var yn=3e5,Le=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=En(t.dappOrigin),o=await wn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},a=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??yn});return n.postMessage({type:te,walletEpk:i,walletOrigin:globalThis.location.origin},r),a}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(t){this._dappWindow.postMessage({type:oe,payload:t},this._dappOrigin),this.close()}deny(){this.sendResponse(bn)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=ue(t,this._dappOrigin,this._dappWindow);if(n!==void 0&&!(n.type!==ne||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 vn.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 En(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 Ro}from"@enbox/auth/browser";import{DwnInterface as ko}from"@enbox/agent";import{DateSort as So,DwnInterfaceName as Wo,DwnMethodName as No}from"@enbox/dwn-sdk-js";export{so as AuthManager,ao as AuthSession,gn as BrowserConnectHandler,Ro as BrowserStorage,uo as CONNECT_DENIED_TOKEN,fo as ConnectProvider,lt as DEFAULT_WALLETS,te as DWEB_CONNECT_LOADED_MESSAGE_TYPE,ye as DWEB_CONNECT_PATH,ne as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,oe as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,So as DateSort,ko as DwnInterface,Wo as DwnInterfaceName,No as DwnMethodName,no as Enbox,Te as MAX_PIN_ATTEMPTS,K as PopupClientTransport,$ as PopupWindowClosedError,G as RelayConnectCancelledError,_o as TypedRecord,rt as WALLET_WELL_KNOWN_PATH,co as WalletConnect,Le as WalletPostMessageTransport,Pn as activatePolyfills,_t as cacheResponse,Mn as clearDrlCache,It as connectViaPopup,Rn as deactivatePolyfills,oo as defineProtocol,at as discoverWalletConnectServerUrl,Re as encodeQr,Ct as fetchResource,me as fetchWalletWellKnown,Je as getDwnEndpoints,xt as handleEvent,lo as normalizeProtocolRequests,X as parseDrlUrl,ke as probeWalletWellKnown,Me as qrToSvg,ro as repository,Ne as runConnectModal,Se as runRelayConnect};
371
361
  //# sourceMappingURL=browser.mjs.map