@enbox/browser 0.3.70 → 0.3.72

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 (39) hide show
  1. package/README.md +30 -7
  2. package/dist/browser.mjs +14 -14
  3. package/dist/browser.mjs.map +4 -4
  4. package/dist/esm/blob-url-pool.js +36 -0
  5. package/dist/esm/blob-url-pool.js.map +1 -0
  6. package/dist/esm/browser-connect-handler.js +3 -1
  7. package/dist/esm/browser-connect-handler.js.map +1 -1
  8. package/dist/esm/file-envelope-url-store.js +203 -0
  9. package/dist/esm/file-envelope-url-store.js.map +1 -0
  10. package/dist/esm/index.js +12 -12
  11. package/dist/esm/index.js.map +1 -1
  12. package/dist/esm/object-url-reference.js +68 -0
  13. package/dist/esm/object-url-reference.js.map +1 -0
  14. package/dist/esm/relay-connect-runner.js +9 -1
  15. package/dist/esm/relay-connect-runner.js.map +1 -1
  16. package/dist/esm/ui/connect-modal.js +134 -16
  17. package/dist/esm/ui/connect-modal.js.map +1 -1
  18. package/dist/types/blob-url-pool.d.ts +16 -0
  19. package/dist/types/blob-url-pool.d.ts.map +1 -0
  20. package/dist/types/browser-connect-handler.d.ts +8 -2
  21. package/dist/types/browser-connect-handler.d.ts.map +1 -1
  22. package/dist/types/file-envelope-url-store.d.ts +30 -0
  23. package/dist/types/file-envelope-url-store.d.ts.map +1 -0
  24. package/dist/types/index.d.ts +16 -14
  25. package/dist/types/index.d.ts.map +1 -1
  26. package/dist/types/object-url-reference.d.ts +20 -0
  27. package/dist/types/object-url-reference.d.ts.map +1 -0
  28. package/dist/types/relay-connect-runner.d.ts +4 -0
  29. package/dist/types/relay-connect-runner.d.ts.map +1 -1
  30. package/dist/types/ui/connect-modal.d.ts +24 -11
  31. package/dist/types/ui/connect-modal.d.ts.map +1 -1
  32. package/package.json +7 -7
  33. package/src/blob-url-pool.ts +55 -0
  34. package/src/browser-connect-handler.ts +13 -2
  35. package/src/file-envelope-url-store.ts +260 -0
  36. package/src/index.ts +23 -159
  37. package/src/object-url-reference.ts +82 -0
  38. package/src/relay-connect-runner.ts +17 -2
  39. package/src/ui/connect-modal.ts +187 -28
package/README.md CHANGED
@@ -41,17 +41,40 @@ API from `@enbox/api`, auth/session helpers from `@enbox/auth`, and
41
41
  browser-specific connect utilities.
42
42
 
43
43
  ```ts
44
- import { BrowserConnectHandler, Enbox, defineProtocol, recordCodecs } from '@enbox/browser';
45
-
46
- const { enbox } = await Enbox.connect({
47
- connectHandler : BrowserConnectHandler({ appName: 'Notes' }),
48
- protocols : [NotesProtocol],
44
+ import {
45
+ BrowserConnectHandler,
46
+ createConnectionStore,
47
+ defineApplicationManifest,
48
+ } from '@enbox/browser';
49
+
50
+ const application = defineApplicationManifest({
51
+ protocols: [NotesProtocol],
52
+ } as const);
53
+ const store = createConnectionStore({
54
+ application,
55
+ connectHandler: BrowserConnectHandler({ appName: 'Notes' }),
49
56
  });
57
+
58
+ let snapshot = await store.initialize();
59
+ if (snapshot.phase === 'disconnected') {
60
+ snapshot = await store.connect();
61
+ }
62
+ if (snapshot.phase !== 'connected') {
63
+ throw snapshot.error ?? new Error('Connection was not established.');
64
+ }
65
+
66
+ const enbox = snapshot.enbox;
67
+
68
+ // ...use enbox...
69
+
70
+ // On sign-out and application shutdown:
71
+ await store.disconnect();
72
+ await store.dispose();
50
73
  ```
51
74
 
52
75
  This is the delegated wallet flow. To create a local owner identity, omit
53
- `connectHandler` and pass `createIdentity: true`. Applications that need session
54
- restoration and refresh should use a manifest-backed connection store.
76
+ `connectHandler` and call `store.connectVault({ createIdentity: true })`. The
77
+ store owns session restoration, refresh, facade replacement, and teardown.
55
78
 
56
79
  ## Bundlers and Service Workers
57
80
 
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyError as mr,ContextRetiredError as hr,defineApplicationManifest as gr,DwnResponseError as wr,Enbox as vr,defineProtocol as br,getApplicationProtocolRequests as yr,ProtocolReadinessError as Er,RecordConflictError as xr,RecordParentNotFoundError as Cr,RecordSquashBackstopError as Pr,RecordValidationError as Rr,protocolContextKey as _r,recordCodecs as kr,ServiceConfigProtocol as Tr}from"@enbox/api";import{AuthManager as Sr,AuthSession as Dr,ConnectDeniedError as Or,SESSION_EXPIRED_ERROR_CODE as Ar,SESSION_REVOKED_ERROR_CODE as Lr,computeConnectionStatus as Wr,isConnectDeniedError as Nr,isSessionExpiredError as qr,isSessionInvalidError as Ur,normalizeProtocolRequests as Ir,WalletConnect as Hr}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as jr,ConnectProvider as Kr}from"@enbox/connect";import{DidDht as sn,DidResolverCacheMemory as gt,DidWeb as ln,resolveDwnEndpointStatus as cn,UniversalResolver as wt}from"@enbox/dids";function te(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 wt({didResolvers:[sn,ln],cache:new gt}),vt=/^http:/,xe=/\/$/,bt="drl";async function yt(e){let t=await cn(e,Ne);return t.status==="ready"?t.endpoints:[]}async function Et(){if(!(typeof caches>"u"))return caches.open(bt)}async function dn(e,t,n,r){let o=e.request.url.replace(vt,"https:").replace(xe,""),i=await Et(),a=await i?.match(o);if(a){if(!navigator.onLine)return a;let s=await r?.onCacheCheck?.(e,o);if(s){let d=a.headers.get("dwn-cache-time");if(d&&Date.now()<Number(d)+(Number(s.ttl)||0))return a}}try{if(n)return await pn(e,t,o,n,i,r);{let s=await Ne.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 pn(e,t,n,r,o,i){let a=await yt(t);if(!a?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let s;for(let d of a)try{let p=`${d.replace(xe,"")}/${t}/${r}`,v=await fetch(p,{headers:e.request.headers});if(v.ok)return await i?.onCacheCheck?.(e,n)&&o&&un(n,p,v,o),v;console.log(`DWN endpoint error: ${v.status}`),s=new Response("DWeb Node request failed",{status:v.status})}catch(p){console.log(`DWN endpoint error: ${p}`),s=new Response("DWeb Node request failed",{status:500})}return s}async function un(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 fn(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=te(n.request.url);r&&n.respondWith(dn(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 xt=`
1
+ export*from"@enbox/api";export*from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as Bo,ConnectProvider as jo}from"@enbox/connect";import{DidDht as yn,DidResolverCacheMemory as Rt,DidWeb as En,resolveDwnEndpointStatus as xn,UniversalResolver as kt}from"@enbox/dids";function ae(t){let e=t.indexOf("://dweb/");if(e===-1)return null;let n=t.slice(0,e);if(n!=="http"&&n!=="https")return null;let r=t.slice(e+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 je=new kt({didResolvers:[yn,En],cache:new Rt}),Tt=/^http:/,ke=/\/$/,Dt="drl";async function St(t){let e=await xn(t,je);return e.status==="ready"?e.endpoints:[]}async function Mt(){if(!(typeof caches>"u"))return caches.open(Dt)}async function Cn(t,e,n,r){let o=t.request.url.replace(Tt,"https:").replace(ke,""),i=await Mt(),s=await i?.match(o);if(s){if(!navigator.onLine)return s;let a=await r?.onCacheCheck?.(t,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 _n(t,e,o,n,i,r);{let a=await je.resolve(e);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 _n(t,e,n,r,o,i){let s=await St(e);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(ke,"")}/${e}/${r}`,b=await fetch(p,{headers:t.request.headers});if(b.ok)return await i?.onCacheCheck?.(t,n)&&o&&Pn(n,p,b,o),b;console.log(`DWN endpoint error: ${b.status}`),a=new Response("DWeb Node request failed",{status:b.status})}catch(p){console.log(`DWN endpoint error: ${p}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function Pn(t,e,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",e);let s=new Response(o.body,{headers:i});await r.put(t,s)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function Rn(t={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let e=self;e.skipWaiting(),e.addEventListener("activate",n=>{n.waitUntil(e.clients.claim())}),e.addEventListener("fetch",n=>{let r=ae(n.request.url);r&&n.respondWith(Cn(n,r[0],r[1],t))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let n=t.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(e){console.error("Error in installing networking features:",e)}}var Lt=`
2
2
  .drl-loading-overlay {
3
3
  position: fixed;
4
4
  inset: 0;
@@ -103,7 +103,7 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
103
103
  opacity: 0;
104
104
  }
105
105
  }
106
- `,mn=`
106
+ `,kn=`
107
107
  <!DOCTYPE html>
108
108
  <html lang='en'>
109
109
  <head>
@@ -119,7 +119,7 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
119
119
  font-family: Arial, sans-serif;
120
120
  text-align: center;
121
121
  }
122
- ${xt}
122
+ ${Lt}
123
123
  </style>
124
124
  </head>
125
125
  <body>
@@ -132,8 +132,8 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
132
132
  </div>
133
133
  </body>
134
134
  </html>
135
- `,be=!1,I=null,ne=null;function ht(){be||(ne=document.createElement("style"),ne.innerHTML=`
136
- ${xt}
135
+ `,_e=!1,B=null,le=null;function Pt(){_e||(le=document.createElement("style"),le.innerHTML=`
136
+ ${Lt}
137
137
 
138
138
  .drl-loading-overlay {
139
139
  opacity: 0;
@@ -145,13 +145,13 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
145
145
  opacity: 1;
146
146
  pointer-events: all;
147
147
  }
148
- `,document.head.append(ne),I=document.createElement("div"),I.classList.add("drl-loading-overlay"),I.innerHTML=`
148
+ `,document.head.append(le),B=document.createElement("div"),B.classList.add("drl-loading-overlay"),B.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
- `,I.lastElementChild.addEventListener("click",qe),document.body.prepend(I),be=!0)}function hn(){be&&(ne?.remove(),ne=null,I?.remove(),I=null,be=!1)}function qe(){document.documentElement.removeAttribute("drl-link-loading"),ye=null}async function gn(e,t,n){let r=null;n?(r=window.open("","_blank"),r&&r.document.write(mn)):(ye=t,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let o=await yt(e);if(!o.length)throw new Error("no valid DWN endpoints found");let i=`${o[0].replace(xe,"")}/${e}/${t}`;n?r&&!r.closed&&(r.location.href=i):ye===t&&(window.location.href=i)}var ye=null,Ee=!1,oe=null,re=null;function wn(){Ee||(oe=async e=>{let t=e.target?.closest("a");if(!t)return;let n=t.href,r=te(n);if(!r)return;let o=r[0],i=r[1],a=t.target==="_blank";e.preventDefault();try{await gn(o,i,a)}catch{throw ye===i&&qe(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}},re=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(G(),t?.src&&te(t.src)){H=t,t.__src__=t.src;let n=t.src.replace(vt,"https:").replace(xe,""),o=await(await Et())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",G,{once:!0})}}else t===H&&G()},document.addEventListener("click",oe),document.addEventListener("pointercancel",G),document.addEventListener("pointerdown",re),Ee=!0)}function vn(){Ee&&(oe&&(document.removeEventListener("click",oe),oe=null),re&&(document.removeEventListener("pointerdown",re),re=null),document.removeEventListener("pointercancel",G),G(),qe(),Ee=!1)}var H=null;async function G(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),H&&(H.src=H.__src__,delete H.__src__,H=null)}function Oo(e={}){e.didResolvers&&(Ne=new wt({didResolvers:e.didResolvers,cache:new gt})),e.serviceWorker!==!1&&fn(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ht,{once:!0}):ht()),e.links!==!1&&wn())}function Ao(){typeof window<"u"&&typeof window.document<"u"&&(vn(),hn())}async function Lo(){return typeof caches>"u"?!1:caches.delete(bt)}import{ConnectClient as ro}from"@enbox/connect";function ie(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=bn(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 bn(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 yn,CONNECT_DENIED_TOKEN as En,ConnectClient as xn}from"@enbox/connect";function Ce(){let e,t,n=new Promise((r,o)=>{e=r,t=o});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}var Ue="/dweb-connect",ae="enbox-connect-loaded",se="enbox-connect-request",F="enbox-connect-response",le="enbox-connect-ack";function Pe(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var Cn=3e5,Pn=500,Rn=1500,_n="enbox-dweb-connect",Ct=500,Pt=700;function kn(){let e=`width=${Ct},height=${Pt},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-Ct)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-Pt)/2));return`${e},left=${r},top=${o}`}function Tn(){if(typeof window>"u")throw new TypeError("[@enbox/browser] DWeb Connect is only available in browser environments.")}var B=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},Y=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;Tn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??Cn;let n=new URL(Ue,t.walletUrl).toString(),r=window.open(n,_n,kn());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((i,a)=>{this._resolveWalletEpk=i,this._rejectWalletEpk=a});let o=Ce();this._responsePromise=o.promise,this._resolveResponse=o.resolve,this._rejectResponse=o.reject,this._messageListener=i=>{this.onMessage(i)},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:se,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:le},this._walletOrigin)}onMessage(t){let n=Pe(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===ae){this.onLoadedBeacon(n);return}n.type===F&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{yn(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 B);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse(En))},Rn)}}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 Re(){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 Mn(e){let t=new Y({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new xn({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof B)return;throw r}}var _t=[-1,10,16,26,18,24,16,18,22,22,26],kt=[-1,1,1,1,2,2,4,4,4,5,5],Tt=[-1,26,44,70,100,134,172,196,242,292,346],Sn=0,Mt=10;function St(e){return Tt[e]-_t[e]*kt[e]}function Ke(e,t){let n=new TextEncoder().encode(e),r=Dn(n.length);if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${Mt}-M capacity).`);let o=On(n,r),i=Ln(o,r),a=17+4*r,s=Array.from({length:a},()=>new Array(a).fill(!1)),d=Array.from({length:a},()=>new Array(a).fill(!1));Un(s,d,r),Bn(s,d,i);let p=t??-1;return p===-1&&(p=An(s,d)),je(s,d,p),$e(s,d,p),{size:a,modules:s,version:r,mask:p}}function Dn(e){for(let t=1;t<=Mt;t++){let n=St(t)*8;if(4+(t<=9?8:16)+e*8<=n)return t}return 0}function On(e,t){let n=[],r=(d,p)=>{for(let v=p-1;v>=0;v--)n.push(d>>>v&1)};r(4,4),r(e.length,t<=9?8:16);for(let d of e)r(d,8);let o=St(t)*8;r(0,Math.min(4,o-n.length)),r(0,(8-n.length%8)%8);let i=[236,17],a=0;for(;n.length<o;)r(i[a],8),a^=1;let s=new Uint8Array(o/8);for(let d=0;d<n.length;d++)s[d>>3]|=n[d]<<7-(d&7);return s}function An(e,t){let n=0,r=1/0;for(let o=0;o<8;o++){je(e,t,o),$e(e,t,o);let i=Yn(e);i<r&&(r=i,n=o),je(e,t,o)}return n}function Ln(e,t){let n=kt[t],r=_t[t],o=Tt[t],i=n-o%n,a=Math.floor(o/n),s=[],d=[],p=Wn(r),v=0;for(let E=0;E<n;E++){let y=a-r+(E<i?0:1),x=e.slice(v,v+y);v+=y,s.push(x),d.push(Nn(x,p))}let f=new Uint8Array(o),P=0,j=a-r+1;for(let E=0;E<j;E++)for(let y=0;y<n;y++)E<s[y].length&&(f[P++]=s[y][E]);for(let E=0;E<r;E++)for(let y=0;y<n;y++)f[P++]=d[y][E];return f}function Be(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 Wn(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]=Be(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Be(n,2)}return t}function Nn(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]^=Be(t[i],o)}return n}var qn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function C(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function Un(e,t,n){let r=e.length;for(let i=0;i<r;i++)C(e,t,6,i,i%2===0),C(e,t,i,6,i%2===0);Ie(e,t,3,3),Ie(e,t,r-4,3),Ie(e,t,3,r-4);let o=qn[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||In(e,t,o[i],o[a]);$e(e,t,0),C(e,t,8,r-8,!0),n>=7&&Hn(e,t,n)}function Ie(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,d=r+i;if(s<0||s>=o||d<0||d>=o)continue;let p=Math.max(Math.abs(a),Math.abs(i));C(e,t,s,d,p!==2&&p!==4)}}function In(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)C(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function $e(e,t,n){let r=e.length,o=Sn<<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++)C(e,t,8,s,(a>>>s&1)!==0);C(e,t,8,7,(a>>>6&1)!==0),C(e,t,8,8,(a>>>7&1)!==0),C(e,t,7,8,(a>>>8&1)!==0);for(let s=9;s<15;s++)C(e,t,14-s,8,(a>>>s&1)!==0);for(let s=0;s<8;s++)C(e,t,r-1-s,8,(a>>>s&1)!==0);for(let s=8;s<15;s++)C(e,t,8,r-15+s,(a>>>s&1)!==0)}function Hn(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,d=r-11+a%3,p=Math.floor(a/3);C(e,t,d,p,s),C(e,t,p,d,s)}}function Bn(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){let a=i<=6?i-1:i;o=jn(e,t,n,a,r,o)}}function jn(e,t,n,r,o,i){for(let a=0;a<o;a++)for(let s=0;s<2;s++){let{x:d,y:p}=Kn(r,a,s,o);!t[p][d]&&i<n.length*8&&(e[p][d]=(n[i>>3]>>>7-(i&7)&1)!==0,i++)}return i}function Kn(e,t,n,r){let o=e-n,a=(e+1&2)===0?r-1-t:t;return{x:o,y:a}}function je(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 $n(e,t){let n=0;for(let r=0;r<t;r++){let o=!1,i=0;for(let a=0;a<t;a++)a===0||e[r][a]!==o?(o=e[r][a],i=1):(i++,i===5?n+=3:i>5&&(n+=1))}for(let r=0;r<t;r++){let o=!1,i=0;for(let a=0;a<t;a++)a===0||e[a][r]!==o?(o=e[a][r],i=1):(i++,i===5?n+=3:i>5&&(n+=1))}return n}function zn(e,t){let n=0;for(let r=0;r<t-1;r++)for(let o=0;o<t-1;o++){let i=e[r][o];i===e[r][o+1]&&i===e[r+1][o]&&i===e[r+1][o+1]&&(n+=3)}return n}function Rt(e,t){if(![!0,!1,!0,!0,!0,!1,!0].every((a,s)=>e[t+s]===a))return 0;let o=t>=4&&e.slice(t-4,t).every(a=>!a),i=t+11<=e.length&&e.slice(t+7,t+11).every(a=>!a);return(o?40:0)+(i?40:0)}function Gn(e,t){let n=0;for(let r=0;r<t;r++){let o=e[r],i=e.map(a=>a[r]);for(let a=0;a+7<=t;a++)n+=Rt(o,a),n+=Rt(i,a)}return n}function Fn(e,t){let n=0;for(let i of e)for(let a of i)a&&n++;let r=t*t;return(Math.ceil(Math.abs(n*20-r*10)/r)-1)*10}function Yn(e){let t=e.length,n=0;return n+=$n(e,t),n+=zn(e,t),n+=Gn(e,t),n+=Fn(e,t),n}var He="http://www.w3.org/2000/svg";function ze(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,a="";for(let v=0;v<e.size;v++)for(let f=0;f<e.size;f++)e.modules[v][f]&&(a+=`M${f+o} ${v+o}h1v1h-1z`);let s=document.createElementNS(He,"svg");s.setAttribute("viewBox",`0 0 ${i} ${i}`),s.setAttribute("shape-rendering","crispEdges"),s.setAttribute("role","img");let d=document.createElementNS(He,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),s.appendChild(d);let p=document.createElementNS(He,"path");return p.setAttribute("d",a),p.setAttribute("fill",n),s.appendChild(p),s}var Dt="/.well-known/enbox-connect";async function _e(e){try{let t=new URL(Dt,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 Ge(e){return await _e(e)!==void 0}import{DidJwk as Vn}from"@enbox/dids";import{X25519 as Qn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Jn,openResponse as Xn,randomToken as Ot,RelayClientTransport as Zn,resolveDelegatePortableDid as eo,sealRequest as to}from"@enbox/connect";var Fe=6,V=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function no(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 Ye(e){if(e.requestType==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let t=e.createTransport??(x=>new Zn({...x,sleep:no})),n=e.cancelled===void 0?void 0:new AbortController,r=t({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed,signal:n?.signal}),o=await Vn.create(),i=await Qn.generateKey(),a={kty:"OKP",crv:"X25519",x:i.x},s=Ot(),d=Ot(),p=await r.requestProfile(d),v={clientDid:o.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,delegateDid:e.delegatePortableDid?.uri,requestType:e.requestType,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:d,responseKey:a,reply:p.reply},f=await to({request:v,signer:o,encryption:p.encryption}),P=await r.deliverRequest(f);P!==void 0&&e.onWalletUriReady(P);let j=e.cancelled===void 0?r.awaitResponse():Promise.race([r.awaitResponse(),e.cancelled]),E;try{E=await j}catch(x){throw n?.abort(),x}if(E===Jn)return;let y;for(let x=1;x<=Fe;x++){let de=await(e.cancelled===void 0?e.requestPin(x,y):Promise.race([e.requestPin(x,y),e.cancelled])),O=await oo({responseCiphertext:E,responsePrivateKey:i,clientDid:o.uri,nonce:s,state:d,pin:de,delegatePortableDid:e.delegatePortableDid,confirmComplete:r.confirmComplete?.bind(r)});if(O.matched)return O.result;y=O.error}throw new Error(`[@enbox/browser] The pairing code did not match after ${Fe} attempts.`)}async function oo(e){try{let t=await Xn({jwe:e.responseCiphertext,recipientPrivateKey:e.responsePrivateKey,expected:{clientDid:e.clientDid,nonce:e.nonce,state:e.state},pin:e.pin}),n=eo({localDelegatePortableDid:e.delegatePortableDid,response:t});return e.confirmComplete?.().catch(()=>{}),{matched:!0,result:{delegatePortableDid:n,delegateGrants:t.delegateGrants,connectedDid:t.providerDid,sessionRevocations:t.sessionRevocations}}}catch(t){let n=t instanceof Error?t:new Error(String(t));if(n.message.startsWith("Connect:"))throw n;return{matched:!1,error:n}}}var qt="enbox:connect:lastChoice",io=12e4,ao=1e4,ke=4,so=4,At=3,Ve={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 Ut(e){return(await _e(e))?.connectServerUrl}async function lo(e){let t=new Y({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new ro({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.requestType})}function co(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function po(){return{runRelay:Ye,runPopup:lo,discoverConnectServerUrl:Ut,validateWalletUrl:Ge,isMobile:co,storage:typeof localStorage>"u"?void 0:localStorage}}function uo(e){try{let t=e?.getItem(qt);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&ho(n.walletUrl))return{method:n.method,walletUrl:n.walletUrl}}catch{}}function fo(e,t){try{e?.setItem(qt,JSON.stringify(t))}catch{}}function mo(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new V))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Qe(e,t){return()=>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.");if(e.mode==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let t={...po(),...e.deps},n=go(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",a=t.isMobile(),s=e.mode==="refresh",d=r?uo(t.storage):void 0,p=d!==void 0&&(s||Lt(n,d.walletUrl))?d.walletUrl:void 0,v=e.walletUrl!==void 0||s&&p!==void 0,f=e.walletUrl??p??n[0]?.url,P=e.preferredMethod??d?.method??"phone";return new Promise((j,E)=>{let y=document.createElement("div");y.id="enbox-connect-modal";let x=y.attachShadow({mode:"open"}),de=document.createElement("style");de.textContent=Eo,x.appendChild(de);let O=document.createElement("div");O.className="overlay";let _=document.createElement("div");_.className="modal",_.setAttribute("role","dialog"),_.setAttribute("aria-modal","true");let Ze=s?`Reconnect to ${o}`:`Connect to ${o}`;_.setAttribute("aria-label",Ze);let A=e.theme??{},Q=A.appearance??"auto";Q!=="auto"&&(_.dataset.appearance=Q);let Me=window.matchMedia?.("(prefers-color-scheme: dark)"),Ht=A.accent!==void 0||A.accentContrast!==void 0||A.light!==void 0||A.dark!==void 0,et=()=>{let l=Me?.matches===!0?"dark":"light",c=Q==="auto"?l:Q,w={accent:A.accent,accentContrast:A.accentContrast,...A[c]};for(let u of Object.keys(Ve)){let b=w[u];typeof b=="string"&&b.trim()!==""?_.style.setProperty(Ve[u],b):_.style.removeProperty(Ve[u])}},tt=()=>et();Ht&&(et(),Q==="auto"&&Me?.addEventListener?.("change",tt));let k=!1,L,nt,pe,Se=!1,K,Bt=()=>K,jt=()=>{K=void 0},ot=new Map,$=[],ue=l=>n.find(c=>c.url===l)??{name:wo(l)??l,url:l},Kt=()=>{if(f===void 0){$=n.slice(0,At);return}if($.some(c=>c.url===f))return;let l=ue(f);$=[l,...n.filter(c=>c.url!==l.url)].slice(0,At)},fe=l=>{f=l,X(),J()},$t=()=>{L?.cancel(),q(),document.removeEventListener("keydown",dt),document.removeEventListener("visibilitychange",pt),Me?.removeEventListener?.("change",tt);try{y.remove()}catch{}},me=l=>{k||(k=!0,$t(),l())},rt=l=>{r&&fo(t.storage,{method:P,walletUrl:f??""}),Qt(),setTimeout(Qe(me,()=>j(l)),1200)},De=()=>me(()=>E(new Error("[@enbox/browser] Connect cancelled.")));_.appendChild(vo(Ze,e.appIcon,De));let W=document.createElement("div");W.className="stage",W.setAttribute("aria-live","polite"),_.appendChild(W);let N=document.createElement("div");N.className="footer",_.appendChild(N);let R=(...l)=>{W.replaceChildren(...l),W.classList.remove("fade-in"),W.offsetWidth,W.classList.add("fade-in")},it=l=>{R(h("div","spinner"),h("p","stage-caption",l))},zt=l=>{let c=L;setTimeout(()=>{k||c!==L||c?.active!==!0||K!==void 0||Ft(l)},0)},at=(l,c,w)=>{let u=document.createElement("a");return u.className=w,u.href=l.walletUri,u.target="_blank",u.rel="noopener noreferrer",u.addEventListener("click",()=>{zt(c)}),u},Gt=l=>{let c=f!==void 0?ue(f):void 0,w=c?.name??"your wallet",u=at(l,w,"qr-box qr-link");if(u.setAttribute("aria-label",`Open ${w} on this device`),u.replaceChildren(ze(Ke(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let b=h("div","qr-logo");b.appendChild(ie(c)),u.appendChild(b)}if(a){let b=at(l,w,"deep-link");c!==void 0&&b.appendChild(ie(c)),b.appendChild(h("span","deep-link-label",`Continue in ${w}`)),u.classList.add("compact"),R(b,h("p","stage-subline",`${w} opens in a new tab \u2014 approve there, then come back for your code.`),h("div","stage-divider","or scan with another phone"),u);return}R(u,h("p","stage-caption","Scan with your phone\u2019s camera"),h("p","stage-subline",`${w} stays on your phone \u2014 or click the code to open it here.`))},Ft=l=>{R(h("div","spinner"),h("p","stage-caption",`Finish in ${l}`),h("p","stage-subline",a?`Approve the connection in the ${l} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),Te("Start over",()=>{Oe()}))},Yt=()=>{let l=f!==void 0?ue(f).name:"your wallet",c=document.createElement("div");c.className="claimed-pulse",R(c,h("p","stage-caption",`Request received \u2014 approve in ${l}`),h("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},Vt=(l,c)=>new Promise(w=>{K=w;let u=f!==void 0?ue(f).name:"your wallet",b=document.createElement("div");b.className="pin-row",c!==void 0&&b.classList.add("shake");let z=bo(b,Bt,jt,it);R(h("p","stage-caption",`Enter the code shown in ${u}`),b,...c!==void 0?[h("p","stage-error",`That code doesn\u2019t match \u2014 check ${u}.`)]:[h("p","stage-subline",l===1?"This confirms you\u2019re the one approving.":"")]),z[0].focus()}),Qt=()=>{let l=h("div","check");l.textContent="\u2713",R(l,h("p","stage-caption","You\u2019re connected."))},st=()=>{R(h("p","stage-caption","No problem \u2014 nothing was shared."),ce("Start over",()=>{J()}),Te("Close",Qe(me,()=>j(void 0))))},he=(l,c)=>{R(h("p","stage-caption",l),ce("Start over",()=>{J()}),Te("Close",Qe(me,()=>E(c??new Error(`[@enbox/browser] ${l}`)))))},Jt=()=>{R(h("p","stage-caption","This wallet can\u2019t connect by phone here."),h("p","stage-subline","You can continue in this browser instead."),ce("Use this browser",()=>{we()}))},ge=a?"tab":"window",Xt=()=>{R(h("p","stage-caption","Connect with a wallet in this browser"),h("p","stage-subline",a?"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."),ce(a?"Open wallet":"Open wallet window",()=>{we()}))},Zt=()=>{R(h("div","spinner"),h("p","stage-caption",`Finish in the wallet ${ge}`),h("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},en=l=>{R(h("p","stage-caption",l?`Your browser blocked the wallet ${ge}.`:`The wallet ${ge} was closed.`),ce(l?"Open it now":`Reopen ${ge}`,()=>{we()}),Te(a?"Use a code instead":"Use your phone instead",()=>{ct("phone")}))},tn=l=>{if(k)return;let c=l instanceof Error?l:new Error(String(l)),w=/popup blocked/i.test(c.message);if(l instanceof B||w){en(w);return}he(/timed out/i.test(c.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",c)},nn=async l=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let c=ot.get(l);return c===void 0&&(c=t.discoverConnectServerUrl(l),ot.set(l,c)),c},q=()=>{clearTimeout(nt),pe=void 0},lt=()=>{!k&&K===void 0&&P==="phone"&&Oe()},on=l=>{q();let c=Math.max(ao,l*1e3-io);pe=Date.now()+c,nt=setTimeout(lt,c)},Oe=async()=>{if(L?.cancel(),q(),f===void 0){he("No wallet is configured.");return}P="phone",X(),it("Getting things ready\u2026");let l=new URL(f).origin,c=await nn(l);if(c===void 0){Jt();return}let w=mo();L=w;try{let u=await t.runRelay({connectServerUrl:c,walletUri:new URL(i,l).toString(),appName:o,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.mode,timeoutMs:e.timeout,cancelled:w.cancelled,onWalletUriReady:b=>{w.active&&!k&&(Gt(b),on(b.expiresIn))},onClaimed:()=>{w.active&&!k&&(q(),Yt())},requestPin:(b,z)=>(q(),Vt(b,z))});if(!w.active||k)return;u===void 0?st():rt(u)}catch(u){if(!w.active||k||u instanceof V)return;let b=u instanceof Error?u:new Error(String(u));he(/timed out/i.test(b.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",b)}},we=async()=>{if(L?.cancel(),q(),f===void 0){he("No wallet is configured.");return}if(!Se){P="browser",X(),Se=!0,Zt();try{let l=await t.runPopup({walletUrl:f,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout,delegatePortableDid:e.delegatePortableDid,requestType:e.mode});if(k)return;l===void 0?st():rt(l)}catch(l){tn(l)}finally{Se=!1}}},J=async()=>{P==="browser"?(L?.cancel(),q(),X(),Xt()):await Oe()},ct=async l=>{P=l,await J()},X=()=>{if(N.replaceChildren(),!v){Kt();let c=rn();c.label!==void 0&&N.appendChild(c.label),N.appendChild(c.row),N.appendChild(c.panel)}let l=document.createElement("div");if(l.className="footer-row",P==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent=a?"Or connect without a code \u2192":"No phone? Use this browser \u2192",c.addEventListener("click",()=>{we()}),l.appendChild(c)}else{let c=document.createElement("button");c.className="footer-link method-link",c.textContent=a?"Use a code instead \u2192":"Use your phone instead \u2192",c.addEventListener("click",()=>{ct("phone")}),l.appendChild(c)}l.childElementCount>0&&N.appendChild(l)},rn=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let m of $){let g=document.createElement("button");g.className="row-tile",g.title=m.description??m.name,g.setAttribute("role","radio");let T=m.url===f;g.setAttribute("aria-checked",T?"true":"false"),T&&g.classList.add("selected"),g.appendChild(ie(m)),g.appendChild(h("span","row-tile-name",m.name)),g.addEventListener("click",()=>{m.url!==f&&fe(m.url)}),l.appendChild(g)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let w=n.filter(m=>!Lt($,m.url)),u=document.createElement("button");u.className="row-tile more-tile",u.title="All wallets",u.setAttribute("aria-expanded","false"),u.appendChild(h("span","more-count",w.length>0?`+${w.length}`:"\u22EF")),u.appendChild(h("span","row-tile-name","More")),u.addEventListener("click",()=>{c.hidden=!c.hidden,u.setAttribute("aria-expanded",c.hidden?"false":"true"),c.hidden||Le()}),l.appendChild(u);let b=$.length>0?h("div","wallet-row-label","Connecting with"):void 0,z=[],Z=document.createElement("div");if(Z.className="wallet-empty",Z.textContent="No other wallets match your search.",Z.hidden=!0,w.length>so){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(),T=0;for(let{wallet:ft,el:an}of z){let mt=g===""||ft.name.toLowerCase().includes(g)||ft.url.toLowerCase().includes(g);an.hidden=!mt,mt&&(T+=1)}Z.hidden=T>0,Le()}),c.appendChild(m)}let ee=document.createElement("div");ee.className="wallet-scroll-wrap",ee.hidden=w.length===0;let M=document.createElement("div");M.className="wallet-scroll";let Ae=document.createElement("div");Ae.className="wallet-grid";let Le=()=>{let m=M.scrollHeight-M.clientHeight>1,g=M.scrollTop+M.clientHeight>=M.scrollHeight-1;ee.classList.toggle("scroll-hint",m&&!g)};M.addEventListener("scroll",Le);for(let m of w){let g=document.createElement("button");g.className="wallet-tile",g.title=m.description??m.name,g.appendChild(ie(m));let T=document.createElement("span");T.className="wallet-tile-name",T.textContent=m.name,g.appendChild(T),g.addEventListener("click",()=>{fe(m.url)}),z.push({wallet:m,el:g}),Ae.appendChild(g)}M.appendChild(Ae),M.appendChild(Z),ee.appendChild(M),c.appendChild(ee);let ve=document.createElement("div");ve.className="wallet-custom";let S=document.createElement("input");S.className="url-input",S.type="url",S.placeholder="https://your-wallet.example";let D=document.createElement("button");D.className="url-go",D.textContent="Use";let U=document.createElement("div");U.className="url-error",U.hidden=!0;let We=!1,ut=async()=>{let m=S.value.trim();if(m==="")return;let g;try{g=new URL(m.includes("://")?m:`https://${m}`).origin}catch{S.classList.add("invalid");return}if(We){fe(g);return}D.disabled=!0,D.textContent="Checking\u2026",U.hidden=!0;let T=await t.validateWalletUrl(g);if(D.disabled=!1,T){D.textContent="Use",fe(g);return}We=!0,D.textContent="Use anyway",S.classList.add("invalid"),U.textContent=`Couldn't verify a wallet at ${g}.`,U.hidden=!1};return S.addEventListener("input",()=>{We=!1,D.textContent="Use",S.classList.remove("invalid"),U.hidden=!0}),S.addEventListener("keydown",m=>{m.key==="Enter"&&ut()}),D.addEventListener("click",()=>{ut()}),ve.appendChild(S),ve.appendChild(D),c.appendChild(ve),c.appendChild(U),{label:b,row:l,panel:c}};O.addEventListener("click",l=>{l.target===O&&De()});let dt=l=>{if(l.key==="Escape"){De();return}l.key==="Tab"&&yo(x,l)};document.addEventListener("keydown",dt);let pt=()=>{if(!(document.visibilityState!=="visible"||k)){if(pe!==void 0&&Date.now()>=pe){lt();return}K!==void 0&&Array.from(x.querySelectorAll(".pin-input")).find(c=>c.value==="")?.focus()}};document.addEventListener("visibilitychange",pt),O.appendChild(_),x.appendChild(O),document.body.appendChild(y),X(),J()})}function Lt(e,t){return e.some(n=>n.url===t)}function ho(e){if(typeof e!="string"||e.trim()==="")return!1;try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function go(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function wo(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function h(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function ce(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Te(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function vo(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=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 bo(e,t,n,r){let o=[];for(let a=0;a<ke;a++){let s=document.createElement("input");s.className="pin-input",s.type="text",s.inputMode="numeric",s.maxLength=1,s.setAttribute("aria-label",`Code digit ${a+1}`),o.push(s),e.appendChild(s)}let i=()=>{let a=o.map(d=>d.value).join(""),s=t();if(a.length===ke&&s!==void 0){let d=s;n(),r("Checking the code\u2026"),d(a)}};return o.forEach((a,s)=>{a.addEventListener("input",()=>{a.value=a.value.replace(/\D/g,"").slice(0,1),a.value!==""&&s+1<o.length&&o[s+1].focus(),i()}),a.addEventListener("keydown",d=>{d.key==="Backspace"&&a.value===""&&s>0&&o[s-1].focus()}),a.addEventListener("paste",d=>{let p=(d.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,ke);p.length!==0&&(d.preventDefault(),p.split("").forEach((v,f)=>{o[f]!==void 0&&(o[f].value=v)}),o[Math.min(p.length,ke)-1]?.focus(),i())})}),o}function yo(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())}var Wt=`
154
+ `,B.lastElementChild.addEventListener("click",He),document.body.prepend(B),_e=!0)}function Tn(){_e&&(le?.remove(),le=null,B?.remove(),B=null,_e=!1)}function He(){document.documentElement.removeAttribute("drl-link-loading"),Pe=null}async function Dn(t,e,n){let r=null;n?(r=window.open("","_blank"),r&&r.document.write(kn)):(Pe=e,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let o=await St(t);if(!o.length)throw new Error("no valid DWN endpoints found");let i=`${o[0].replace(ke,"")}/${t}/${e}`;n?r&&!r.closed&&(r.location.href=i):Pe===e&&(window.location.href=i)}var Pe=null,Re=!1,ce=null,de=null;function Sn(){Re||(ce=async t=>{let e=t.target?.closest("a");if(!e)return;let n=e.href,r=ae(n);if(!r)return;let o=r[0],i=r[1],s=e.target==="_blank";t.preventDefault();try{await Dn(o,i,s)}catch{throw Pe===i&&He(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}},de=async t=>{let e=t.composedPath()[0];if(t.pointerType==="mouse"&&t.button===2||t.pointerType==="touch"&&t.isPrimary){if(Y(),e?.src&&ae(e.src)){j=e,e.__src__=e.src;let n=e.src.replace(Tt,"https:").replace(ke,""),o=await(await Mt())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(e.src=i)}e.addEventListener("pointerup",Y,{once:!0})}}else e===j&&Y()},document.addEventListener("click",ce),document.addEventListener("pointercancel",Y),document.addEventListener("pointerdown",de),Re=!0)}function Mn(){Re&&(ce&&(document.removeEventListener("click",ce),ce=null),de&&(document.removeEventListener("pointerdown",de),de=null),document.removeEventListener("pointercancel",Y),Y(),He(),Re=!1)}var j=null;async function Y(t){t?.type==="pointerup"&&await new Promise(e=>requestAnimationFrame(()=>e())),j&&(j.src=j.__src__,delete j.__src__,j=null)}function Vr(t={}){t.didResolvers&&(je=new kt({didResolvers:t.didResolvers,cache:new Rt})),t.serviceWorker!==!1&&Rn(t),typeof window<"u"&&typeof window.document<"u"&&(t.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Pt,{once:!0}):Pt()),t.links!==!1&&Sn())}function Zr(){typeof window<"u"&&typeof window.document<"u"&&(Mn(),Tn())}async function eo(){return typeof caches>"u"?!1:caches.delete(Dt)}import{ConnectClient as vr}from"@enbox/connect";function pe(t){let e=document.createElement("span");e.className="wallet-icon";let n=document.createElement("span");n.className="wallet-badge",n.textContent=t.name.charAt(0).toUpperCase(),e.appendChild(n);let r=Ln(t);if(r.length===0)return e;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],e.appendChild(o),e}function Ln(t){if(t.icon!==void 0)return[t.icon];let e;try{e=new URL(t.url).origin}catch{return[]}return[`${e}/favicon.svg`,`${e}/favicon.ico`,`${e}/favicon.png`]}import{assertX25519PublicJwk as An,CONNECT_DENIED_TOKEN as On,ConnectClient as Un}from"@enbox/connect";function Te(){let t,e,n=new Promise((r,o)=>{t=r,e=o});return n.catch(()=>{}),{promise:n,resolve:t,reject:e}}var $e="/dweb-connect",ue="enbox-connect-loaded",fe="enbox-connect-request",G="enbox-connect-response",me="enbox-connect-ack";function De(t,e,n){if(t.origin!==e||t.source!==n)return;let r=t.data;if(!(typeof r!="object"||r===null))return r}var Wn=3e5,Nn=500,qn=1500,In="enbox-dweb-connect",At=500,Ot=700;function Bn(){let t=`width=${At},height=${Ot},menubar=no,toolbar=no,location=no,status=no`,e=window.outerWidth>0?window.outerWidth:window.screen?.availWidth??0,n=window.outerHeight>0?window.outerHeight:window.screen?.availHeight??0;if(e===0||n===0)return t;let r=Math.max(0,Math.round((window.screenX??0)+(e-At)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-Ot)/2));return`${t},left=${r},top=${o}`}function jn(){if(typeof window>"u")throw new TypeError("[@enbox/browser] DWeb Connect is only available in browser environments.")}var H=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},J=class{constructor(e){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;jn(),this._walletOrigin=new URL(e.walletUrl).origin,this._timeoutMs=e.timeoutMs??Wn;let n=new URL($e,e.walletUrl).toString(),r=window.open(n,In,Bn());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((i,s)=>{this._resolveWalletEpk=i,this._rejectWalletEpk=s});let o=Te();this._responsePromise=o.promise,this._resolveResponse=o.resolve,this._rejectResponse=o.reject,this._messageListener=i=>{this.onMessage(i)},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()},Nn)}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:fe,jwe:e},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:me},this._walletOrigin)}onMessage(e){let n=De(e,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===ue){this.onLoadedBeacon(n);return}n.type===G&&this.onResponseMessage(n)}}onLoadedBeacon(e){if(this._settled||this._walletEpkReceived)return;let n;try{An(e.walletEpk),n=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?.(n)}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 H);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse(On))},qn)}}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 Se(){let t=Intl.DateTimeFormat().resolvedOptions(),e=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,...e&&e.length>0?{languages:e}:{},...t.timeZone?{timezone:t.timeZone}:{}}}async function Hn(t){let e=new J({walletUrl:t.walletUrl,timeoutMs:t.timeout}),n=new Un({transport:e});try{return await n.connect({appName:t.appName??globalThis.location.host,appIcon:t.appIcon,clientMetadata:Se(),permissionRequests:t.permissionRequests})}catch(r){if(r instanceof H)return;throw r}}var Wt=[-1,10,16,26,18,24,16,18,22,22,26],Nt=[-1,1,1,1,2,2,4,4,4,5,5],qt=[-1,26,44,70,100,134,172,196,242,292,346],$n=0,It=10;function Bt(t){return qt[t]-Wt[t]*Nt[t]}function Ge(t,e){let n=new TextEncoder().encode(t),r=Kn(n.length);if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${It}-M capacity).`);let o=Fn(n,r),i=Yn(o,r),s=17+4*r,a=Array.from({length:s},()=>new Array(s).fill(!1)),d=Array.from({length:s},()=>new Array(s).fill(!1));Xn(a,d,r),er(a,d,i);let p=e??-1;return p===-1&&(p=zn(a,d)),Ye(a,d,p),Je(a,d,p),{size:s,modules:a,version:r,mask:p}}function Kn(t){for(let e=1;e<=It;e++){let n=Bt(e)*8;if(4+(e<=9?8:16)+t*8<=n)return e}return 0}function Fn(t,e){let n=[],r=(d,p)=>{for(let b=p-1;b>=0;b--)n.push(d>>>b&1)};r(4,4),r(t.length,e<=9?8:16);for(let d of t)r(d,8);let o=Bt(e)*8;r(0,Math.min(4,o-n.length)),r(0,(8-n.length%8)%8);let i=[236,17],s=0;for(;n.length<o;)r(i[s],8),s^=1;let a=new Uint8Array(o/8);for(let d=0;d<n.length;d++)a[d>>3]|=n[d]<<7-(d&7);return a}function zn(t,e){let n=0,r=1/0;for(let o=0;o<8;o++){Ye(t,e,o),Je(t,e,o);let i=ar(t);i<r&&(r=i,n=o),Ye(t,e,o)}return n}function Yn(t,e){let n=Nt[e],r=Wt[e],o=qt[e],i=n-o%n,s=Math.floor(o/n),a=[],d=[],p=Gn(r),b=0;for(let u=0;u<n;u++){let y=s-r+(u<i?0:1),_=t.slice(b,b+y);b+=y,a.push(_),d.push(Jn(_,p))}let E=new Uint8Array(o),C=0,Z=s-r+1;for(let u=0;u<Z;u++)for(let y=0;y<n;y++)u<a[y].length&&(E[C++]=a[y][u]);for(let u=0;u<r;u++)for(let y=0;y<n;y++)E[C++]=d[y][u];return E}function ze(t,e){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(e>>>r&1)*t;return n&255}function Gn(t){let e=new Uint8Array(t);e[t-1]=1;let n=1;for(let r=0;r<t;r++){for(let o=0;o<t;o++)e[o]=ze(e[o],n),o+1<t&&(e[o]^=e[o+1]);n=ze(n,2)}return e}function Jn(t,e){let n=new Uint8Array(e.length);for(let r of t){let o=r^n[0];n.copyWithin(0,1),n[n.length-1]=0;for(let i=0;i<e.length;i++)n[i]^=ze(e[i],o)}return n}var Qn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function P(t,e,n,r,o){t[r][n]=o,e[r][n]=!0}function Xn(t,e,n){let r=t.length;for(let i=0;i<r;i++)P(t,e,6,i,i%2===0),P(t,e,i,6,i%2===0);Ke(t,e,3,3),Ke(t,e,r-4,3),Ke(t,e,3,r-4);let o=Qn[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||Vn(t,e,o[i],o[s]);Je(t,e,0),P(t,e,8,r-8,!0),n>=7&&Zn(t,e,n)}function Ke(t,e,n,r){let o=t.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));P(t,e,a,d,p!==2&&p!==4)}}function Vn(t,e,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)P(t,e,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function Je(t,e,n){let r=t.length,o=$n<<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++)P(t,e,8,a,(s>>>a&1)!==0);P(t,e,8,7,(s>>>6&1)!==0),P(t,e,8,8,(s>>>7&1)!==0),P(t,e,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)P(t,e,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)P(t,e,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)P(t,e,8,r-15+a,(s>>>a&1)!==0)}function Zn(t,e,n){let r=t.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);P(t,e,d,p,a),P(t,e,p,d,a)}}function er(t,e,n){let r=t.length,o=0;for(let i=r-1;i>=1;i-=2){let s=i<=6?i-1:i;o=tr(t,e,n,s,r,o)}}function tr(t,e,n,r,o,i){for(let s=0;s<o;s++)for(let a=0;a<2;a++){let{x:d,y:p}=nr(r,s,a,o);!e[p][d]&&i<n.length*8&&(t[p][d]=(n[i>>3]>>>7-(i&7)&1)!==0,i++)}return i}function nr(t,e,n,r){let o=t-n,s=(t+1&2)===0?r-1-e:e;return{x:o,y:s}}function Ye(t,e,n){let r=t.length;for(let o=0;o<r;o++)for(let i=0;i<r;i++){if(e[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&&(t[o][i]=!t[o][i])}}function rr(t,e){let n=0;for(let r=0;r<e;r++){let o=!1,i=0;for(let s=0;s<e;s++)s===0||t[r][s]!==o?(o=t[r][s],i=1):(i++,i===5?n+=3:i>5&&(n+=1))}for(let r=0;r<e;r++){let o=!1,i=0;for(let s=0;s<e;s++)s===0||t[s][r]!==o?(o=t[s][r],i=1):(i++,i===5?n+=3:i>5&&(n+=1))}return n}function or(t,e){let n=0;for(let r=0;r<e-1;r++)for(let o=0;o<e-1;o++){let i=t[r][o];i===t[r][o+1]&&i===t[r+1][o]&&i===t[r+1][o+1]&&(n+=3)}return n}function Ut(t,e){if(![!0,!1,!0,!0,!0,!1,!0].every((s,a)=>t[e+a]===s))return 0;let o=e>=4&&t.slice(e-4,e).every(s=>!s),i=e+11<=t.length&&t.slice(e+7,e+11).every(s=>!s);return(o?40:0)+(i?40:0)}function ir(t,e){let n=0;for(let r=0;r<e;r++){let o=t[r],i=t.map(s=>s[r]);for(let s=0;s+7<=e;s++)n+=Ut(o,s),n+=Ut(i,s)}return n}function sr(t,e){let n=0;for(let i of t)for(let s of i)s&&n++;let r=e*e;return(Math.ceil(Math.abs(n*20-r*10)/r)-1)*10}function ar(t){let e=t.length,n=0;return n+=rr(t,e),n+=or(t,e),n+=ir(t,e),n+=sr(t,e),n}var Fe="http://www.w3.org/2000/svg";function Qe(t,e={}){let n=e.dark??"#000000",r=e.light??"#ffffff",o=e.quietZone??2,i=t.size+o*2,s="";for(let b=0;b<t.size;b++)for(let E=0;E<t.size;E++)t.modules[b][E]&&(s+=`M${E+o} ${b+o}h1v1h-1z`);let a=document.createElementNS(Fe,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(Fe,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let p=document.createElementNS(Fe,"path");return p.setAttribute("d",s),p.setAttribute("fill",n),a.appendChild(p),a}var jt="/.well-known/enbox-connect";async function Me(t){try{let e=new URL(jt,t).toString(),n=await fetch(e,{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 Xe(t){return await Me(t)!==void 0}import{DidJwk as lr}from"@enbox/dids";import{X25519 as cr}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as dr,openResponse as pr,randomToken as Ht,RelayClientTransport as ur,resolveDelegatePortableDid as fr,sealRequest as mr}from"@enbox/connect";var Ve=6,Q=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function hr(t){return new Promise(e=>{if(typeof document>"u"){setTimeout(e,t);return}let n=()=>{clearTimeout(o),document.removeEventListener("visibilitychange",r),e()},r=()=>{document.visibilityState==="visible"&&n()},o=setTimeout(n,t);document.addEventListener("visibilitychange",r)})}async function Ze(t){if(t.requestType==="refresh"&&t.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let e=t.createTransport??(_=>new ur({..._,sleep:hr})),n=t.cancelled===void 0?void 0:new AbortController,r=e({connectServerUrl:t.connectServerUrl,walletUri:t.walletUri,timeoutMs:t.timeoutMs,pollIntervalMs:t.pollIntervalMs,onClaimed:t.onClaimed,signal:n?.signal}),o=await lr.create(),i=await cr.generateKey(),s={kty:"OKP",crv:"X25519",x:i.x},a=Ht(),d=Ht(),p=await r.requestProfile(d),b={clientDid:o.uri,appName:t.appName,appIcon:t.appIcon,applicationId:t.applicationId,clientMetadata:t.clientMetadata,permissionRequests:t.permissionRequests,delegateDid:t.delegatePortableDid?.uri,requestType:t.requestType,expectedProviderDid:t.expectedProviderDid,supportedDidMethods:["did:dht","did:jwk"],nonce:a,state:d,responseKey:s,reply:p.reply},E=await mr({request:b,signer:o,encryption:p.encryption}),C=await r.deliverRequest(E);C!==void 0&&t.onWalletUriReady(C);let Z=t.cancelled===void 0?r.awaitResponse():Promise.race([r.awaitResponse(),t.cancelled]),u;try{u=await Z}catch(_){throw n?.abort(),_}if(u===dr)return;let y;for(let _=1;_<=Ve;_++){let he=await(t.cancelled===void 0?t.requestPin(_,y):Promise.race([t.requestPin(_,y),t.cancelled])),A=await gr({responseCiphertext:u,responsePrivateKey:i,clientDid:o.uri,nonce:a,state:d,pin:he,expectedProviderDid:t.expectedProviderDid,delegatePortableDid:t.delegatePortableDid,confirmComplete:r.confirmComplete?.bind(r)});if(A.matched)return A.result;y=A.error}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ve} attempts.`)}async function gr(t){try{let e=await pr({jwe:t.responseCiphertext,recipientPrivateKey:t.responsePrivateKey,expected:{clientDid:t.clientDid,nonce:t.nonce,state:t.state,providerDid:t.expectedProviderDid},pin:t.pin}),n=fr({localDelegatePortableDid:t.delegatePortableDid,response:e});return t.confirmComplete?.().catch(()=>{}),{matched:!0,result:{delegatePortableDid:n,delegateGrants:e.delegateGrants,connectedDid:e.providerDid,sessionRevocations:e.sessionRevocations}}}catch(e){let n=e instanceof Error?e:new Error(String(e));if(n.message.startsWith("Connect:"))throw n;return{matched:!1,error:n}}}var Yt="enbox:connect:lastChoice",Ae="enbox:connect:sessionChoices",Gt=20,br=12e4,wr=1e4,Le=4,yr=4,$t=3,et={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 Jt(t){return(await Me(t))?.connectServerUrl}async function Er(t){let e=new J({walletUrl:t.walletUrl,timeoutMs:t.timeoutMs});return await new vr({transport:e}).connect({appName:t.appName,appIcon:t.appIcon,applicationId:t.applicationId,clientMetadata:Se(),permissionRequests:t.permissionRequests,delegatePortableDid:t.delegatePortableDid,requestType:t.requestType,expectedProviderDid:t.expectedProviderDid})}function xr(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function Cr(){return{runRelay:Ze,runPopup:Er,discoverConnectServerUrl:Jt,validateWalletUrl:Xe,isMobile:xr,storage:typeof localStorage>"u"?void 0:localStorage}}function _r(t){try{let e=t?.getItem(Yt);if(e==null)return;let n=JSON.parse(e);if((n.method==="phone"||n.method==="browser")&&Qt(n.walletUrl))return{method:n.method,walletUrl:n.walletUrl}}catch{}}function Pr(t,e){try{t?.setItem(Yt,JSON.stringify(e))}catch{}}function Rr(t){if(typeof t!="object"||t===null)return!1;let e=t;return(e.method==="phone"||e.method==="browser")&&Qt(e.walletUrl)&&typeof e.delegateDid=="string"&&e.delegateDid.length>0&&typeof e.providerDid=="string"&&e.providerDid.length>0}function nt(t){try{let e=t?.getItem(Ae);if(e==null)return[];let n=JSON.parse(e);return Array.isArray(n)?n.filter(Rr).slice(-Gt):[]}catch{return[]}}function kr(t,e,n){if(e===void 0)return;let r=nt(t);for(let o=r.length-1;o>=0;o--){let i=r[o];if(i.delegateDid===e&&(n===void 0||i.providerDid===n))return i}}function Tr(t,e){try{let n=nt(t).filter(r=>r.delegateDid!==e.delegateDid||r.providerDid!==e.providerDid);n.push(e),t?.setItem(Ae,JSON.stringify(n.slice(-Gt)))}catch{}}function Dr(t,e,n){try{let r=nt(t).filter(o=>o.delegateDid!==e||o.providerDid!==n);r.length===0?t?.removeItem(Ae):t?.setItem(Ae,JSON.stringify(r))}catch{}}function Sr(){let t,e={active:!0},n=new Promise((r,o)=>{t=()=>{e.active===!0&&(e.active=!1,o(new Q))}});return n.catch(()=>{}),e.cancelled=n,e.cancel=t,e}function tt(t,e){return()=>t(e)}function rt(t){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");if(t.mode==="refresh"&&t.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let e={...Cr(),...t.deps},n=Mr(t.wallets??[]),r=t.rememberChoice??!0,o=t.appName??window.location.host,i=t.applicationId??window.location.origin,s=e.isMobile(),a=t.mode==="refresh",d=r?_r(e.storage):void 0,p=r&&a?kr(e.storage,t.delegatePortableDid?.uri,t.expectedProviderDid):void 0,b=t.expectedProviderDid??p?.providerDid,E=t.relayWalletPath??"/connect/app",C=t.walletUrl===void 0?"Choose another wallet or method":"Choose another method",Z=d!==void 0&&(a||Kt(n,d.walletUrl))?d.walletUrl:void 0,u=p?.walletUrl??t.walletUrl??Z??n[0]?.url,y=p?.method??t.preferredMethod??d?.method??"phone";return new Promise((_,he)=>{let A=document.createElement("div");A.id="enbox-connect-modal";let ge=A.attachShadow({mode:"open"}),lt=document.createElement("style");lt.textContent=Wr,ge.appendChild(lt);let ee=document.createElement("div");ee.className="overlay";let R=document.createElement("div");R.className="modal",R.setAttribute("role","dialog"),R.setAttribute("aria-modal","true");let ct=a?`Reconnect to ${o}`:`Connect to ${o}`;R.setAttribute("aria-label",ct);let O=t.theme??{},te=O.appearance??"auto";te!=="auto"&&(R.dataset.appearance=te);let Oe=window.matchMedia?.("(prefers-color-scheme: dark)"),Zt=O.accent!==void 0||O.accentContrast!==void 0||O.light!==void 0||O.dark!==void 0,dt=()=>{let l=Oe?.matches===!0?"dark":"light",c=te==="auto"?l:te,g={accent:O.accent,accentContrast:O.accentContrast,...O[c]};for(let f of Object.keys(et)){let w=g[f];typeof w=="string"&&w.trim()!==""?R.style.setProperty(et[f],w):R.style.removeProperty(et[f])}},pt=()=>dt();Zt&&(dt(),te==="auto"&&Oe?.addEventListener?.("change",pt));let k=!1,L,ut,ve,Ue=!1,K,en=()=>K,tn=()=>{K=void 0},ft=new Map,F=[],ne=l=>n.find(c=>c.url===l)??{name:Lr(l)??l,url:l},nn=()=>{if(u===void 0){F=n.slice(0,$t);return}if(F.some(c=>c.url===u))return;let l=ne(u);F=[l,...n.filter(c=>c.url!==l.url)].slice(0,$t)},be=l=>{u=l,z(),oe()},rn=()=>{L?.cancel(),U(),document.removeEventListener("keydown",yt),document.removeEventListener("visibilitychange",Et),Oe?.removeEventListener?.("change",pt);try{A.remove()}catch{}},we=l=>{k||(k=!0,rn(),l())},mt=l=>{r&&u!==void 0&&(Pr(e.storage,{method:y,walletUrl:u}),Tr(e.storage,{delegateDid:l.delegatePortableDid.uri,providerDid:l.connectedDid,method:y,walletUrl:u})),dn(),setTimeout(tt(we,()=>_(l)),1200)},We=()=>we(()=>he(new Error("[@enbox/browser] Connect cancelled.")));R.appendChild(Ar(ct,t.appIcon,We));let N=document.createElement("div");N.className="stage",N.setAttribute("aria-live","polite"),R.appendChild(N);let q=document.createElement("div");q.className="footer",R.appendChild(q);let x=(...l)=>{N.replaceChildren(...l),N.classList.remove("fade-in"),N.offsetWidth,N.classList.add("fade-in")},ht=l=>{x(m("div","spinner"),m("p","stage-caption",l))},on=l=>{let c=L;setTimeout(()=>{k||c!==L||c?.active!==!0||K!==void 0||an(l)},0)},gt=(l,c,g)=>{let f=document.createElement("a");return f.className=g,f.href=l.walletUri,f.target="_blank",f.rel="noopener noreferrer",f.addEventListener("click",()=>{on(c)}),f},sn=l=>{let c=u!==void 0?ne(u):void 0,g=c?.name??"your wallet",f=gt(l,g,"qr-box qr-link");if(f.setAttribute("aria-label",`Open ${g} on this device`),f.replaceChildren(Qe(Ge(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let w=m("div","qr-logo");w.appendChild(pe(c)),f.appendChild(w)}if(s){let w=gt(l,g,"deep-link");c!==void 0&&w.appendChild(pe(c)),w.appendChild(m("span","deep-link-label",`Continue in ${g}`)),f.classList.add("compact"),x(w,m("p","stage-subline",`${g} opens in a new tab \u2014 approve there, then come back for your code.`),m("div","stage-divider","or scan with another phone"),f);return}x(f,m("p","stage-caption","Scan with your phone\u2019s camera"),m("p","stage-subline",`${g} stays on your phone \u2014 or click the code to open it here.`))},an=l=>{x(m("div","spinner"),m("p","stage-caption",`Finish in ${l}`),m("p","stage-subline",s?`Approve the connection in the ${l} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),$("Start over",()=>{Ee()}))},ln=()=>{let l=u!==void 0?ne(u).name:"your wallet",c=document.createElement("div");c.className="claimed-pulse",x(c,m("p","stage-caption",`Request received \u2014 approve in ${l}`),m("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},cn=(l,c)=>new Promise(g=>{K=g;let f=u!==void 0?ne(u).name:"your wallet",w=document.createElement("div");w.className="pin-row",c!==void 0&&w.classList.add("shake");let W=Or(w,en,tn,ht);x(m("p","stage-caption",`Enter the code shown in ${f}`),w,...c!==void 0?[m("p","stage-error",`That code doesn\u2019t match \u2014 check ${f}.`)]:[m("p","stage-subline",l===1?"This confirms you\u2019re the one approving.":"")]),W[0].focus()}),dn=()=>{let l=m("div","check");l.textContent="\u2713",x(l,m("p","stage-caption","You\u2019re connected."))},vt=()=>{x(m("p","stage-caption","No problem \u2014 nothing was shared."),X("Start over",()=>{oe()}),$("Close",tt(we,()=>_(void 0))))},Ne=()=>{p!==void 0&&(L?.cancel(),L=void 0,U(),Dr(e.storage,p.delegateDid,p.providerDid),p=void 0,t.walletUrl!==void 0&&(u=t.walletUrl),z(),x(m("p","stage-caption","Choose another way to reconnect."),m("p","stage-subline","We\u2019ll still require the same wallet profile used for this session.")))},ye=(l,c)=>{x(m("p","stage-caption",l),X("Start over",()=>{oe()}),...p!==void 0?[$(C,Ne)]:[],$("Close",tt(we,()=>he(c??new Error(`[@enbox/browser] ${l}`)))))},pn=()=>{if(p!==void 0){x(m("p","stage-caption","Your saved wallet connection is unavailable right now."),m("p","stage-subline","Try again in a moment to reconnect the same session."),X("Try again",()=>{Ee()}),$(C,Ne));return}x(m("p","stage-caption","This wallet can\u2019t connect by phone here."),m("p","stage-subline","You can continue in this browser instead."),X("Use this browser",()=>{xe()}))},re=s?"tab":"window",un=()=>{let l=u!==void 0?ne(u).name:"your wallet",c=p!==void 0,f=c?`We\u2019ll open the same ${l} profile used for this session.`: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.",W=c?`Open ${l} ${re}`:s?"Open wallet":"Open wallet window";x(m("p","stage-caption",c?`Reconnect with ${l}`:"Connect with a wallet in this browser"),m("p","stage-subline",f),X(W,()=>{xe()}))},fn=()=>{x(m("div","spinner"),m("p","stage-caption",`Finish in the wallet ${re}`),m("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},mn=l=>{x(m("p","stage-caption",l?`Your browser blocked the wallet ${re}.`:`The wallet ${re} was closed.`),X(l?"Open it now":`Reopen ${re}`,()=>{xe()}),...p!==void 0?[$(C,Ne)]:[$(s?"Use a code instead":"Use your phone instead",()=>{wt("phone")})])},hn=l=>{if(k)return;let c=l instanceof Error?l:new Error(String(l)),g=/popup blocked/i.test(c.message);if(l instanceof H||g){mn(g);return}ye(/timed out/i.test(c.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",c)},gn=async l=>{if(t.connectServerUrl!==void 0)return t.connectServerUrl;let c=ft.get(l);return c===void 0&&(c=e.discoverConnectServerUrl(l),ft.set(l,c)),c},U=()=>{clearTimeout(ut),ve=void 0},bt=()=>{!k&&K===void 0&&y==="phone"&&Ee()},vn=l=>{U();let c=Math.max(wr,l*1e3-br);ve=Date.now()+c,ut=setTimeout(bt,c)},Ee=async()=>{if(L?.cancel(),U(),u===void 0){ye("No wallet is configured.");return}y="phone",z(),ht("Getting things ready\u2026");let l=new URL(u).origin,c=await gn(l);if(c===void 0){pn();return}let g=Sr();L=g;try{let f=await e.runRelay({connectServerUrl:c,walletUri:new URL(E,l).toString(),appName:o,appIcon:t.appIcon,applicationId:i,clientMetadata:Se(),permissionRequests:t.permissionRequests,delegatePortableDid:t.delegatePortableDid,requestType:t.mode,expectedProviderDid:b,timeoutMs:t.timeout,cancelled:g.cancelled,onWalletUriReady:w=>{g.active&&!k&&(sn(w),vn(w.expiresIn))},onClaimed:()=>{g.active&&!k&&(U(),ln())},requestPin:(w,W)=>(U(),cn(w,W))});if(!g.active||k)return;f===void 0?vt():mt(f)}catch(f){if(!g.active||k||f instanceof Q)return;let w=f instanceof Error?f:new Error(String(f));ye(/timed out/i.test(w.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",w)}},xe=async()=>{if(L?.cancel(),U(),u===void 0){ye("No wallet is configured.");return}if(!Ue){y="browser",z(),Ue=!0,fn();try{let l=await e.runPopup({walletUrl:u,permissionRequests:t.permissionRequests,appName:o,appIcon:t.appIcon,applicationId:i,timeoutMs:t.timeout,delegatePortableDid:t.delegatePortableDid,requestType:t.mode,expectedProviderDid:b});if(k)return;l===void 0?vt():mt(l)}catch(l){hn(l)}finally{Ue=!1}}},oe=async()=>{y==="browser"?(L?.cancel(),U(),z(),un()):await Ee()},wt=async l=>{y=l,await oe()},z=()=>{if(q.replaceChildren(),p===void 0&&t.walletUrl===void 0){nn();let c=bn();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",y==="phone"&&p===void 0){let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Or connect without a code \u2192":"No phone? Use this browser \u2192",c.addEventListener("click",()=>{xe()}),l.appendChild(c)}else if(y==="browser"&&p===void 0){let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Use a code instead \u2192":"Use your phone instead \u2192",c.addEventListener("click",()=>{wt("phone")}),l.appendChild(c)}l.childElementCount>0&&q.appendChild(l)},bn=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let h of F){let v=document.createElement("button");v.className="row-tile",v.title=h.description??h.name,v.setAttribute("role","radio");let T=h.url===u;v.setAttribute("aria-checked",T?"true":"false"),T&&v.classList.add("selected"),v.appendChild(pe(h)),v.appendChild(m("span","row-tile-name",h.name)),v.addEventListener("click",()=>{h.url!==u&&be(h.url)}),l.appendChild(v)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let g=n.filter(h=>!Kt(F,h.url)),f=document.createElement("button");f.className="row-tile more-tile",f.title="All wallets",f.setAttribute("aria-expanded","false"),f.appendChild(m("span","more-count",g.length>0?`+${g.length}`:"\u22EF")),f.appendChild(m("span","row-tile-name","More")),f.addEventListener("click",()=>{c.hidden=!c.hidden,f.setAttribute("aria-expanded",c.hidden?"false":"true"),c.hidden||Ie()}),l.appendChild(f);let w=F.length>0?m("div","wallet-row-label","Connecting with"):void 0,W=[],ie=document.createElement("div");if(ie.className="wallet-empty",ie.textContent="No other wallets match your search.",ie.hidden=!0,g.length>yr){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 v=h.value.trim().toLowerCase(),T=0;for(let{wallet:Ct,el:wn}of W){let _t=v===""||Ct.name.toLowerCase().includes(v)||Ct.url.toLowerCase().includes(v);wn.hidden=!_t,_t&&(T+=1)}ie.hidden=T>0,Ie()}),c.appendChild(h)}let se=document.createElement("div");se.className="wallet-scroll-wrap",se.hidden=g.length===0;let D=document.createElement("div");D.className="wallet-scroll";let qe=document.createElement("div");qe.className="wallet-grid";let Ie=()=>{let h=D.scrollHeight-D.clientHeight>1,v=D.scrollTop+D.clientHeight>=D.scrollHeight-1;se.classList.toggle("scroll-hint",h&&!v)};D.addEventListener("scroll",Ie);for(let h of g){let v=document.createElement("button");v.className="wallet-tile",v.title=h.description??h.name,v.appendChild(pe(h));let T=document.createElement("span");T.className="wallet-tile-name",T.textContent=h.name,v.appendChild(T),v.addEventListener("click",()=>{be(h.url)}),W.push({wallet:h,el:v}),qe.appendChild(v)}D.appendChild(qe),D.appendChild(ie),se.appendChild(D),c.appendChild(se);let Ce=document.createElement("div");Ce.className="wallet-custom";let S=document.createElement("input");S.className="url-input",S.type="url",S.placeholder="https://your-wallet.example";let M=document.createElement("button");M.className="url-go",M.textContent="Use";let I=document.createElement("div");I.className="url-error",I.hidden=!0;let Be=!1,xt=async()=>{let h=S.value.trim();if(h==="")return;let v;try{v=new URL(h.includes("://")?h:`https://${h}`).origin}catch{S.classList.add("invalid");return}if(Be){be(v);return}M.disabled=!0,M.textContent="Checking\u2026",I.hidden=!0;let T=await e.validateWalletUrl(v);if(M.disabled=!1,T){M.textContent="Use",be(v);return}Be=!0,M.textContent="Use anyway",S.classList.add("invalid"),I.textContent=`Couldn't verify a wallet at ${v}.`,I.hidden=!1};return S.addEventListener("input",()=>{Be=!1,M.textContent="Use",S.classList.remove("invalid"),I.hidden=!0}),S.addEventListener("keydown",h=>{h.key==="Enter"&&xt()}),M.addEventListener("click",()=>{xt()}),Ce.appendChild(S),Ce.appendChild(M),c.appendChild(Ce),c.appendChild(I),{label:w,row:l,panel:c}};ee.addEventListener("click",l=>{l.target===ee&&We()});let yt=l=>{if(l.key==="Escape"){We();return}l.key==="Tab"&&Ur(ge,l)};document.addEventListener("keydown",yt);let Et=()=>{if(!(document.visibilityState!=="visible"||k)){if(ve!==void 0&&Date.now()>=ve){bt();return}K!==void 0&&Array.from(ge.querySelectorAll(".pin-input")).find(c=>c.value==="")?.focus()}};document.addEventListener("visibilitychange",Et),ee.appendChild(R),ge.appendChild(ee),document.body.appendChild(A),z(),oe()})}function Kt(t,e){return t.some(n=>n.url===e)}function Qt(t){if(typeof t!="string"||t.trim()==="")return!1;try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function Mr(t){return t.filter((e,n)=>t.findIndex(r=>r.url===e.url)===n)}function Lr(t){if(t!==void 0)try{return new URL(t).hostname}catch{return t}}function m(t,e,n){let r=document.createElement(t);return r.className=e,n!==void 0&&(r.textContent=n),r}function X(t,e){let n=document.createElement("button");return n.className="stage-btn",n.textContent=t,n.addEventListener("click",e),n}function $(t,e){let n=document.createElement("button");return n.className="footer-link",n.textContent=t,n.addEventListener("click",e),n}function Ar(t,e,n){let r=document.createElement("div");r.className="header";let o=document.createElement("div");if(o.className="header-identity",e!==void 0){let a=document.createElement("img");a.className="header-icon",a.src=e,a.alt="",a.width=24,a.height=24,a.addEventListener("error",()=>a.remove()),o.appendChild(a)}let i=document.createElement("h2");i.textContent=t,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 Or(t,e,n,r){let o=[];for(let s=0;s<Le;s++){let a=document.createElement("input");a.className="pin-input",a.type="text",a.inputMode="numeric",a.maxLength=1,a.setAttribute("aria-label",`Code digit ${s+1}`),o.push(a),t.appendChild(a)}let i=()=>{let s=o.map(d=>d.value).join(""),a=e();if(s.length===Le&&a!==void 0){let d=a;n(),r("Checking the code\u2026"),d(s)}};return o.forEach((s,a)=>{s.addEventListener("input",()=>{s.value=s.value.replace(/\D/g,"").slice(0,1),s.value!==""&&a+1<o.length&&o[a+1].focus(),i()}),s.addEventListener("keydown",d=>{d.key==="Backspace"&&s.value===""&&a>0&&o[a-1].focus()}),s.addEventListener("paste",d=>{let p=(d.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Le);p.length!==0&&(d.preventDefault(),p.split("").forEach((b,E)=>{o[E]!==void 0&&(o[E].value=b)}),o[Math.min(p.length,Le)-1]?.focus(),i())})}),o}function Ur(t,e){let n=Array.from(t.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=t.activeElement;e.shiftKey&&(i===r||i===null)?(e.preventDefault(),o.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r.focus())}var Ft=`
155
155
  --ec-bg: #ffffff;
156
156
  --ec-surface: #f5f6f8;
157
157
  --ec-text: #17171f;
@@ -160,7 +160,7 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
160
160
  --ec-accent: #0a62d0;
161
161
  --ec-accent-contrast: #ffffff;
162
162
  --ec-danger: #c0392b;
163
- --ec-success: #1e9e5a;`,Nt=`
163
+ --ec-success: #1e9e5a;`,zt=`
164
164
  --ec-bg: #181822;
165
165
  --ec-surface: #23232f;
166
166
  --ec-text: #e9e9f0;
@@ -169,7 +169,7 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
169
169
  --ec-accent: #58a6ff;
170
170
  --ec-accent-contrast: #0b1526;
171
171
  --ec-danger: #ff7a7a;
172
- --ec-success: #43d17c;`,Eo=`
172
+ --ec-success: #43d17c;`,Wr=`
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{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
204
204
  50% { transform: scale(1); opacity: 1; }
205
205
  }
206
206
 
207
- .modal {${Wt}
207
+ .modal {${Ft}
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{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
220
220
  flex-direction: column;
221
221
  }
222
222
  @media (prefers-color-scheme: dark) {
223
- .modal {${Nt}
223
+ .modal {${zt}
224
224
  }
225
225
  }
226
- .modal[data-appearance='light'] {${Wt}
226
+ .modal[data-appearance='light'] {${Ft}
227
227
  }
228
- .modal[data-appearance='dark'] {${Nt}
228
+ .modal[data-appearance='dark'] {${zt}
229
229
  }
230
230
 
231
231
  button, input { font-family: inherit; }
@@ -536,5 +536,5 @@ import{AudienceDecryptError as ur,createConnectionStore as fr,ContextNotReadyErr
536
536
  .overlay, .modal, .stage.fade-in > *, .pin-row.shake { animation: none; }
537
537
  .claimed-pulse::after { animation: none; }
538
538
  }
539
- `;var It=[{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:"Sumi",url:"https://sumi-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"},{name:"Quay",url:"https://quay-id.pages.dev",description:"A safe harbor for your digital identity"},{name:"Quoin",url:"https://quoin-id.pages.dev",description:"A cornerstone for your digital identity"}];function xo(e={}){let{wallets:t=It,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:a,rememberChoice:s,connectServerUrl:d,relayWalletPath:p,theme:v}=e;return{async requestAccess(f){return Je({wallets:t,walletUrl:n,preferredMethod:a,rememberChoice:s,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:p,timeout:r,theme:v,mode:f.requestType,delegatePortableDid:f.delegatePortableDid,permissionRequests:f.permissionRequests})}}}import{X25519 as Co}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Po,ConnectProvider as Ro}from"@enbox/connect";var _o=3e5,ko=5e3,Xe=class e{constructor(t){this._requestReceived=!1;this._dappOrigin=t.dappOrigin,this._dappWindow=t.dappWindow,this._recipientPrivateKey=t.recipientPrivateKey;let n=Ce();this._requestPromise=n.promise,this._resolveRequest=n.resolve,this._rejectRequest=n.reject,this._messageListener=r=>{this.onMessage(r)},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 TypeError("[@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=To(t.dappOrigin),o=await Co.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},a=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??_o});return n.postMessage({type:ae,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:F,payload:t},this._dappOrigin),this.close()}async sendResponseAwaitingAck(t,n={}){let r=new Promise(a=>{this._resolveAck=a});this._dappWindow.postMessage({type:F,payload:t},this._dappOrigin);let o=setTimeout(()=>{this._resolveAck?.(!1)},n.timeoutMs??ko),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(Po)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=Pe(t,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===le){this._resolveAck?.(!0);return}if(!(n.type!==se||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 Ro.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 To(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{Record as ei}from"@enbox/api";import{BrowserStorage as ni}from"@enbox/auth/browser";import{createProfileReader as ri,isRetryableProfileReadStatus as ii}from"@enbox/protocols";import{DwnInterface as si}from"@enbox/agent";import{DateSort as ci,DwnInterfaceName as di,DwnMethodName as pi}from"@enbox/dwn-sdk-js";export{ur as AudienceDecryptError,Sr as AuthManager,Dr as AuthSession,xo as BrowserConnectHandler,ni as BrowserStorage,jr as CONNECT_DENIED_TOKEN,Or as ConnectDeniedError,Kr as ConnectProvider,mr as ContextNotReadyError,hr as ContextRetiredError,It as DEFAULT_WALLETS,le as DWEB_CONNECT_ACK_MESSAGE_TYPE,ae as DWEB_CONNECT_LOADED_MESSAGE_TYPE,Ue as DWEB_CONNECT_PATH,se as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,F as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,ci as DateSort,si as DwnInterface,di as DwnInterfaceName,pi as DwnMethodName,wr as DwnResponseError,vr as Enbox,Fe as MAX_PIN_ATTEMPTS,Y as PopupClientTransport,B as PopupWindowClosedError,Er as ProtocolReadinessError,ei as Record,xr as RecordConflictError,Cr as RecordParentNotFoundError,Pr as RecordSquashBackstopError,Rr as RecordValidationError,V as RelayConnectCancelledError,Ar as SESSION_EXPIRED_ERROR_CODE,Lr as SESSION_REVOKED_ERROR_CODE,Tr as ServiceConfigProtocol,Dt as WALLET_WELL_KNOWN_PATH,Hr as WalletConnect,Xe as WalletPostMessageTransport,Oo as activatePolyfills,un as cacheResponse,Lo as clearDrlCache,Wr as computeConnectionStatus,Mn as connectViaPopup,fr as createConnectionStore,ri as createProfileReader,Ao as deactivatePolyfills,gr as defineApplicationManifest,br as defineProtocol,Ut as discoverWalletConnectServerUrl,Ke as encodeQr,pn as fetchResource,_e as fetchWalletWellKnown,yr as getApplicationProtocolRequests,yt as getDwnEndpoints,dn as handleEvent,Nr as isConnectDeniedError,ii as isRetryableProfileReadStatus,qr as isSessionExpiredError,Ur as isSessionInvalidError,Ir as normalizeProtocolRequests,te as parseDrlUrl,Ge as probeWalletWellKnown,_r as protocolContextKey,ze as qrToSvg,kr as recordCodecs,Je as runConnectModal,Ye as runRelayConnect};
539
+ `;var Xt=[{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:"Sumi",url:"https://sumi-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"},{name:"Quay",url:"https://quay-id.pages.dev",description:"A safe harbor for your digital identity"},{name:"Quoin",url:"https://quoin-id.pages.dev",description:"A cornerstone for your digital identity"}];function Nr(t={}){let{wallets:e=Xt,walletUrl:n,timeout:r,appName:o,appIcon:i,applicationId:s,preferredMethod:a,rememberChoice:d,connectServerUrl:p,relayWalletPath:b,theme:E}=t;return{async requestAccess(C){return rt({wallets:e,walletUrl:n,preferredMethod:a,rememberChoice:d,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,applicationId:s,connectServerUrl:p,relayWalletPath:b,timeout:r,theme:E,mode:C.requestType,delegatePortableDid:C.delegatePortableDid,expectedProviderDid:C.expectedProviderDid,permissionRequests:C.permissionRequests})}}}import{X25519 as qr}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Ir,ConnectProvider as Br}from"@enbox/connect";var jr=3e5,Hr=5e3,ot=class t{constructor(e){this._requestReceived=!1;this._dappOrigin=e.dappOrigin,this._dappWindow=e.dappWindow,this._recipientPrivateKey=e.recipientPrivateKey;let n=Te();this._requestPromise=n.promise,this._resolveRequest=n.resolve,this._rejectRequest=n.reject,this._messageListener=r=>{this.onMessage(r)},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 TypeError("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let n=e.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=$r(e.dappOrigin),o=await qr.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new t({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:e.timeoutMs??jr});return n.postMessage({type:ue,walletEpk:i,walletOrigin:globalThis.location.origin},r),s}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(e){this._dappWindow.postMessage({type:G,payload:e},this._dappOrigin),this.close()}async sendResponseAwaitingAck(e,n={}){let r=new Promise(s=>{this._resolveAck=s});this._dappWindow.postMessage({type:G,payload:e},this._dappOrigin);let o=setTimeout(()=>{this._resolveAck?.(!1)},n.timeoutMs??Hr),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(Ir)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(e){let n=De(e,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===me){this._resolveAck?.(!0);return}if(!(n.type!==fe||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(e){try{let n=await Br.openRequest({jwe:e,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(e){if(clearTimeout(this._timeoutId),e instanceof Error){this.close(),this._rejectRequest(e);return}this._resolveRequest(e)}};function $r(t){if(t!==void 0)return new URL(t).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.")}function Kr(t){if(!Number.isSafeInteger(t)||t<0||t>2147483647)throw new TypeError("delayMs must be an integer between 0 and 2147483647.")}var V=class{constructor(e,n){this._onEmpty=n;this._isRevoked=!1;this._references=0;this._releaseTimers=new Set;this.url=globalThis.URL.createObjectURL(e)}get references(){return this._references}acquire(){if(this._isRevoked)throw new Error("Object URL has been revoked.");this._references+=1;let e=!1,n,r=()=>{e||(e=!0,n!==void 0&&(clearTimeout(n),this._releaseTimers.delete(n)),!this._isRevoked&&(this._references-=1,this._references===0&&this._onEmpty(this)))};return Object.freeze({url:this.url,release:r,releaseAfter:o=>{Kr(o),!(e||this._isRevoked||n!==void 0)&&(n=setTimeout(r,o),this._releaseTimers.add(n))}})}revoke(){if(!this._isRevoked){this._isRevoked=!0;for(let e of this._releaseTimers)clearTimeout(e);this._releaseTimers.clear(),this._references=0,globalThis.URL.revokeObjectURL(this.url)}}};var it=class{constructor(){this._references=new Map;this._isDisposed=!1}acquire(e){if(this._isDisposed)throw new Error("BlobUrlPool is disposed.");let n=this._references.get(e);return n===void 0&&(n=new V(e,r=>{this._references.delete(e),r.revoke()}),this._references.set(e,n)),n.acquire()}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let e of this._references.values())e.revoke();this._references.clear()}}};function Fr(){return new it}var zr=128*1024*1024,Yr=50;function Vt(t,e){if(t!==1/0&&(!Number.isSafeInteger(t)||t<0))throw new TypeError(`${e} must be a non-negative safe integer or Infinity.`)}function st(t){throw t.abort(),t.signal.reason}var at=class{constructor(e){this._options=e;this._cache=new Map;this._entries=new Set;this._pending=new Map;this._bytes=0;this._generation=0;this._isDisposed=!1;this._maxBytes=e.maxBytes??zr,this._maxEntries=e.maxEntries??Yr,Vt(this._maxBytes,"maxBytes"),Vt(this._maxEntries,"maxEntries")}async acquire(e){this._assertActive();let n=this._options.key(e),r=this._cache.get(n);if(r!==void 0)return this._acquire(r);let o=this._pending.get(n)??this._startRead(e,n),i=await o.promise;if(this._isDisposed||o.generation!==this._generation)return st(o.controller);if(i!==void 0)return this._cache.get(n)!==i?st(o.controller):this._acquire(i)}acquireCached(e){this._assertActive();let n=this._cache.get(this._options.key(e));return n===void 0?void 0:this._acquire(n)}invalidate(e){this._assertActive();let n=this._options.key(e);this._pending.get(n)?.controller.abort(),this._pending.delete(n);let o=this._cache.get(n);o!==void 0&&this._remove(o)}clear(){this._assertActive(),this._reset(!1)}dispose(){this._isDisposed||(this._isDisposed=!0,this._reset(!0))}_abortReads(){for(let e of this._pending.values())e.controller.abort();this._pending.clear()}_acquire(e){this._cache.delete(e.key),this._cache.set(e.key,e);let n=e.url.acquire();return this._evict(),Object.freeze({filename:e.filename,mimeType:e.mimeType,release:n.release,releaseAfter:n.releaseAfter,url:n.url})}_assertActive(){if(this._isDisposed)throw new Error("FileEnvelopeUrlStore is disposed.")}_assertCurrent(e,n,r){(this._isDisposed||n.signal.aborted||this._generation!==r||this._pending.get(e)?.controller!==n)&&st(n)}_evict(){for(;this._cache.size>this._maxEntries||this._bytes>this._maxBytes;){let e=[...this._cache.values()].find(n=>n.url.references===0);if(e===void 0)return;this._remove(e)}}async _load(e,n,r,o){let i=await this._options.read(e,r.signal);if(this._assertCurrent(n,r,o),i===void 0)return;let s=this._options.blobForUrl(i);this._assertCurrent(n,r,o);let a=new V(s,()=>this._released(d)),d={bytes:s.size,filename:i.filename,key:n,mimeType:i.mimeType,url:a};return this._cache.set(n,d),this._bytes+=d.bytes,this._entries.add(d),d}_released(e){this._cache.get(e.key)!==e?this._revoke(e):this._evict()}_remove(e){this._cache.get(e.key)===e&&(this._cache.delete(e.key),this._bytes-=e.bytes,e.url.references===0&&this._revoke(e))}_reset(e){this._generation+=1,this._abortReads(),this._cache.clear(),this._bytes=0;for(let n of this._entries)(e||n.url.references===0)&&this._revoke(n)}_revoke(e){e.url.revoke(),this._entries.delete(e)}_startRead(e,n){let r=new AbortController,o=this._generation,i=this._load(e,n,r,o).finally(()=>{this._pending.get(n)?.controller===r&&this._pending.delete(n)}),s={controller:r,generation:o,promise:i};return this._pending.set(n,s),s}};function Gr(t){return new at(t)}import{createProfileReader as ei,isRetryableProfileReadStatus as ti}from"@enbox/protocols";import{DwnInterface as ri}from"@enbox/agent";import{DateSort as ii,DwnInterfaceName as si,DwnMethodName as ai}from"@enbox/dwn-sdk-js";export{Nr as BrowserConnectHandler,Bo as CONNECT_DENIED_TOKEN,jo as ConnectProvider,Xt as DEFAULT_WALLETS,me as DWEB_CONNECT_ACK_MESSAGE_TYPE,ue as DWEB_CONNECT_LOADED_MESSAGE_TYPE,$e as DWEB_CONNECT_PATH,fe as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,G as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,ii as DateSort,ri as DwnInterface,si as DwnInterfaceName,ai as DwnMethodName,Ve as MAX_PIN_ATTEMPTS,J as PopupClientTransport,H as PopupWindowClosedError,Q as RelayConnectCancelledError,jt as WALLET_WELL_KNOWN_PATH,ot as WalletPostMessageTransport,Vr as activatePolyfills,Pn as cacheResponse,eo as clearDrlCache,Hn as connectViaPopup,Fr as createBlobUrlPool,Gr as createFileEnvelopeUrlStore,ei as createProfileReader,Zr as deactivatePolyfills,Jt as discoverWalletConnectServerUrl,Ge as encodeQr,_n as fetchResource,Me as fetchWalletWellKnown,St as getDwnEndpoints,Cn as handleEvent,ti as isRetryableProfileReadStatus,ae as parseDrlUrl,Xe as probeWalletWellKnown,Qe as qrToSvg,rt as runConnectModal,Ze as runRelayConnect};
540
540
  //# sourceMappingURL=browser.mjs.map