@seams/wallet 0.15.1 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +2 -2
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/icons.js +23 -1
- package/dist/esm/sdk/{host-DYuu07E5.js → host-z-JJRWQe.js} +1 -1
- package/dist/esm/sdk/runtime-auth-ZcxkQ-XF.js +1 -0
- package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/esm/sdk/wallet-ui.css +1 -1
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{host-DYuu07E5.js → host-z-JJRWQe.js} +1 -1
- package/dist/public/sdk/runtime-auth-ZcxkQ-XF.js +1 -0
- package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/public/sdk/wallet-ui.css +1 -1
- package/dist/public/wallet-assets.manifest.json +6 -6
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/icons.d.ts +1 -0
- package/package.json +1 -1
- package/dist/esm/sdk/runtime-auth-BNR1wI8E.js +0 -1
- package/dist/public/sdk/runtime-auth-BNR1wI8E.js +0 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"packageName": "@seams/wallet",
|
|
4
|
-
"packageVersion": "0.15.
|
|
4
|
+
"packageVersion": "0.15.2",
|
|
5
5
|
"assetRoot": "dist/public",
|
|
6
6
|
"sdkBasePath": "/sdk",
|
|
7
7
|
"walletServicePath": "/wallet-service",
|
|
8
8
|
"headersManifest": "headers.manifest.json",
|
|
9
9
|
"versionSkewContract": {
|
|
10
10
|
"kind": "wallet_iframe_protocol_handshake",
|
|
11
|
-
"packageVersion": "0.15.
|
|
11
|
+
"packageVersion": "0.15.2",
|
|
12
12
|
"protocolVersion": "16.0.0",
|
|
13
13
|
"readyPayloadField": "protocolVersion",
|
|
14
14
|
"failureMode": "typed_error",
|
|
@@ -970,8 +970,8 @@
|
|
|
970
970
|
]
|
|
971
971
|
},
|
|
972
972
|
{
|
|
973
|
-
"route": "/sdk/host-
|
|
974
|
-
"sourceFile": "sdk/host-
|
|
973
|
+
"route": "/sdk/host-z-JJRWQe.js",
|
|
974
|
+
"sourceFile": "sdk/host-z-JJRWQe.js",
|
|
975
975
|
"owner": "wallet_sdk_asset",
|
|
976
976
|
"routeClass": "javascript",
|
|
977
977
|
"contentType": "text/javascript; charset=utf-8",
|
|
@@ -1810,8 +1810,8 @@
|
|
|
1810
1810
|
]
|
|
1811
1811
|
},
|
|
1812
1812
|
{
|
|
1813
|
-
"route": "/sdk/runtime-auth-
|
|
1814
|
-
"sourceFile": "sdk/runtime-auth-
|
|
1813
|
+
"route": "/sdk/runtime-auth-ZcxkQ-XF.js",
|
|
1814
|
+
"sourceFile": "sdk/runtime-auth-ZcxkQ-XF.js",
|
|
1815
1815
|
"owner": "wallet_sdk_asset",
|
|
1816
1816
|
"routeClass": "javascript",
|
|
1817
1817
|
"contentType": "text/javascript; charset=utf-8",
|
|
@@ -5,14 +5,14 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
6
|
<title>Web3Authn Wallet Service</title>
|
|
7
7
|
<!-- Surface styles are external so strict CSP can keep style-src 'self' -->
|
|
8
|
-
<link rel="stylesheet" href="/sdk/wallet-ui.css?v=0.15.
|
|
8
|
+
<link rel="stylesheet" href="/sdk/wallet-ui.css?v=0.15.2" />
|
|
9
9
|
<!-- Minimal shims some ESM bundles expect (externalized to enable strict CSP) -->
|
|
10
|
-
<script src="/sdk/wallet-shims.js?v=0.15.
|
|
10
|
+
<script src="/sdk/wallet-shims.js?v=0.15.2"></script>
|
|
11
11
|
<!-- Hint the browser to fetch the host script earlier -->
|
|
12
|
-
<link rel="modulepreload" href="/sdk/wallet-iframe-host-runtime.js?v=0.15.
|
|
12
|
+
<link rel="modulepreload" href="/sdk/wallet-iframe-host-runtime.js?v=0.15.2" crossorigin>
|
|
13
13
|
</head>
|
|
14
14
|
<body>
|
|
15
15
|
<!-- sdkBasePath points to the SDK root (e.g. '/sdk'). Load the host directly. -->
|
|
16
|
-
<script type="module" src="/sdk/wallet-iframe-host-runtime.js?v=0.15.
|
|
16
|
+
<script type="module" src="/sdk/wallet-iframe-host-runtime.js?v=0.15.2"></script>
|
|
17
17
|
</body>
|
|
18
18
|
</html>
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** @jsxImportSource preact */
|
|
2
2
|
import type { ComponentChildren } from 'preact';
|
|
3
3
|
export declare function fingerprintIcon(): ComponentChildren;
|
|
4
|
+
export declare function passkeyRingIcon(): ComponentChildren;
|
|
4
5
|
export declare function accountDropdownIcon(): ComponentChildren;
|
|
5
6
|
export declare function backIcon(): ComponentChildren;
|
|
6
7
|
export declare function linkDeviceIcon(): ComponentChildren;
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{M as e,O as t}from"./domainIds-BzkGsRqO.js";import{k as n}from"./chains-C_X_fNuS.js";import"./primitives-CqrjmIAH.js";import"./walletDbName-DtRewci9.js";import"./signingSessionSeal-DX41aXUL.js";import{a as r,c as i,d as a,l as o,u as s}from"./sessionObservationRevision-CnEOLDbl.js";import{C as c,S as l,T as u,_ as ee,a as te,b as ne,c as re,d as ie,f as d,g as ae,h as oe,l as se,m as f,n as p,r as ce,s as le,t as ue,u as de,v as fe,w as pe,x as me,y as he}from"./shared-BywEqTsd.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import{t as ge}from"./walletIframeIdentity-Cz82I_Uh.js";import"./errors-DIWY1KR9.js";import{en as _e,i as ve,n as ye,nn as be,r as xe,s as Se}from"./registration-DEGZR8kA.js";import"./accountIds-Cpvlkvbe.js";import"./registrationSignerPlan-CPzHavPM.js";import{a as m}from"./signerDomain-Dp7BhfmZ.js";import"./registrationIntent-090Zj7Iu.js";import"./singletons-BXhnsqeY.js";import"./walletAuthority-CAiGuWW2.js";import"./emailOtpEcdsaDerivationIdentity-Bik0N8v9.js";import{t as Ce}from"./challengeDelivery-CATQ4u6P.js";import"./digestEncoding-BX3VW9eF.js";import{a as we,n as Te}from"./registrationIds-BaK3jUS6.js";import"./passkey-custody-DpTM-eNJ.js";import{c as Ee,i as De,s as Oe}from"./sdkSentEvents-D4KtK7_I.js";import"./walletCustodyEcdsaContinuity-B4fTDL10.js";import"./keccak-mS0Mejjx.js";import{g as ke,p as Ae}from"./wallet-recovery-Bfhfk52N.js";import"./nearEd25519YaoMaterialActivation-Bo3IOTS-.js";import{t as je}from"./walletSessionAuthorizationStatus-BL7j2TeM.js";import{a as Me,i as Ne}from"./adapters-DsAaBNNY.js";import{t as Pe}from"./surface-measurement-reporter-DvVHPu_O.js";import"./signNear-XGZBxc_g.js";import{a as Fe,c as h,i as Ie,l as g,n as Le,o as _,t as v}from"./jsxRuntime.module-DKsgiFjd.js";function Re(e){return{PM_GET_LAST_WALLET_MOVE_REQUEST:He.bind(null,e),PM_MOVE_WALLET:Ve.bind(null,e),PM_GET_WALLET_PLACEMENT:ze.bind(null,e),PM_GET_WALLET_MOVE:Be.bind(null,e)}}async function ze(e,r){let i=n(r.payload,`Wallet placement request`),a=t(i.walletId);if(!a.ok||Object.keys(i).length!==1)throw Error(`Wallet placement identity is invalid`);let o=await e.getWalletRuntime().placement.get(a.value);e.respondIfCancelled(r.requestId)||p(e,r.requestId,o)}async function Be(e,r){let i=n(r.payload,`Wallet move request`),a=t(i.walletId),o=se(i.moveId);if(!a.ok||Object.keys(i).length!==2)throw Error(`Wallet move request is invalid`);let s=await e.getWalletRuntime().placement.getMove(a.value,o);e.respondIfCancelled(r.requestId)||p(e,r.requestId,s)}async function Ve(e,t){let n=de(t.payload),r=await e.getWalletRuntime().placement.move(n);e.respondIfCancelled(t.requestId)||p(e,t.requestId,r)}async function He(e,r){let i=n(r.payload,`Wallet move locator request`),a=t(i.walletId);if(!a.ok||Object.keys(i).length!==1)throw Error(`Wallet move locator identity is invalid`);let o=await e.getWalletRuntime().placement.getLastMoveRequest(a.value);e.respondIfCancelled(r.requestId)||p(e,r.requestId,o)}function Ue(e){if(!e)throw Error(`PM_UNLOCK payload is required`);return e}function We(e){switch(e.kind){case`default_options`:return{};case`custom_options`:return{...y(`signerSlot`,e.options.signerSlot),...y(`signingSession`,e.options.signingSession),...y(`unlockSelection`,e.options.unlockSelection),...Ge(e.options.ecdsaKeyFactsInventory)}}}function Ge(e){switch(e.kind){case`default`:return{};case`value`:return{ecdsaKeyFactsInventory:e.value}}}function y(e,t){switch(t.kind){case`default`:return{};case`value`:return{[e]:t.value}}}function b(e){return e===`register`?`Creating passkey wallet…`:`Unlocking wallet…`}const Ke=/\bHTTP 429\b|too many requests|rate limit/i,qe=/\bHTTP 5\d\d\b|failed to fetch|load failed|networkerror|network request failed|connection ?closed/i,Je=/timed out|timeout/i;function Ye(e){return Ke.test(e)?`Too many attempts. Wait a moment.`:qe.test(e)?`Can’t reach Seams right now.`:Je.test(e)?`That took too long.`:`Something went wrong.`}function x(e){return{kind:`recoverable`,reason:`error`,message:Ye(e),detail:e}}function S(e,t){let n=t?e.find(e=>e.walletId===t.walletId&&e.authMethod===t.authMethod):null,r=t?e.find(e=>e.walletId===t.walletId):null,i=n??r??e[0];if(!i)return{kind:`discoverable`,selectedAccount:null,loginTarget:{kind:`discoverable`}};let a=e.filter(e=>e.walletId===i.walletId),o=a.some(e=>e.authMethod===`passkey`),s=a.some(e=>e.authMethod===`email_otp`),c={selectedAccount:i,walletId:i.walletId,loginTarget:{kind:`wallet`,walletId:i.walletId}};if(o&&s)return{kind:`passkey_and_email_otp`,...c};if(o)return{kind:`passkey`,...c};if(s)return{kind:`email_otp`,...c};throw Error(`Selected auth-menu account has no supported authentication method`)}function C(e){switch(e.kind){case`discoverable`:case`passkey`:case`passkey_and_email_otp`:return!0;case`email_otp`:return!1}}function w(e){switch(e.kind){case`discoverable`:case`email_otp`:case`passkey_and_email_otp`:return!0;case`passkey`:return!1}}function T(e){return e.kind===`busy`}function Xe(e){let t=e.status;return t.kind===`idle`&&t.interaction===`actionable`}function E(e){let t=e.status;return t.kind===`recoverable`?!0:t.kind===`idle`&&t.interaction===`actionable`}function D(e){if(!E(e))return!1;switch(e.kind){case`google_otp_login`:return!e.submitBusy&&/^\d{6}$/.test(e.otpCode);case`google_registration`:return!e.rerollBusy&&!e.submitBusy;case`link_device`:return!1;case`recovery`:return e.stage===`passkey_ready`||e.stage===`google_ready`||e.stage===`sign_in_ready`||e.stage===`email_code_required`&&/^\d{6}$/.test(e.otpCode);case`passkey`:return e.mode===`login`?C(S(e.accountOptions,e.selectedAccount)):!e.showRegistrationInput||e.passkeyName.trim().length>0}}function O(e){return E(e)?e.kind!==`passkey`||e.mode!==`login`?!0:w(S(e.accountOptions,e.selectedAccount)):!1}const Ze=()=>new Promise(e=>setTimeout(e,90));function Qe(e){return e.dataset.blink?null:(e.dataset.blink=`off`,Ze().then(()=>(e.dataset.blink=`on`,Ze())).then(()=>{delete e.dataset.blink}))}function k(e,t,...n){return v(g,{children:v(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":t,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`,children:n})})}function A(){return k(`22`,`1.5`,v(`path`,{d:`M6.405 19.048c.184-.443.353-.894.507-1.351`}),v(`path`,{d:`M14.343 20.693c.266-.751.502-1.516.707-2.294.186-.706.346-1.422.478-2.147`}),v(`path`,{d:`M19.448 17.058c.364-1.964.555-3.989.555-6.058 0-4.418-3.582-8-8-8-1.255 0-2.443.289-3.501.805`}),v(`path`,{d:`M3.523 15.025c.314-1.29.48-2.638.48-4.025 0-1.74.556-3.351 1.499-4.664`}),v(`path`,{d:`M12.003 11c0 2.76-.447 5.416-1.273 7.899-.213.639-.451 1.266-.712 1.881`}),v(`path`,{d:`M7.712 14.5c.191-1.138.291-2.308.291-3.5 0-2.209 1.791-4 4-4s4 1.791 4 4c0 .617-.02 1.229-.058 1.836`}))}function $e(){return v(g,{children:v(`svg`,{class:`seams-account-dropdown-arrow`,viewBox:`0 0 24 24`,"aria-hidden":`true`,focusable:`false`,children:v(`path`,{d:`M9.75 3h4.5v10.28l4.3-4.3 3.18 3.18L12 21.9l-9.73-9.74 3.18-3.18 4.3 4.3V3Z`})})})}function et(){return k(`18`,`2.25`,v(`path`,{d:`m15 18-6-6 6-6`}))}function tt(){return k(`18`,`2`,v(`rect`,{width:`5`,height:`5`,x:`3`,y:`3`,rx:`1`}),v(`rect`,{width:`5`,height:`5`,x:`16`,y:`3`,rx:`1`}),v(`rect`,{width:`5`,height:`5`,x:`3`,y:`16`,rx:`1`}),v(`path`,{d:`M21 16h-3a2 2 0 0 0-2 2v3`}),v(`path`,{d:`M21 21v.01`}),v(`path`,{d:`M12 7v3a2 2 0 0 1-2 2H7`}),v(`path`,{d:`M3 12h.01`}),v(`path`,{d:`M12 3h.01`}),v(`path`,{d:`M12 16v.01`}),v(`path`,{d:`M16 12h1`}),v(`path`,{d:`M21 12v.01`}),v(`path`,{d:`M12 21v-1`}))}function nt(){return k(`18`,`2`,v(`path`,{d:`M20 11v6`}),v(`path`,{d:`M20 13h2`}),v(`path`,{d:`M3 21v-2a4 4 0 0 1 4-4h6a4 4 0 0 1 2.072.578`}),v(`circle`,{cx:`10`,cy:`7`,r:`4`}),v(`circle`,{cx:`20`,cy:`19`,r:`2`}))}function rt(){return k(`21`,`1.75`,v(`rect`,{x:`2.75`,y:`5`,width:`18.5`,height:`14`,rx:`2.75`}),v(`path`,{d:`m3.75 7.75 6.94 4.86a2.25 2.25 0 0 0 2.62 0l6.94-4.86`}))}function it(){return k(`22`,`1.75`,v(`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`}),v(`path`,{d:`M15 7h2a5 5 0 0 1 3.54 8.54`}),v(`path`,{d:`m2 2 20 20`}),v(`path`,{d:`M8 12h3`}))}function at(){return v(g,{children:v(`svg`,{class:`seams-input-action-icon`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`,children:[v(`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`}),v(`path`,{d:`M21 3v5h-5`}),v(`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`}),v(`path`,{d:`M8 16H3v5`})]})})}function j(){return v(`svg`,{width:`18`,height:`18`,viewBox:`0 0 48 48`,"aria-hidden":`true`,children:[v(`path`,{fill:`#EA4335`,d:`M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z`}),v(`path`,{fill:`#4285F4`,d:`M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z`}),v(`path`,{fill:`#FBBC05`,d:`M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z`}),v(`path`,{fill:`#34A853`,d:`M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z`})]})}function ot(){return k(`13`,`1.75`,v(`path`,{d:`m9 6 6 6-6 6`}))}function st(){return k(`14`,`1.6`,v(`path`,{d:`M12 3 4.5 6v5.5c0 4.2 2.7 7.4 7.5 9.5 4.8-2.1 7.5-5.3 7.5-9.5V6L12 3Z`}),v(`path`,{d:`m8.5 11.5 2.5 2.5 4.5-5`}))}function ct(){return k(`15`,`1.6`,v(`path`,{d:`M12 8v5`}),v(`path`,{d:`M12 16v.1`}),v(`circle`,{cx:`12`,cy:`12`,r:`9`}))}var lt=class extends _{constructor(...e){super(...e),this.shownNotice=``}render(){let{notice:e,onRetry:t}=this.props;return e&&(this.shownNotice=e),v(`div`,{class:`seams-auth-footer`,"data-state":e?`notice`:`brand`,children:[v(`div`,{class:`seams-auth-footer-brand`,"aria-hidden":e?`true`:void 0,children:[st(),` `,v(`span`,{children:`Secured by`}),` `,v(Ne,{})]}),v(`div`,{class:`seams-auth-footer-notice`,children:[ct(),v(`span`,{class:`seams-auth-footer-text`,"aria-hidden":`true`,children:this.shownNotice}),v(`button`,{class:`seams-auth-footer-action`,type:`button`,disabled:!e,onClick:t,children:`Try again`})]}),e?v(`p`,{class:`sr-only`,role:`alert`,children:e}):null]})}};function ut(e,t){return v(g,{children:v(`div`,{class:`seams-link-device-dot-ring is-${e}`,"aria-hidden":`true`,children:[Array.from({length:12},(e,t)=>v(g,{children:v(`span`,{"data-dot-index":t})})),t?v(g,{children:v(`div`,{class:`seams-link-device-dot-ring-glyph`,children:t})}):null,v(`svg`,{class:`seams-link-device-dot-ring-check`,viewBox:`0 0 52 52`,fill:`none`,stroke:`currentColor`,"stroke-width":`2.5`,"stroke-linecap":`round`,"stroke-linejoin":`round`,children:v(`path`,{d:`m18.5 27 5 5 10-11`})})]})})}function dt(e){switch(e.kind){case`sending`:return{ring:`waiting`,heading:`Sending your code`,status:`Emailing a 6-digit code`,pending:!0,tone:`neutral`};case`resending`:return{ring:`waiting`,heading:`Sending a new code`,status:`Emailing a fresh 6-digit code`,pending:!0,tone:`neutral`};case`submitting`:return{ring:`waiting`,heading:`Checking your code`,status:`Verifying the code you entered`,pending:!0,tone:`neutral`};case`code_input`:return{ring:`idle`,heading:`Verify your email`,status:`Enter the 6-digit code we just sent.`,pending:!1,tone:`neutral`};case`incorrect`:return{ring:`idle`,heading:`Verify your email`,status:e.message,pending:!1,tone:`error`};case`expired`:return{ring:`idle`,heading:`That code expired`,status:e.message,pending:!1,tone:`error`};case`unavailable`:return{ring:`idle`,heading:`Email code unavailable`,status:e.message,pending:!1,tone:`error`};case`completed`:return{ring:`approved`,heading:`Email verified`,status:`Finishing linking this device`,pending:!0,tone:`neutral`}}}function ft(e){let t=Ce(e);return t===null?null:v(`p`,{class:`seams-otp-description`,children:[`Demo email code: `,v(`code`,{children:t})]})}const M=`seams-auth-menu-title`,N=`seams-auth-menu-account-list`;function P(e,t=6){return e.padEnd(t,` `).slice(0,t).split(``)}const pt=new Set(Ae);function F(e){let t=``;for(let n of e.toUpperCase()){let e=n===`O`?`0`:n===`I`||n===`L`?`1`:n;pt.has(e)&&(t+=e)}return t}const mt=/[\s\-\u2010-\u2015\u2212]/;function ht(e){let t=new Set;for(let n of e.toUpperCase())mt.test(n)||F(n)||t.add(n);return Array.from(t).slice(0,3)}function gt(e,t,n){let r=t&&t.start===t.end?t.start:null,i=t===null?null:Math.min(t.start,31),a=[];for(let o=0;o<32;o+=4){let s=o+4,c=[];for(let i=o;i<s;i+=1){let a=e[i]??``,o=[`seams-otp-slot`];a&&o.push(`is-filled`),i===r&&o.push(`is-caret`),r===32&&i===31&&o.push(`is-caret-after`),t&&i>=t.start&&i<t.end&&o.push(`is-selected`),n&&i>=n.start&&i<n.end&&o.push(`is-new`),c.push(v(`span`,{class:o.join(` `),"data-recovery-slot":i,children:a},i))}let l=[`seams-recovery-code-group`];i!==null&&i>=o&&i<s&&l.push(`is-active`),e.length>=s&&l.push(`is-complete`),a.push(v(`div`,{class:l.join(` `),children:c},o))}return a}function _t(e,t,n,r){let i=null;for(let r of e.querySelectorAll(`[data-recovery-slot]`)){let e=Number(r.dataset.recoverySlot),a=r.getBoundingClientRect(),o=t<a.left?a.left-t:Math.max(0,t-a.right),s=n<a.top?a.top-n:Math.max(0,n-a.bottom),c=o*o+s*s;(i===null||c<i.distance)&&(i={index:e,distance:c,after:t>a.left+a.width/2})}return i===null?null:Math.min(i.after?i.index+1:i.index,r)}function I(e){return v(g,{children:v(`span`,{class:`seams-otp-slot ${e.trim()?`is-filled`:``}`,children:e})})}function vt(e){let t=e.kind===`recovery`?`:${e.stage}`:``;return`${e.kind}:${e.mode}:${e.status.kind}${t}`}function yt(e){return e.status.kind===`busy`?e.status.headline:e.status.kind===`recoverable`?e.status.message:e.stage===`passkey_ready`?`Recovery code accepted.`:e.stage===`sign_in_ready`?`Wallet recovered. Unlock it to continue.`:``}function bt(e){return e.kind===`recovery`?e.stage===`choose_method`?`Back to recovery code`:`Back to unlock wallet`:`Back`}function L(e){return e.kind===`recovery`&&e.stage===`finalizing`}function xt(e){return e===`register`?{prompt:`Already have a wallet?`,action:`Unlock wallet`,nextMode:`login`}:{prompt:`Don't have a wallet?`,action:`Create a wallet`,nextMode:`register`}}function St(e){return e===`register`?`Create a wallet`:`Unlock wallet`}function Ct(e){return e===`register`?`Create wallet with passkey`:`Unlock with passkey`}function wt(e){return e.kind===`google_otp_login`||e.kind===`google_registration`?e.error||null:e.kind===`passkey`&&e.status.kind===`recoverable`&&e.status.reason===`error`?e.status.message:null}function R(e){return S(e.accountOptions,e.selectedAccount).selectedAccount}function Tt(e){return e.walletId}function z(e){return e.authMethod===`email_otp`?e.emailAddress:null}function Et(e){if(!e)return`Saved wallets`;let t=z(e);return t?`Saved wallets. Selected wallet ID ${e.walletId}, email ${t}`:`Saved wallets. Selected ${e.walletId}`}function Dt(e){let t=e.filter(e=>e.authMethod===`passkey`),n=e.filter(e=>e.authMethod===`email_otp`);return[{authMethod:`passkey`,label:`Passkey`,accounts:t},{authMethod:`email_otp`,label:`Email OTP`,accounts:n}].filter(e=>e.accounts.length>0)}var Ot=class extends _{constructor(...e){super(...e),this.state={accountMenu:`closed`,recoverySelection:null,recoveryRejection:null},this.recoveryDrawnCode=``,this.recoveryArrival=null,this.recoveryArrivalTimer=null,this.recoveryRejectionTimer=null,this.accountMenuExitTimer=null,this.accountMenuChoice=null,this.previouslyFocusedElement=null,this.shouldFocusInitialControl=!0,this.contentResizeObserver=null,this.contentHeightFrame=null,this.previousLinkDeviceStateKind=null,this.previousRecoveryStage=null,this.lastMethod=`passkey`,this.queueContentHeightSync=()=>{this.contentHeightFrame!==null&&cancelAnimationFrame(this.contentHeightFrame),this.contentHeightFrame=requestAnimationFrame(this.syncContentHeight)},this.syncContentHeight=()=>{this.contentHeightFrame=null;let e=this.props.element.querySelector(`.seams-content-switcher`),t=this.props.element.querySelector(`.seams-content-sizer`);!e||!t||this.props.styles.setDynamicDeclarations(this.props.element.id+`-height`,`#`+this.props.element.id+` .seams-content-switcher`,{height:t.scrollHeight+`px`})},this.onKeydown=e=>{if(e.key===`Escape`){if(e.preventDefault(),this.viewModel&&L(this.viewModel))return;if(this.accountMenuOpen){this.closeAccountMenu();return}this.emitIntent({kind:`close`,reason:`escape`});return}if(e.key!==`Tab`)return;let t=this.focusableElements();if(t.length===0)return;let n=document.activeElement,r=t.indexOf(n instanceof HTMLElement?n:t[0]);e.shiftKey&&r<=0?(e.preventDefault(),t[t.length-1]?.focus()):!e.shiftKey&&r===t.length-1&&(e.preventDefault(),t[0]?.focus())},this.onBackClick=()=>{this.emitIntent({kind:`back`})},this.onKeyDown=e=>{if(e.key!==`Escape`||e.defaultPrevented)return;let t=this.viewModel;!t||t.kind!==`recovery`&&!T(t.status)||(e.preventDefault(),e.stopPropagation(),!L(t)&&this.emitIntent({kind:`back`}))},this.onIntentSwitchClick=()=>{let e=this.viewModel;e&&this.emitIntent({kind:`mode_selected`,mode:xt(e.mode).nextMode})},this.onRegistrationReroll=()=>{this.emitIntent({kind:`registration_reroll`})},this.onPasskeyNameInput=e=>{e.currentTarget instanceof HTMLInputElement&&this.emitIntent({kind:`passkey_name_changed`,passkeyName:e.currentTarget.value})},this.onLoginAccountSelect=e=>{let t=e.currentTarget;if(!(t instanceof HTMLButtonElement))return;let n=t.dataset.walletId,r=t.dataset.authMethod,i=this.viewModel;if(!n||i.kind!==`passkey`||i.mode!==`login`)return;let a=i.accountOptions.find(e=>e.walletId===n&&e.authMethod===r),o=R(i);if(!a||!o||this.accountMenuChoice)return;let s=Qe(t);if(!s)return;let c={chosen:a,previous:o};this.accountMenuChoice=c,this.emitIntent({kind:`login_account_selected`,walletId:a.walletId,authMethod:a.authMethod}),s.then(()=>{this.accountMenuChoice===c&&this.closeAccountMenu()})},this.onAccountMenuToggle=()=>{this.accountMenuOpen?this.closeAccountMenu():this.openAccountMenu()},this.onDocumentPointerDown=e=>{!this.accountMenuOpen||!(e.target instanceof Node)||this.props.element.querySelector(`.seams-account-menu`)?.contains(e.target)||this.closeAccountMenu()},this.onPrimaryClick=()=>{let e=this.viewModel;if(!e||!D(e)||e.kind===`link_device`)return;if(e.kind===`google_otp_login`){this.emitIntent({kind:`google_otp_submit`});return}if(e.kind===`google_registration`){this.emitIntent({kind:`google_registration_complete`});return}let t=e.mode===`register`?{kind:`submit`,mode:`register`,passkeyName:e.passkeyName}:{kind:`submit`,mode:`login`};this.lastMethod=`passkey`,this.emitIntent(t)},this.onGoogleOtpCodeInput=e=>{e.currentTarget instanceof HTMLInputElement&&this.emitIntent({kind:`google_otp_code_changed`,code:e.currentTarget.value})},this.onGoogleOtpKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this.emitIntent({kind:`google_otp_submit`}))},this.onGoogleOtpResend=()=>{this.emitIntent({kind:`google_otp_resend`})},this.onGoogleRegistrationReroll=()=>{this.emitIntent({kind:`google_registration_reroll`})},this.onGoogleClick=()=>{this.lastMethod=`google`,this.emitIntent({kind:`external_auth`,provider:`google`})},this.onNoticeRetry=()=>{this.lastMethod===`google`&&O(this.viewModel)?this.onGoogleClick():this.onPrimaryClick()},this.onLinkDeviceOpen=()=>{this.emitIntent({kind:`link_device_open`})},this.onRecoveryOpen=()=>{this.emitIntent({kind:`recovery_open`})},this.onRecoveryCodeInput=e=>{if(!(e.currentTarget instanceof HTMLInputElement)||this.viewModel.kind!==`recovery`)return;let t=e.currentTarget,n=t.value,r=ht(n);r.length>0&&this.showRecoveryRejection(r);let i=F(n.slice(0,t.selectionStart??n.length)).length,a=F(n).slice(0,32);t.value!==a&&(t.value=a,t.setSelectionRange(Math.min(i,a.length),Math.min(i,a.length))),this.syncRecoverySelection(t),this.emitIntent({kind:`recovery_code_changed`,recoveryCode:a})},this.onRecoverySelectionMove=e=>{e.currentTarget instanceof HTMLInputElement&&this.syncRecoverySelection(e.currentTarget)},this.onRecoveryCodeClick=e=>{let t=e.currentTarget;if(t instanceof HTMLInputElement){if(t.selectionStart===t.selectionEnd){let n=_t(this.props.element,e.clientX,e.clientY,t.value.length);n!==null&&t.setSelectionRange(n,n)}this.syncRecoverySelection(t)}},this.clearRecoveryRejection=()=>{this.recoveryRejectionTimer=null,this.setState({recoveryRejection:null})},this.endRecoveryArrival=()=>{this.recoveryArrivalTimer=null,this.recoveryArrival=null},this.onRecoveryCodeBlur=()=>{this.setState({recoverySelection:null})},this.onRecoverySubmit=e=>{e.preventDefault(),this.emitIntent({kind:`recovery_code_submit`})},this.onRecoveryPasskeySelected=()=>{this.emitIntent({kind:`recovery_passkey_selected`})},this.onRecoveryGoogleSelected=()=>{this.emitIntent({kind:`recovery_google_selected`})},this.onRecoveryGoogleOtpCodeInput=e=>{e.currentTarget instanceof HTMLInputElement&&this.emitIntent({kind:`recovery_google_otp_code_changed`,code:e.currentTarget.value})},this.onRecoveryGoogleOtpKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this.emitIntent({kind:`recovery_google_otp_submit`}))},this.onRecoveryGoogleOtpSubmit=()=>{this.emitIntent({kind:`recovery_google_otp_submit`})},this.onRecoveryCreatePasskey=()=>{this.emitIntent({kind:`recovery_create_passkey`})},this.onRecoverySignIn=()=>{this.emitIntent({kind:`recovery_sign_in`})},this.onLinkDeviceCreatePasskey=()=>{this.emitIntent({kind:`link_device_create_passkey`})},this.onLinkDeviceFactorChange=e=>{if(!(e.currentTarget instanceof HTMLInputElement))return;let t=e.currentTarget.value===`email_otp`?{kind:`email_otp`}:{kind:`passkey_prf`};this.emitIntent({kind:`link_device_factor_selected`,targetFactor:t})},this.onLinkDeviceTargetEmailInput=e=>{e.currentTarget instanceof HTMLInputElement&&this.emitIntent({kind:`link_device_target_email_changed`,emailAddress:e.currentTarget.value})},this.onLinkDeviceStart=()=>{this.emitIntent({kind:`link_device_start`})},this.onLinkDeviceEmailOtpCodeInput=e=>{e.currentTarget instanceof HTMLInputElement&&this.emitIntent({kind:`link_device_email_otp_code_changed`,code:e.currentTarget.value})},this.onLinkDeviceEmailOtpKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this.emitIntent({kind:`link_device_email_otp_submit`}))},this.onLinkDeviceEmailOtpResend=()=>{this.emitIntent({kind:`link_device_email_otp_resend`})},this.onLinkDeviceEmailOtpSubmit=()=>{this.emitIntent({kind:`link_device_email_otp_submit`})}}get viewModel(){return this.props.viewModel}get accountMenuOpen(){return this.state.accountMenu===`open`}openAccountMenu(){this.endAccountMenuExit(),this.setState({accountMenu:`open`})}closeAccountMenu(){this.accountMenuOpen&&(this.setState({accountMenu:`closing`}),this.accountMenuExitTimer=setTimeout(()=>{this.endAccountMenuExit(),this.setState({accountMenu:`closed`})},160))}endAccountMenuExit(){this.accountMenuExitTimer!==null&&clearTimeout(this.accountMenuExitTimer),this.accountMenuExitTimer=null,this.accountMenuChoice=null}componentDidMount(){let e=document.activeElement;e instanceof HTMLElement&&!this.props.element.contains(e)&&(this.previouslyFocusedElement=e),document.addEventListener(`pointerdown`,this.onDocumentPointerDown),document.addEventListener(`keydown`,this.onKeyDown,!0),this.afterRender()}componentDidUpdate(e){this.afterRender(e.viewModel)}componentWillUnmount(){this.contentResizeObserver?.disconnect(),this.contentResizeObserver=null,this.contentHeightFrame!==null&&cancelAnimationFrame(this.contentHeightFrame),this.contentHeightFrame=null,this.endAccountMenuExit(),this.recoveryArrivalTimer!==null&&clearTimeout(this.recoveryArrivalTimer),this.recoveryRejectionTimer!==null&&clearTimeout(this.recoveryRejectionTimer),window.removeEventListener(`resize`,this.queueContentHeightSync),document.removeEventListener(`pointerdown`,this.onDocumentPointerDown),document.removeEventListener(`keydown`,this.onKeyDown,!0),this.props.styles.deleteDynamicRule(this.props.element.id+`-height`),this.restoreFocus()}afterRender(e){this.shouldFocusInitialControl&&this.focusInitialControl(),this.focusRecoveryControl(e),this.focusLinkDevicePasskeyAction(),this.observeContentSize(),this.queueContentHeightSync()}focusRecoveryControl(e){let t=this.viewModel;if(e?.kind===`recovery`&&t.kind!==`recovery`){this.previousRecoveryStage=null,this.props.element.querySelector(`[data-recovery-action]`)?.focus();return}if(t.kind!==`recovery`)return;let n=this.previousRecoveryStage!==t.stage;if(this.previousRecoveryStage=t.stage,t.stage===`enter_code`){let t=this.props.element.querySelector(`[aria-invalid="true"]`);if(t){t.focus();return}(e?.kind!==`recovery`||e.stage!==`enter_code`)&&this.props.element.querySelector(`[data-recovery-code]`)?.focus();return}if(t.stage===`choose_method`){n&&this.props.element.querySelector(`[data-recovery-target]`)?.focus();return}let r=t.status.kind===`recoverable`&&e?.kind===`recovery`&&e.status.kind!==`recoverable`;(n||r)&&(t.stage===`passkey_ready`||t.stage===`finalizing`||t.stage===`sign_in_ready`)&&this.props.element.querySelector(`[data-auth-menu-primary]`)?.focus()}focusLinkDevicePasskeyAction(){let e=this.viewModel.kind===`link_device`?this.viewModel.linkDevice.kind:null,t=e===`passkey_required`&&this.previousLinkDeviceStateKind!==e;this.previousLinkDeviceStateKind=e,t&&this.props.element.querySelector(`[data-link-device-passkey-action]`)?.focus()}observeContentSize(){if(this.contentResizeObserver)return;let e=this.props.element.querySelector(`.seams-content-sizer`);e&&(this.contentResizeObserver=new ResizeObserver(this.queueContentHeightSync),this.contentResizeObserver.observe(e),window.addEventListener(`resize`,this.queueContentHeightSync))}focusInitialControl(){if(!this.props.element.isConnected||!this.shouldFocusInitialControl)return;this.shouldFocusInitialControl=!1;let e=document.activeElement;e instanceof HTMLElement&&this.props.element.contains(e)||this.props.element.querySelector(`[data-auth-menu-input], [data-auth-menu-primary]`)?.focus()}restoreFocus(){let e=this.previouslyFocusedElement;this.previouslyFocusedElement=null,e?.isConnected&&e.focus()}focusableElements(){return Array.from(this.props.element.querySelectorAll(`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])`))}showRecoveryRejection(e){let t=this.state.recoveryRejection?.parity===0?1:0;this.setState({recoveryRejection:{characters:e,parity:t}}),this.recoveryRejectionTimer!==null&&clearTimeout(this.recoveryRejectionTimer),this.recoveryRejectionTimer=setTimeout(this.clearRecoveryRejection,2e3)}recoveryCodeArrival(e){let t=this.recoveryDrawnCode;if(e===t)return this.recoveryArrival;this.recoveryDrawnCode=e;let n=0;for(;n<t.length&&t[n]===e[n];)n+=1;let r=n+e.length-t.length;return this.recoveryArrival=e.length>t.length?{start:n,end:r}:null,this.recoveryArrivalTimer!==null&&clearTimeout(this.recoveryArrivalTimer),this.recoveryArrivalTimer=setTimeout(this.endRecoveryArrival,600),this.recoveryArrival}syncRecoverySelection(e){let t=e.value.length,n=Math.min(e.selectionStart??t,t),r=Math.min(Math.max(e.selectionEnd??n,n),t),i=this.state.recoverySelection;i?.start===n&&i.end===r||this.setState({recoverySelection:{start:n,end:r}})}emitIntent(e){this.props.onIntent(e)}render(){let e=this.viewModel;if(!e)return v(g,{});let t=T(e.status),n=e.kind===`link_device`,r=e.kind===`google_otp_login`,i=e.kind===`google_registration`,a=e.kind===`recovery`;return v(g,{children:v(`div`,{class:`seams-signup-menu-root auth-menu-root`,"data-mode":e.mode,"data-waiting":t?`true`:`false`,"data-scan-device":n?`true`:`false`,"data-otp-prompt":r?`true`:`false`,"data-registration-prompt":i?`true`:`false`,"data-recovery":a?`true`:`false`,"aria-labelledby":M,"aria-busy":t?`true`:`false`,tabIndex:-1,onKeyDown:this.onKeydown,children:[v(`div`,{class:`seams-menu-origin`,children:[v(Me,{}),` `,v(`span`,{children:e.hostname})]}),v(`div`,{class:`seams-content-switcher`,children:[v(`button`,{class:`seams-back-button ${t||n||r||i||a?`is-visible`:``}`,type:`button`,"aria-label":bt(e),"data-auth-menu-close":!0,disabled:L(e),onClick:this.onBackClick,children:et()}),a?v(`div`,{class:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:yt(e)}):null,v(`div`,{class:`seams-content-area`,children:v(`div`,{class:`seams-content-sizer`,children:t?this.renderWaiting(e):v(g,{children:v(`div`,{class:`seams-signin-menu`,children:v(g,{children:this.renderActiveView(e)},vt(e))})})})})]}),v(lt,{notice:wt(e),onRetry:this.onNoticeRetry})]})})}renderActiveView(e){return e.kind===`recovery`?this.renderRecovery(e):e.kind===`link_device`?this.renderLinkDevice(e):e.kind===`google_otp_login`?this.renderGoogleOtp(e):e.kind===`google_registration`?this.renderGoogleRegistration(e):v(g,{children:[this.renderMenuHeader(e),` `,this.renderPasskeyInput(e),this.renderAuthMethods(e),` `,this.renderOtherOptions(),this.renderIntentSwitch(e)]})}renderMenuHeader(e){let t=St(e.mode);return v(`div`,{class:`seams-menu-header`,children:[t===e.heading?null:v(`div`,{class:`seams-menu-eyebrow`,children:t}),v(`div`,{class:`seams-title`,id:M,children:e.heading}),e.subtitle?v(`div`,{class:`seams-subhead`,children:e.subtitle}):null]})}renderHeader(e){return v(g,{children:v(`div`,{class:`seams-header`,children:v(`div`,{children:[v(`div`,{class:`seams-title`,id:M,children:e.heading}),v(`div`,{class:`seams-subhead`,children:e.subtitle})]})})})}renderPasskeyInput(e){if(e.mode===`login`){let t=R(e);if(!t)return v(g,{});let n=Dt(e.accountOptions),r=this.state.accountMenu,i=this.accountMenuChoice,a=i?.previous??t;return v(g,{children:v(`div`,{class:`seams-passkey-row`,children:v(`div`,{class:`seams-input-pill`,children:[v(`div`,{class:`seams-input-wrap`,children:v(`div`,{class:`seams-account-menu-account seams-selected-account`,"aria-hidden":`true`,children:[v(`span`,{class:`seams-account-menu-account-primary`,children:Tt(t)}),z(t)?v(g,{children:v(`span`,{class:`seams-account-menu-account-secondary`,children:z(t)})}):null]})}),v(`div`,{class:`seams-account-menu ${r===`closed`?``:`is-open`}`,children:[v(`button`,{class:`seams-account-menu-trigger`,type:`button`,"data-auth-menu-input":!0,"aria-label":Et(t),"aria-haspopup":`listbox`,"aria-expanded":this.accountMenuOpen?`true`:`false`,"aria-controls":N,onClick:this.onAccountMenuToggle,children:$e()}),r===`closed`?null:v(g,{children:v(`div`,{id:N,class:`seams-account-menu-popover ${r===`closing`?`is-closing`:``}`,role:`listbox`,children:n.map(e=>{let t=`${N}-${e.authMethod}`;return v(g,{children:v(`div`,{class:`seams-account-menu-group`,role:`group`,"aria-labelledby":t,children:[v(`div`,{id:t,class:`seams-account-menu-group-label`,children:e.label}),e.accounts.map(e=>{let t=e.walletId===a.walletId&&e.authMethod===a.authMethod,n=!t&&e.walletId===i?.chosen.walletId&&e.authMethod===i.chosen.authMethod,r=z(e);return v(g,{children:v(`button`,{class:`seams-account-menu-option ${t?`is-selected`:``} ${n?`is-chosen`:``}`,type:`button`,role:`option`,"aria-selected":t?`true`:`false`,title:r?`${e.walletId} ${r}`:e.walletId,"data-wallet-id":e.walletId,"data-auth-method":e.authMethod,onClick:this.onLoginAccountSelect,children:[v(`span`,{class:`seams-account-menu-check`,"aria-hidden":`true`}),v(`span`,{class:`seams-account-menu-account`,children:[v(`span`,{class:`seams-account-menu-account-primary`,children:e.walletId}),r?v(g,{children:v(`span`,{class:`seams-account-menu-account-secondary`,children:r})}):null]})]})})})]})})})})})]})]})})})}return e.showRegistrationInput?v(g,{children:v(`div`,{class:`seams-passkey-row`,children:v(`div`,{class:`seams-input-pill`,children:[v(`div`,{class:`seams-input-wrap`,children:v(`input`,{id:`seams-auth-menu-passkey-name`,class:`seams-input`,"data-auth-menu-input":!0,type:`text`,autocomplete:`nickname`,placeholder:e.passkeyNameLabel,value:e.passkeyName,readonly:e.passkeyNameReadOnly,disabled:T(e.status),onInput:this.onPasskeyNameInput})}),e.passkeyNameReadOnly?v(g,{children:v(`button`,{class:`seams-input-action-trigger auth-menu-registration-reroll`,type:`button`,title:`Generate another name`,"aria-label":`Generate another name`,onClick:this.onRegistrationReroll,disabled:!Xe(e),children:at()})}):null]})})}):v(g,{})}renderAuthMethods(e){let t=e.enabledExternalProviders?.includes(`google`)??!1;return v(g,{children:v(`div`,{class:`seams-auth-methods`,children:[v(`button`,{class:`seams-auth-method-btn seams-auth-method-btn-primary`,type:`button`,"data-auth-menu-primary":!0,disabled:!D(e),onClick:this.onPrimaryClick,children:[A(),v(`span`,{children:Ct(e.mode)})]}),t?v(`button`,{class:`seams-auth-method-btn`,type:`button`,"data-auth-menu-provider":`google`,disabled:!O(e),onClick:this.onGoogleClick,children:[j(),v(`span`,{children:`Continue with Google`})]}):null]})})}renderOtherOptions(){return v(g,{children:[v(`div`,{class:`seams-menu-options-label`,children:`Other options`}),v(`div`,{class:`seams-menu-options`,children:[v(`button`,{class:`seams-menu-option`,type:`button`,onClick:this.onLinkDeviceOpen,children:[v(`span`,{class:`seams-menu-option-icon`,children:tt()}),v(`span`,{class:`seams-menu-option-text`,children:[`Link this device `,v(`small`,{children:`Scan a code with your other device`})]}),ot()]}),v(`button`,{class:`seams-menu-option`,type:`button`,"data-recovery-action":!0,onClick:this.onRecoveryOpen,children:[v(`span`,{class:`seams-menu-option-icon`,children:nt()}),v(`span`,{class:`seams-menu-option-text`,children:[`Recover wallet `,v(`small`,{children:`Use your recovery code`})]}),ot()]})]})]})}renderRecovery(e){if(e.stage===`enter_code`){let t=F(e.recoveryCode).slice(0,32),n=this.recoveryCodeArrival(t),r=this.state.recoveryRejection,i=e.status.kind===`recoverable`?e.status.message:``,a=e.recoveryCodeError??i,o=a.length>0;return v(g,{children:[this.renderHeader(e),v(`p`,{id:`seams-recovery-code-feedback`,class:`seams-recovery-status ${o?`seams-recovery-error`:``}`,"aria-hidden":o?`false`:`true`,role:o?`alert`:`status`,children:a}),v(`form`,{class:`seams-recovery-form`,novalidate:!0,onSubmit:this.onRecoverySubmit,children:[v(`div`,{class:`seams-recovery-field`,children:[v(`div`,{class:`seams-recovery-field-header`,children:[v(`label`,{class:`seams-field-label`,for:`seams-recovery-code`,children:`Recovery code`}),v(`span`,{id:`seams-recovery-code-count`,class:`seams-recovery-code-count`,children:[t.length,`/`,32]})]}),v(`div`,{class:`seams-otp-code-field seams-recovery-code-field ${r?`is-rejecting-${r.parity}`:``}`,children:[v(`input`,{id:`seams-recovery-code`,class:`seams-otp-input`,"data-recovery-code":!0,name:`recoveryCode`,type:`text`,inputmode:`text`,autocomplete:`off`,autocapitalize:`characters`,autocorrect:`off`,spellcheck:!1,"aria-invalid":e.recoveryCodeError?`true`:`false`,"aria-describedby":e.recoveryCodeError?`seams-recovery-code-feedback seams-recovery-code-count seams-recovery-code-hint`:`seams-recovery-code-count seams-recovery-code-hint`,value:t,onInput:this.onRecoveryCodeInput,onFocus:this.onRecoverySelectionMove,onKeyUp:this.onRecoverySelectionMove,onSelect:this.onRecoverySelectionMove,onClick:this.onRecoveryCodeClick,onBlur:this.onRecoveryCodeBlur}),v(`div`,{class:`seams-otp-slots seams-recovery-code-slots ${n&&n.end-n.start>1?`is-sweeping`:``}`,"aria-hidden":`true`,children:gt(t,this.state.recoverySelection,n)})]}),v(`p`,{id:`seams-recovery-code-hint`,class:`seams-recovery-code-hint ${r?`is-error`:``}`,"aria-live":`polite`,children:r?`Recovery codes don’t use ${r.characters.join(`, `)}.`:`You can paste the whole code.`})]}),v(`button`,{class:`seams-auth-method-btn seams-auth-method-btn-primary`,type:`submit`,"data-auth-menu-primary":!0,"data-recovery-continue":!0,children:`Continue`})]})]})}if(e.stage===`choose_method`||e.stage===`preparing`){let t=e.stage===`preparing`?e.target.kind:null,n=e.status.kind===`recoverable`?e.status.message:e.status.kind===`busy`?e.status.headline:``,r=e.enabledExternalProviders?.includes(`google`)??!1;return v(g,{children:[this.renderHeader(e),v(`p`,{class:`seams-recovery-status ${e.status.kind===`recoverable`?`seams-recovery-error`:``}`,"aria-hidden":`true`,children:n}),v(`div`,{class:`seams-auth-methods seams-recovery-methods`,children:[v(`button`,{class:`seams-auth-method-btn seams-auth-method-btn-primary`,type:`button`,"data-auth-menu-primary":!0,"data-recovery-target":`passkey`,disabled:t!==null,onClick:this.onRecoveryPasskeySelected,children:[t===`passkey`?v(`span`,{class:`seams-spinner`,"aria-hidden":`true`}):A(),v(`span`,{children:`Create a passkey`})]}),r?v(`button`,{class:`seams-auth-method-btn`,type:`button`,"data-recovery-target":`google_email_otp`,disabled:t!==null,onClick:this.onRecoveryGoogleSelected,children:[t===`google_email_otp`?v(`span`,{class:`seams-spinner`,"aria-hidden":`true`}):j(),v(`span`,{children:`Continue with Google`})]}):null]}),v(`p`,{class:`seams-recovery-method-note`,children:`This adds a new sign-in method to your wallet.`})]})}if(e.stage===`email_code_required`){let t=P(e.otpCode),n=/^\d{6}$/.test(e.otpCode)&&e.status.kind!==`busy`,r=e.delivery.status===`reused`?`Use the code already sent to ${e.emailHint}.`:`A 6-digit code was sent to ${e.emailHint}.`;return v(g,{children:[this.renderHeader(e),v(`div`,{class:`seams-otp-prompt`,"aria-live":`polite`,children:[v(`p`,{class:`seams-otp-description`,children:r}),ft(e.delivery),v(`label`,{class:`seams-field-label`,for:`seams-recovery-google-otp`,children:`Email code`}),v(`div`,{class:`seams-otp-code-field`,"data-disabled":e.status.kind===`busy`?`true`:`false`,children:[v(`input`,{class:`seams-otp-input`,id:`seams-recovery-google-otp`,"data-auth-menu-input":!0,"data-email-otp-challenge-id":e.challengeId,"data-email-otp-wallet-id":e.walletId,name:`recoveryEmailOtpCode`,type:`text`,inputmode:`numeric`,autocomplete:`one-time-code`,spellcheck:!1,pattern:`[0-9]*`,maxLength:6,"aria-invalid":e.status.kind===`recoverable`?`true`:`false`,"aria-describedby":e.status.kind===`recoverable`?`seams-recovery-google-otp-error`:``,value:e.otpCode,disabled:e.status.kind===`busy`,onInput:this.onRecoveryGoogleOtpCodeInput,onKeyDown:this.onRecoveryGoogleOtpKeydown}),v(`div`,{class:`seams-otp-slots`,"aria-hidden":`true`,children:t.map(I)})]}),e.status.kind===`recoverable`?v(g,{children:v(`p`,{id:`seams-recovery-google-otp-error`,class:`seams-recovery-status seams-recovery-error`,role:`alert`,children:e.status.message})}):null,v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,"data-auth-menu-primary":!0,disabled:!n,onClick:this.onRecoveryGoogleOtpSubmit,children:`Verify email code`})]})]})}let t=e.stage===`finalizing`&&e.status.kind===`recoverable`,n=e.stage===`sign_in_ready`,r=e.target.kind===`google_email_otp`,i=e.status.kind===`recoverable`?e.status.message:n?null:e.stage===`google_ready`?`Continue with Google, then verify the code sent to your email.`:r?`Finishing recovery with Google…`:`Create a new passkey to finish recovering this wallet.`,a=n?this.onRecoverySignIn:r?t?this.onRecoveryGoogleOtpSubmit:this.onGoogleClick:this.onRecoveryCreatePasskey;return v(g,{children:[this.renderHeader(e),v(`div`,{class:`seams-recovery-confirmation`,children:[i===null?null:v(g,{children:v(`p`,{class:`seams-recovery-status`,children:i})}),v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,"data-auth-menu-primary":!0,onClick:a,children:[r&&!t?j():null,n?r?`Unlock with Google`:`Unlock with new passkey`:t?`Retry finalization`:r?`Continue with Google`:`Create new passkey`]})]})]})}renderIntentSwitch(e){let t=xt(e.mode);return v(g,{children:v(`div`,{class:`seams-auth-intent-switch`,children:[v(`span`,{children:t.prompt}),v(`button`,{type:`button`,"data-auth-menu-mode":t.nextMode,onClick:this.onIntentSwitchClick,children:t.action})]})})}renderWaiting(e){let t=e.status;if(t.kind!==`busy`)return v(g,{});let n=t.headline;return v(g,{children:v(`div`,{class:`seams-waiting`,role:`status`,"aria-live":`polite`,children:[t.illustration===`passkey`?v(`span`,{class:`seams-passkey-prompt`,role:`img`,"aria-label":`Passkey authentication`,children:A()}):null,v(`div`,{class:`seams-waiting-message`,children:[v(`span`,{class:`seams-waiting-text`,children:n}),t.illustration===`passkey`?v(`span`,{class:`seams-passkey-instruction`,children:`Complete the prompt on your device.`}):null,e.showProgress&&t.detail&&t.detail!==n?v(g,{children:v(`span`,{class:`seams-waiting-sdk-events`,children:t.detail})}):null]}),t.illustration===`passkey`?null:v(`div`,{"aria-label":`Loading`,class:`seams-spinner`})]})})}renderLinkDevice(e){let t=e.linkDevice;if(t.kind===`select_factor`)return this.renderLinkDeviceFactorSelection(t);if(t.kind===`passkey_required`||t.kind===`creating_passkey`)return this.renderLinkDevicePasskeyConfirmation(t);if(t.kind===`email_otp_required`)return this.renderLinkDeviceEmailOtp(t);if(t.kind===`activating`)return this.renderLinkedDeviceActivation(t);if(t.kind===`expired`)return this.renderLinkDeviceFailurePanel({dismiss:`expired`,title:`Linking expired`,detail:t.message,action:`Try again`});if(t.kind===`cancelled`)return this.renderLinkDeviceFailurePanel({dismiss:`cancelled`,title:`Linking cancelled`,detail:t.message,action:`Return to unlock wallet`});if(t.kind===`error`||t.kind===`activation_error`)return this.renderLinkDeviceFailure(t);let n=t.kind===`ready`;return v(g,{children:v(`div`,{class:`seams-scan-device-content`,children:v(`div`,{class:`qr-code-container`,children:v(`div`,{class:`qr-body`,children:v(`div`,{class:`qr-code-section`,children:[v(`div`,{class:`qr-code-display`,children:n?v(g,{children:v(`img`,{src:t.qrCodeDataURL,alt:`QR code to link this device`,class:`qr-code-image`})}):v(g,{children:v(`div`,{class:`qr-code-placeholder`,children:v(`span`,{class:`seams-spinner`,"aria-hidden":`true`})})})}),v(`div`,{class:`qr-header`,children:v(`h2`,{class:`qr-title`,id:M,children:e.heading})}),v(`div`,{class:`qr-instruction`,children:n?e.subtitle:`Preparing a one-time code for your other device.`}),v(`div`,{class:`qr-status`,role:`status`,"aria-live":`polite`,children:[n?t.message:`Generating QR code`,v(`span`,{class:`animated-ellipsis`})]})]})})})})})}renderLinkDeviceFactorSelection(e){let t=e.targetFactor.kind===`email_otp`,n=e.targetFactor.kind===`email_otp`&&typeof e.targetEmail==`string`?e.targetEmail:``,r=!t||pe(n);return v(g,{children:v(`div`,{class:`seams-link-device-confirmation`,children:[v(`h2`,{class:`qr-title`,id:M,children:`Match your other device`}),v(`p`,{class:`seams-link-device-confirmation-copy`,children:`Choose the unlock method for Device 2. Email code sends a one-time code to the address you enter.`}),v(`fieldset`,{class:`seams-link-device-factor-options`,children:[v(`legend`,{class:`sr-only`,children:`Wallet unlock method`}),v(`label`,{children:[v(`span`,{class:`seams-auth-method-choice-icon`,children:A()}),v(`span`,{class:`seams-auth-method-choice-label`,children:`Passkey`}),v(`input`,{type:`radio`,name:`linked-device-factor`,value:`passkey_prf`,checked:e.targetFactor.kind===`passkey_prf`,onChange:this.onLinkDeviceFactorChange})]}),v(`label`,{children:[v(`span`,{class:`seams-auth-method-choice-icon`,children:rt()}),v(`span`,{class:`seams-auth-method-choice-label`,children:`Email code`}),v(`input`,{type:`radio`,name:`linked-device-factor`,value:`email_otp`,checked:e.targetFactor.kind===`email_otp`,onChange:this.onLinkDeviceFactorChange})]})]}),t?v(g,{children:v(`label`,{class:`seams-link-device-target-email`,children:[v(`span`,{class:`seams-field-label`,children:`Email address`}),v(`input`,{type:`email`,name:`linked-device-target-email`,autocomplete:`email`,value:n,"aria-label":`Email address`,"aria-invalid":n.length>0&&!r?`true`:`false`,onInput:this.onLinkDeviceTargetEmailInput})]})}):null,e.error?v(g,{children:v(`p`,{class:`seams-link-device-inline-error`,role:`alert`,children:e.error})}):null,v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,"data-auth-menu-primary":!0,disabled:!r,onClick:this.onLinkDeviceStart,children:`Continue`})]})})}renderLinkDeviceEmailOtp(e){let t=e.state,n=dt(t),r=t.kind===`sending`||t.kind===`submitting`||t.kind===`resending`,i=e.otpCode.length===6&&(t.kind===`code_input`||t.kind===`incorrect`),a=t.kind!==`completed`&&t.kind!==`expired`&&t.kind!==`unavailable`,o=`maskedEmailHint`in t?t.maskedEmailHint:``,s=P(e.otpCode);return v(g,{children:v(`div`,{class:`seams-link-device-confirmation seams-link-device-email-otp`,"data-tone":n.tone,"data-otp-phase":t.kind,children:[ut(n.ring,rt()),v(`h2`,{class:`qr-title`,id:M,children:n.heading}),o?v(g,{children:v(`div`,{class:`seams-link-device-email-chip`,title:o,children:v(`span`,{children:o})})}):null,v(`p`,{class:`seams-link-device-email-status`,id:`seams-linked-device-otp-status`,role:`status`,"aria-live":`polite`,children:[n.status,n.pending?v(g,{children:v(`span`,{class:`animated-ellipsis`,"aria-hidden":`true`})}):null]}),a?v(g,{children:[v(`label`,{class:`sr-only`,for:`seams-linked-device-email-otp`,children:`Email code`}),v(`div`,{class:`seams-otp-code-field`,"data-disabled":r?`true`:`false`,children:[v(`input`,{class:`seams-otp-input`,id:`seams-linked-device-email-otp`,"data-auth-menu-input":!0,type:`text`,inputmode:`numeric`,autocomplete:`one-time-code`,pattern:`[0-9]*`,maxLength:6,"aria-label":`Email verification code`,"aria-describedby":`seams-linked-device-otp-status`,"aria-invalid":t.kind===`incorrect`?`true`:`false`,value:e.otpCode,disabled:r,onInput:this.onLinkDeviceEmailOtpCodeInput,onKeyDown:this.onLinkDeviceEmailOtpKeydown}),v(`div`,{class:`seams-otp-slots`,"aria-hidden":`true`,children:s.map(I)})]})]}):null,this.renderLinkDeviceEmailOtpActions(t,{busy:r,canSubmit:i})]})})}renderLinkDeviceEmailOtpActions(e,t){return e.kind===`completed`?null:e.kind===`unavailable`?v(g,{children:v(`button`,{class:`seams-link-device-btn`,type:`button`,"data-link-device-error-dismiss":!0,onClick:this.onBackClick,children:`Return to unlock wallet`})}):e.kind===`expired`?v(g,{children:v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,onClick:this.onLinkDeviceEmailOtpResend,children:`Send a new code`})}):v(g,{children:[v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,disabled:!t.canSubmit,onClick:this.onLinkDeviceEmailOtpSubmit,children:e.kind===`submitting`?`Verifying`:`Verify code`}),v(`button`,{class:`seams-otp-resend`,type:`button`,disabled:t.busy,onClick:this.onLinkDeviceEmailOtpResend,children:`Send another code`})]})}renderLinkDeviceFailure(e){let t=e.kind===`activation_error`;return this.renderLinkDeviceFailurePanel({dismiss:`error`,title:t?`Device linked`:`Couldn't link device`,detail:t?v(g,{children:[`Unable to open the wallet. Go back and try again. `,e.message]}):e.message,action:`Return to unlock wallet`})}renderLinkDeviceFailurePanel(e){return v(g,{children:v(`div`,{class:`seams-link-device-confirmation seams-link-device-failure`,children:[v(`div`,{class:`seams-link-device-failure-icon`,children:it()}),v(`h2`,{class:`qr-title`,id:M,children:e.title}),v(`p`,{class:`seams-link-device-failure-detail`,role:`alert`,children:e.detail}),v(`button`,{class:`seams-link-device-btn`,type:`button`,"data-auth-menu-primary":!0,[`data-link-device-${e.dismiss}-dismiss`]:!0,onClick:this.onBackClick,children:e.action})]})})}renderLinkedDeviceActivation(e){return v(g,{children:v(`div`,{class:`seams-link-device-confirmation`,children:[v(`span`,{class:`seams-spinner`,"aria-hidden":`true`}),v(`h2`,{class:`qr-title`,id:M,children:`Opening linked wallet`}),v(`p`,{class:`seams-link-device-confirmation-copy`,role:`status`,"aria-live":`polite`,children:e.message})]})})}renderLinkDevicePasskeyConfirmation(e){let t=e.kind===`creating_passkey`;return v(g,{children:v(`div`,{class:`seams-link-device-confirmation`,children:[ut(t?`waiting`:`approved`),v(`h2`,{class:`qr-title`,id:M,"aria-live":`polite`,children:e.message}),v(`button`,{class:`seams-link-device-btn seams-link-device-btn-primary`,type:`button`,"data-auth-menu-primary":!0,"data-link-device-passkey-action":!0,disabled:t,onClick:this.onLinkDeviceCreatePasskey,children:t?`Waiting for passkey`:`Create passkey`})]})})}renderGoogleOtp(e){let t=e.delivery.status===`reused`?`Use the code already sent to ${e.emailHint}.`:`A 6-digit code was sent to ${e.emailHint}.`,n=P(e.otpCode);return v(g,{children:v(`div`,{class:`seams-otp-prompt`,"aria-live":`polite`,children:[v(`div`,{class:`seams-otp-prompt-copy`,children:[v(`div`,{class:`seams-otp-title`,id:M,children:e.heading}),v(`p`,{class:`seams-otp-description`,children:t}),ft(e.delivery),v(`div`,{class:`seams-otp-account`,title:e.walletId,children:[v(`span`,{class:`seams-otp-account-label`,children:`Wallet`}),v(`span`,{class:`seams-otp-account-value`,children:e.walletId})]})]}),v(`label`,{class:`seams-field-label`,for:`seams-auth-menu-google-otp`,children:`Email code`}),v(`div`,{class:`seams-otp-code-field`,"data-disabled":e.submitBusy?`true`:`false`,children:[v(`input`,{class:`seams-otp-input`,id:`seams-auth-menu-google-otp`,"data-auth-menu-input":!0,"data-email-otp-challenge-id":e.challengeId,"data-email-otp-wallet-id":e.walletId,type:`text`,inputmode:`numeric`,autocomplete:`one-time-code`,pattern:`[0-9]*`,maxLength:6,value:e.otpCode,disabled:e.submitBusy,onInput:this.onGoogleOtpCodeInput,onKeyDown:this.onGoogleOtpKeydown}),v(`div`,{class:`seams-otp-slots`,"aria-hidden":`true`,children:n.map(I)})]}),v(`p`,{class:`seams-otp-helper`,children:e.prompt.helperText??``}),v(`button`,{class:`seams-auth-method-btn seams-auth-method-btn-primary`,type:`button`,"data-auth-menu-primary":!0,disabled:!D(e),onClick:this.onPrimaryClick,children:e.submitBusy?`Unlocking…`:e.ctaLabel}),v(`button`,{class:`seams-otp-resend auth-menu-google-resend`,type:`button`,disabled:e.resendBusy||e.submitBusy,onClick:this.onGoogleOtpResend,children:e.resendBusy?`Sending…`:`Resend Code`})]})})}renderGoogleRegistration(e){return v(g,{children:v(`div`,{class:`seams-otp-prompt`,"aria-live":`polite`,children:[v(`div`,{class:`seams-otp-prompt-copy`,children:[v(`div`,{class:`seams-otp-title`,id:M,children:e.heading}),v(`p`,{class:`seams-otp-description`,children:e.subtitle}),v(`div`,{class:`seams-otp-account`,title:e.walletId,children:[v(`span`,{class:`seams-otp-account-label`,children:`Wallet`}),v(`span`,{class:`seams-otp-account-value`,children:e.walletId})]}),v(`button`,{class:`seams-otp-reroll`,type:`button`,disabled:e.rerollBusy||e.submitBusy,onClick:this.onGoogleRegistrationReroll,children:e.rerollBusy?`Generating…`:`Generate another name`})]}),v(`button`,{class:`seams-auth-method-btn seams-auth-method-btn-primary`,type:`button`,"data-auth-menu-primary":!0,disabled:!D(e),onClick:this.onPrimaryClick,children:e.submitBusy?`Creating...`:e.ctaLabel})]})})}};const kt=new WeakMap;let At=0;function jt(e){let t=kt.get(e);return t||(t=Ie({doc:e,baseCss:``,dynamicStyleDataAttr:`data-seams-auth-menu-dynamic`,nonce:Fe}),kt.set(e,t)),t}var Mt=class{constructor(e){this.cancel=()=>{this.state.kind===`mounted`&&this.state.onIntent({kind:`close`,reason:`close_button`})};let t=e.parent.ownerDocument;this.styles=jt(t),this.element=t.createElement(`div`),this.element.className=`seams-wallet-ui seams-auth-menu-surface`,this.element.id=`seams-auth-menu-${++At}`,this.state={kind:`mounted`,onIntent:e.onIntent},this.element.addEventListener(`cancel`,this.cancel),e.parent.appendChild(this.element);try{this.update(e.viewModel)}catch(e){throw this.dispose(),e}}update(e){this.state.kind!==`disposed`&&(this.element.dataset.theme=e.appearance.theme.mode,this.styles.setDynamicRule(this.element.id+`-appearance`,Le(this.element.id,e.appearance)),h(v(Ot,{element:this.element,viewModel:e,onIntent:this.state.onIntent,styles:this.styles}),this.element))}dispose(){this.state.kind!==`disposed`&&(this.state={kind:`disposed`},this.element.removeEventListener(`cancel`,this.cancel),h(null,this.element),this.styles.deleteDynamicRule(this.element.id+`-appearance`),this.element.remove())}};function Nt(e){return new Mt(e)}const Pt=Symbol(`hostedPasskeyLoginPrepared`),Ft=Symbol(`hostedPasskeyAccountSyncPrepared`),B=300*1e3;function It(e){return{signingEngine:e.signingEngine,nearClient:e.nearClient,configs:e.configs,theme:e.theme,resumePendingAcknowledgementsV1:e.resumePendingAcknowledgementsV1}}const V=new WeakMap;function Lt(e){return e.signal}function H(e){if(Lt(e).aborted)throw Error(`Hosted auth-menu passkey preparation was cancelled`)}function Rt(e){if(Date.now()>=e.expiresAtMs)throw W(e),Error(`Hosted auth-menu passkey preparation expired`)}function zt(e){let t=V.get(e);if(!t)throw Error(`Hosted auth-menu passkey preparation is unknown`);if(t.lifecycle!==`ready`)throw Error(`Hosted auth-menu passkey preparation is no longer usable`);if(Date.now()>=e.expiresAtMs)throw W(e),Error(`Hosted auth-menu passkey preparation expired`);return H(e.cancellation),t}function Bt(e){return{id:String(e.credentialId||``).trim(),type:`public-key`,transports:Array.isArray(e.transports)?e.transports:[]}}function Vt(e){return{authMenuSessionId:e.authMenuSessionId,requestId:e.requestId}}async function Ht(e){H(e.cancellation);let t=we(e.walletId),n=await oe(String(t));if(n){H(e.cancellation);let r=Object.freeze({kind:`hosted_passkey_linked_authority_login_prepared_v1`,...Vt(e),walletId:t,selection:n,expiresAtMs:Date.now()+B,cancellation:e.cancellation,[Pt]:!0});return V.set(r,{context:e.context,loginOptions:{},syncOptions:{},lifecycle:`ready`,authority:null}),r}let r=await he({walletId:String(t),requestedCapabilityFamilies:{kind:`all_registered_mpc`}}),i=r.kind===`resolved`?r.subjectSet:await ae(String(t));if(!i)return await U({context:e.context,walletId:null,authMenuSessionId:e.authMenuSessionId,requestId:e.requestId,cancellation:e.cancellation});H(e.cancellation);let a=Object.freeze({kind:`hosted_passkey_owner_login_prepared_v1`,...Vt(e),walletId:t,subjectSet:i,expiresAtMs:Date.now()+B,cancellation:e.cancellation,[Pt]:!0});return V.set(a,{context:e.context,loginOptions:{},syncOptions:{},lifecycle:`ready`,authority:null}),a}async function U(e){H(e.cancellation);let t=await le(e.context,e.walletId);H(e.cancellation);let n=Object.freeze({kind:`hosted_passkey_account_sync_prepared_v1`,authMenuSessionId:e.authMenuSessionId,requestId:e.requestId,challenge:t,expiresAtMs:Date.now()+B,cancellation:e.cancellation,[Ft]:!0});return V.set(n,{context:e.context,loginOptions:{},syncOptions:{},lifecycle:`ready`,authority:null}),n}function Ut(e){let t=zt(e);t.lifecycle=`consuming`;let n={subjectId:e.challenge.walletId||`account-sync`,challengeB64u:e.challenge.syncOptions.challengeB64u,allowCredentials:e.challenge.syncOptions.credentialIds.map(e=>Bt({credentialId:e}))},r;try{r=t.context.signingEngine.getAuthenticationCredentialsSerialized({...n,includeSecondPrfOutput:!1})}catch(e){throw t.lifecycle=`cancelled`,e}return t.authority=r,r.then(()=>{t.lifecycle===`consuming`&&(t.lifecycle=`consumed`)},()=>{t.lifecycle===`consuming`&&(t.lifecycle=`cancelled`)}),r}function Wt(e){let t=V.get(e);if(!t)throw Error(`Hosted auth-menu passkey preparation is unknown`);if(t.lifecycle!==`consuming`&&t.lifecycle!==`consumed`||!t.authority)throw Error(`Hosted auth-menu passkey credential must be started by its CTA`);return t.lifecycle=`completing`,t}async function Gt(e){let t=zt(e);t.lifecycle=`completing`;let n=!1,r=e=>{e.phase===Oe.CANCELLED&&(n=!0)};try{let i=t.loginOptions.onEvent,a={...t.loginOptions,onEvent:e=>{r(e),i?.(e)}},o=e.kind===`hosted_passkey_linked_authority_login_prepared_v1`?await ee(t.context,String(e.walletId),a):await fe(t.context,e.subjectSet,a);return o.success?t.context.resumePendingAcknowledgementsV1():d(),{result:o,cancelledByUser:n}}finally{t.lifecycle=`finished`}}async function Kt(e){let t=Wt(e),n=t.authority;if(!n)throw Error(`Hosted auth-menu passkey credential is missing`);try{let r=await n;return Rt(e),H(e.cancellation),await re(t.context,e.challenge,r,t.syncOptions)}finally{t.lifecycle=`finished`}}function W(e){let t=V.get(e);!t||t.lifecycle===`finished`||t.lifecycle===`cancelled`||(t.lifecycle=`cancelled`)}const qt=`That recovery code can’t be used. Check the code and try again.`;function Jt(e){let t=e.replace(/[\s-]/g,``);if(!t)return`Enter a recovery code.`;if(t.length!==32)return`Enter all 32 characters of the recovery code.`;try{return ke(t),null}catch{return qt}}function G(e){if(e.kind===`hosted_passkey_registration_prepared_v1`){ye(e);return}W(e)}function K(){}function Yt(e){return e.target.kind===`passkey`}function Xt(e){return e.kind===`recovery`&&e.stage===`finalizing`&&(e.operation.kind===`hosted_recovery_credential_created`||e.operation.kind===`hosted_recovery_email_otp_verified`)}function Zt(e){return e.targetFactor.kind===`email_otp`?{targetFactor:e.targetFactor,targetEmail:u(e.targetEmail)}:{targetFactor:e.targetFactor}}const Qt={kind:`recoverable`,reason:`error`,message:`Google sign-in was cancelled.`};function q(e){let t=e.mode??e.request.initialMode,n=e.request.copy[t],r={kind:`passkey`,appearance:e.appearance,hostname:e.hostname,closeLabel:e.request.copy.common.closeLabel,heading:n.title,subtitle:n.subtitle,ctaLabel:n.passkeyCta,showProgress:e.request.showProgress,enabledExternalProviders:e.request.enabledExternalProviders,status:{kind:`idle`,interaction:`arming`}};return t===`register`?{...r,mode:t,showRegistrationInput:e.request.showRegistrationInput||e.request.registrationAccountInput===`sponsored_named_near_account`,passkeyNameReadOnly:e.request.registrationAccountInput===`implicit_wallet`,passkeyName:e.request.registrationAccountInput===`implicit_wallet`?String(Te()):``,passkeyNameLabel:e.request.copy.register.passkeyNameLabel}:{...r,mode:t,accountOptions:[],selectedAccount:null}}function $t(e){let t=q({...e,mode:`login`});if(t.kind!==`passkey`||t.mode!==`login`)throw Error(`login view model construction failed`);return t}async function en(e){let[t]=await Promise.allSettled([e,new Promise(e=>setTimeout(e,500))]);if(t.status===`rejected`)throw t.reason;return t.value}function tn(e){return e.trim()||`Wallet`}function nn(e){return`close_button`}function J(){try{let e=globalThis.crypto?.randomUUID?.();if(e)return`auth-menu-external-${e}`}catch{}return`auth-menu-external-${Date.now()}-${Math.random().toString(36).slice(2)}`}function rn(e){return{appearance:e.base.appearance,hostname:e.base.hostname,closeLabel:e.base.closeLabel,heading:e.flow.prompt.title,subtitle:e.flow.prompt.description,ctaLabel:e.flow.prompt.submitLabel,showProgress:e.base.showProgress,enabledExternalProviders:e.base.enabledExternalProviders,status:e.status}}function an(e){let t=`google-email-otp-login:${e.flow.walletId}:`;if(!e.flow.flowId.startsWith(t))throw Error(`Google Email OTP login flow identity is invalid`);return{...rn({base:e.base,flow:e.flow,status:e.status??{kind:`idle`,interaction:`actionable`}}),kind:`google_otp_login`,mode:`login`,emailHint:e.flow.emailHint,walletId:String(e.flow.walletId),challengeId:e.flow.flowId.slice(t.length),prompt:e.flow.prompt,delivery:e.flow.delivery,otpCode:e.otpCode??``,resendBusy:e.resendBusy??!1,submitBusy:e.submitBusy??!1,...e.error?{error:e.error}:{}}}function on(e){return{...rn({base:e.base,flow:e.flow,status:e.status??{kind:`idle`,interaction:`actionable`}}),kind:`google_registration`,mode:`register`,emailHint:e.flow.emailHint,walletId:String(e.flow.walletId),prompt:e.flow.prompt,rerollBusy:e.rerollBusy??!1,submitBusy:e.submitBusy??!1,...e.error?{error:e.error}:{}}}function Y(e){return e instanceof Error&&e.message.trim()?e.message.trim():String(e)}function sn(e){switch(e.kind){case`passkey`:return e.status.kind===`recoverable`?{mode:e.mode,message:e.status.detail??e.status.message}:null;case`google_otp_login`:case`google_registration`:return e.error?{mode:e.mode,message:e.error}:e.status.kind===`recoverable`?{mode:e.mode,message:e.status.message}:null;case`link_device`:return null;case`recovery`:return e.stage===`sign_in_ready`&&e.status.kind===`recoverable`?{mode:`login`,message:e.status.detail??e.status.message}:null;default:{let t=e;throw Error(`Unknown auth-menu view model: ${JSON.stringify(t)}`)}}}function cn(e){return{kind:`link_device`,appearance:e.appearance,hostname:e.hostname,closeLabel:e.closeLabel,heading:`Scan and link device`,subtitle:`Scan this code with your other device.`,ctaLabel:``,showProgress:e.showProgress,enabledExternalProviders:e.enabledExternalProviders,status:{kind:`idle`,interaction:`actionable`},mode:e.mode,linkDevice:{kind:`select_factor`,targetFactor:{kind:`passkey_prf`}}}}function X(e){let t={kind:`recovery`,mode:`login`,appearance:e.base.appearance,hostname:e.base.hostname,closeLabel:e.base.closeLabel,heading:`Recover wallet`,subtitle:e.stage===`sign_in_ready`?e.target.kind===`google_email_otp`?`Your Google account is ready to unlock your wallet.`:`Your wallet is ready. Unlock it with your passkey.`:e.stage===`choose_method`||e.stage===`preparing`?`Choose how you will sign in to this wallet from now on.`:`Enter a recovery code to recover your wallet.`,ctaLabel:e.stage===`passkey_ready`?`Create new passkey`:e.stage===`google_ready`?`Continue with Google`:e.stage===`email_code_required`?`Verify email code`:e.stage===`sign_in_ready`?e.target.kind===`google_email_otp`?`Unlock with Google`:`Unlock with new passkey`:e.stage===`preparing`||e.stage===`choose_method`?`Create a passkey`:`Continue`,showProgress:e.base.showProgress,enabledExternalProviders:e.base.enabledExternalProviders,recoveryCode:e.recoveryCode??``,recoveryCodeError:e.recoveryCodeError??null};switch(e.stage){case void 0:case`enter_code`:return{...t,stage:`enter_code`,status:e.status??{kind:`idle`,interaction:`actionable`}};case`choose_method`:return{...t,stage:`choose_method`,status:e.status??{kind:`idle`,interaction:`actionable`}};case`preparing`:return{...t,stage:e.stage,target:e.target,status:e.status};case`passkey_ready`:return{...t,target:e.target,walletId:e.walletId,stage:e.stage,status:e.status??{kind:`idle`,interaction:`actionable`}};case`google_ready`:return{...t,target:e.target,walletId:e.walletId,stage:e.stage,status:e.status??{kind:`idle`,interaction:`actionable`}};case`email_code_required`:return{...t,target:e.target,walletId:e.walletId,stage:e.stage,challengeId:e.challengeId,emailHint:e.emailHint,delivery:e.delivery,otpCode:e.otpCode??``,status:e.status??{kind:`idle`,interaction:`awaiting_input`}};case`finalizing`:return{...t,target:e.target,walletId:e.walletId,stage:e.stage,status:e.status};case`sign_in_ready`:return{...t,target:e.target,walletId:e.walletId,stage:e.stage,status:e.status??{kind:`idle`,interaction:`actionable`}}}}function Z(e){if(e.stage===`enter_code`||e.stage===`choose_method`||e.stage===`preparing`)throw Error(`recovery wallet id is unavailable before preparation`);return e.walletId}function Q(e){if(e.stage===`enter_code`||e.stage===`choose_method`)throw Error(`recovery target is unavailable before preparation`);return e.target}function $(e){return e.kind===`dismissed`?{kind:`idle`,interaction:`actionable`}:{kind:`recoverable`,reason:`error`,message:e.kind===`consumed`?`That recovery code has already been used. Use another code.`:qt}}function ln(){return{kind:`recoverable`,reason:`error`,message:`Recovery couldn’t be completed. Try again.`}}function un(e){return e.kind===`dismissed`?{kind:`idle`,interaction:`actionable`}:{kind:`recoverable`,reason:`error`,message:`A passkey couldn’t be created. Try again.`}}var dn=class{constructor(e){this.surface=null,this.outcomeResolver=null,this.outcomePromise=null,this.cleanedUp=!1,this.prepared=null,this.preparePasskey=null,this.registrationPreparation=null,this.preparationCancellation=null,this.googleCancellation=null,this.loginPreparation=null,this.loginAccountOptions=[],this.selectedLoginAccount=null,this.modeSelectionSource=`initial`,this.measurementReporter=null,this.preparationGeneration=0,this.googleGeneration=0,this.deviceLinkGeneration=0,this.linkedDeviceActivationInProgress=!1,this.targetPasskeyActivation=null,this.targetEmailOtpActivation=null,this.linkedDeviceEmailOtpSendStarted=!1,this.linkedDeviceTargetFactor={kind:`passkey_prf`},this.linkedDeviceTargetEmailAddress=``,this.preparationDeadlineTimer=null,this.preparationExpiryTimer=null,this.lastReportedError=null,this.recoveryGeneration=0,this.recoveryCancellation=null,this.recoveryLoginPrepared=null,this.recoveryReturnState=null,this.prepareSelectedLogin=e=>{if(!this.loginPreparation)throw Error(`Hosted login preparation is unavailable`);let t=S(this.loginAccountOptions,this.selectedLoginAccount);if(!C(t))throw Error(`Email OTP accounts require Google sign-in`);return this.loginPreparation(t.kind===`discoverable`?null:t.walletId,e)},this.postSurfaceMeasurement=e=>{this.sendToParent({type:`SURFACE_MEASUREMENT`,payload:e})},this.onIntent=e=>{switch(e.kind){case`mode_selected`:this.selectMode(e.mode);return;case`back`:this.back();return;case`link_device_open`:this.openLinkDevice();return;case`recovery_open`:this.openRecovery();return;case`recovery_code_changed`:this.changeRecoveryCode(e.recoveryCode);return;case`recovery_code_submit`:this.submitRecoveryCode();return;case`recovery_passkey_selected`:this.prepareRecovery(`passkey`);return;case`recovery_google_selected`:this.prepareRecovery(`google_email_otp`);return;case`recovery_google_otp_code_changed`:this.changeRecoveryGoogleOtpCode(e.code);return;case`recovery_google_otp_submit`:this.submitRecoveryGoogleOtp();return;case`recovery_create_passkey`:this.createRecoveryPasskey();return;case`recovery_sign_in`:this.signInRecoveredWallet();return;case`link_device_factor_selected`:this.selectLinkedDeviceTargetFactor(e.targetFactor);return;case`link_device_target_email_changed`:this.changeLinkedDeviceTargetEmailAddress(e.emailAddress);return;case`link_device_start`:this.startSelectedDeviceLinking();return;case`link_device_create_passkey`:this.createLinkedDevicePasskey();return;case`link_device_email_otp_code_changed`:this.changeLinkedDeviceEmailOtpCode(e.code);return;case`link_device_email_otp_resend`:this.resendLinkedDeviceEmailOtp();return;case`link_device_email_otp_submit`:this.submitLinkedDeviceEmailOtp();return;case`registration_reroll`:this.rerollRegistrationWallet();return;case`close`:this.cancel(nn(e));return;case`passkey_name_changed`:{let t=this.stateValue.kind===`preparing`||this.stateValue.kind===`ready`?this.stateValue.viewModel:null;t?.kind===`passkey`&&t.mode===`register`&&!t.passkeyNameReadOnly&&(this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...t,passkeyName:e.passkeyName,status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.startPasskeyPreparation());return}case`login_account_selected`:this.selectLoginAccount(e.walletId,e.authMethod);return;case`submit`:if(this.stateValue.kind===`preparing`&&this.stateValue.viewModel.status.kind===`recoverable`){this.retryPreparation();return}this.stateValue.kind===`ready`&&this.prepared===this.stateValue.prepared&&(e.mode===`register`&&this.stateValue.prepared.kind===`hosted_passkey_registration_prepared_v1`||e.mode===`login`&&(this.stateValue.prepared.kind===`hosted_passkey_owner_login_prepared_v1`||this.stateValue.prepared.kind===`hosted_passkey_linked_authority_login_prepared_v1`||this.stateValue.prepared.kind===`hosted_passkey_account_sync_prepared_v1`))&&this.performPreparedPasskey(this.stateValue.prepared);return;case`external_auth`:this.requestExternalAuth(e.provider);return;case`google_otp_code_changed`:this.updateGoogleOtpCode(e.code);return;case`google_otp_resend`:this.resendGoogleOtp();return;case`google_otp_submit`:this.submitGoogleOtp();return;case`google_registration_reroll`:this.rerollGoogleRegistration();return;case`google_registration_complete`:this.completeGoogleRegistration();return;case`retry`:this.retryPreparation();return;default:return fn(e)}},this.showRegistrationDelay=e=>{if(e.phase!==De.STEP_05_ED25519_SIGNER_PROVISION_DELAYED&&e.phase!==De.STEP_06_RELAY_BOOTSTRAP_DELAYED)return;let t=this.stateValue;if(t.kind!==`performing`)return;let n=t.viewModel;n.kind!==`passkey`||n.status.kind!==`busy`||(this.stateValue={...t,viewModel:{...n,status:{kind:`busy`,headline:e.message}}},this.updateElement())},this.identity={authMenuSessionId:e.request.authMenuSessionId,requestId:e.requestId},this.request=e.request,this.beginGoogleEmailOtp=e.beginGoogleEmailOtp,this.startDeviceLinking=e.startDeviceLinking,this.cancelDeviceLinking=e.cancelDeviceLinking,this.recoveryPort=e.recoveryPort,this.prepareRecoveredLogin=e.prepareRecoveredLogin,this.sendToParent=e.sendToParent,this.stateValue={kind:`preparing`,viewModel:q({request:e.request,appearance:e.appearance,hostname:tn(e.hostname)})}}get state(){return this.stateValue}setRegistrationPreparation(e){this.registrationPreparation=e,this.stateValue.kind!==`complete`&&this.currentViewModel().mode===`register`&&(this.preparePasskey=null,this.startPasskeyPreparation())}setPasskeyPreparation(e){this.preparePasskey=e,this.startPasskeyPreparation()}setLoginPreparation(e){let t=this.stateValue.kind===`complete`?null:this.currentViewModel();t?.kind===`passkey`&&t.mode===`login`&&(this.stateValue.kind===`preparing`||this.stateValue.kind===`ready`)&&this.invalidatePreparation(),this.loginPreparation=e.prepare,this.loginAccountOptions=e.accountOptions,this.selectedLoginAccount=e.selectedAccount,this.updateLoginSelectionViewModel(),(this.stateValue.kind===`preparing`||this.stateValue.kind===`ready`)&&this.currentViewModel().mode===`login`&&this.activateSelectedLoginMethod()}defaultToLoginForDetectedLocalWallet(){if(this.modeSelectionSource!==`initial`||this.stateValue.kind===`complete`)return;let e=this.currentViewModel();e.kind!==`passkey`||e.mode!==`register`||this.showPasskeyMode(`login`)}activateSelectedLoginMethod(){if(C(S(this.loginAccountOptions,this.selectedLoginAccount))){this.setPasskeyPreparation(this.prepareSelectedLogin);return}this.preparePasskey=null;let e=this.stateValue;e.kind!==`preparing`&&e.kind!==`ready`||e.viewModel.kind!==`passkey`||e.viewModel.mode!==`login`||(this.stateValue={kind:`preparing`,viewModel:{...e.viewModel,status:{kind:`idle`,interaction:`actionable`}}},this.updateElement())}updateLoginSelectionViewModel(){let e=this.stateValue;e.kind!==`preparing`&&e.kind!==`ready`||e.viewModel.kind!==`passkey`||e.viewModel.mode!==`login`||(this.stateValue={...e,viewModel:{...e.viewModel,accountOptions:this.loginAccountOptions,selectedAccount:this.selectedLoginAccount}})}mount(){if(this.surface||this.cleanedUp)throw Error(`Hosted auth-menu session is already mounted`);if(document.querySelectorAll(`.seams-auth-menu-surface`).length>0)throw Error(`A hosted auth-menu surface is already mounted`);let e=document.body||document.documentElement;if(!e)throw Error(`Wallet host document has no mount root`);this.surface=Nt({parent:e,viewModel:this.currentViewModel(),onIntent:this.onIntent}),this.measurementReporter=Pe({kind:`auth_menu_surface`,element:this.surface.element,requestId:this.identity.requestId,authMenuSessionId:this.identity.authMenuSessionId,postMeasurement:this.postSurfaceMeasurement})}waitForOutcome(){return this.stateValue.kind===`complete`?Promise.resolve(this.stateValue.outcome):(this.outcomePromise||=new Promise(e=>{this.outcomeResolver=e}),this.outcomePromise)}cancel(e){if(Xt(this.stateValue)){if(e===`close_button`)return;this.complete({kind:`cancelled`,authMenuSessionId:this.identity.authMenuSessionId,reason:e});return}this.stateValue.kind===`link_device`&&console.error(`[Device2Linking] auth menu cancelled`,{reason:e}),this.invalidatePreparation(),this.complete({kind:`cancelled`,authMenuSessionId:this.identity.authMenuSessionId,reason:e})}startPasskeyPreparation(){if(this.stateValue.kind===`complete`)return;let e=this.currentViewModel();if(e.kind!==`passkey`)return;let t=e.mode===`register`?this.registrationPreparation:null,n=e.mode===`login`?this.preparePasskey:null;if(!n&&!t)return;if(t&&e.mode===`register`&&e.showRegistrationInput&&e.passkeyName.trim().length===0){this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...e,status:{kind:`idle`,interaction:`awaiting_input`}}},this.updateElement();return}this.clearPreparationExpiryTimer();let r=++this.preparationGeneration,i=new AbortController;this.preparationCancellation=i;let a={kind:`abort_signal`,signal:i.signal};this.stateValue={kind:`preparing`,viewModel:{...e,status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.schedulePreparationDeadline(r,i),Promise.resolve().then(()=>t?t(this.registrationValue(),a,this.showRegistrationDelay):n(a)).then(t=>{if(r!==this.preparationGeneration||this.stateValue.kind===`complete`){G(t);return}this.clearPreparationDeadlineTimer(),this.prepared=t,this.stateValue={kind:`ready`,prepared:t,viewModel:{...e,status:{kind:`idle`,interaction:`actionable`}}},this.schedulePreparationExpiry(t),this.updateElement()},t=>{r!==this.preparationGeneration||this.stateValue.kind===`complete`||(this.clearPreparationDeadlineTimer(),this.stateValue={kind:`preparing`,viewModel:{...e,status:x(Y(t))}},this.updateElement())})}invalidatePreparation(){this.invalidateRecovery(),this.stateValue.kind===`link_device`&&(this.deviceLinkGeneration+=1,this.cancelDeviceLinking().catch(()=>{})),this.clearPreparationDeadlineTimer(),this.clearPreparationExpiryTimer(),this.preparationGeneration+=1,this.preparationCancellation?.abort(),this.preparationCancellation=null,this.googleGeneration+=1,this.googleCancellation?.abort(),this.googleCancellation=null;let e=this.prepared;this.prepared=null,e&&G(e),this.stateValue.kind===`performing`&&G(this.stateValue.prepared),(this.stateValue.kind===`google_login`||this.stateValue.kind===`google_registration`)&&this.stateValue.flow.cancel().catch(()=>{})}invalidateRecovery(){this.recoveryGeneration+=1,this.recoveryCancellation?.abort(),this.recoveryCancellation=null;let e=this.recoveryLoginPrepared;this.recoveryLoginPrepared=null,e&&G(e);let t=this.stateValue;t.kind!==`recovery`||!t.operation||Xt(t)||this.recoveryPort.cancel(t.operation).catch(()=>{})}registrationValue(){let e=this.stateValue;return(e.kind===`preparing`||e.kind===`ready`)&&e.viewModel.kind===`passkey`&&e.viewModel.mode===`register`?e.viewModel.passkeyName:``}clearPreparationExpiryTimer(){this.preparationExpiryTimer!==null&&(clearTimeout(this.preparationExpiryTimer),this.preparationExpiryTimer=null)}clearPreparationDeadlineTimer(){this.preparationDeadlineTimer!==null&&(clearTimeout(this.preparationDeadlineTimer),this.preparationDeadlineTimer=null)}schedulePreparationDeadline(e,t){this.clearPreparationDeadlineTimer(),this.preparationDeadlineTimer=setTimeout(this.expirePasskeyPreparation.bind(this,e,t),2e4)}expirePasskeyPreparation(e,t){let n=this.stateValue;e!==this.preparationGeneration||t!==this.preparationCancellation||n.kind!==`preparing`||n.viewModel.kind!==`passkey`||n.viewModel.status.kind!==`idle`||n.viewModel.status.interaction!==`arming`||(this.clearPreparationDeadlineTimer(),this.preparationGeneration+=1,this.preparationCancellation=null,t.abort(),this.stateValue={kind:`preparing`,viewModel:{...n.viewModel,status:x(`Passkey preparation timed out`)}},this.updateElement())}schedulePreparationExpiry(e){this.clearPreparationExpiryTimer();let t=Math.max(0,e.expiresAtMs-Date.now());this.preparationExpiryTimer=setTimeout(()=>{this.preparationExpiryTimer=null,!(this.stateValue.kind!==`ready`||this.stateValue.prepared!==e||this.prepared!==e||this.stateValue.viewModel.kind!==`passkey`)&&(G(e),this.prepared=null,this.stateValue={kind:`preparing`,viewModel:{...this.stateValue.viewModel,status:{kind:`recoverable`,reason:`expired`,message:`Passkey preparation expired. Retry to continue.`}}},this.updateElement())},t)}startGoogleFlow(e,t){this.invalidatePreparation();let n=++this.googleGeneration,r=new AbortController;this.googleCancellation=r;let i=this.currentViewModel();i.kind===`recovery`||i.kind===`link_device`||(this.stateValue={kind:`preparing`,viewModel:{...i,status:{kind:`busy`,headline:`Waiting for Google login…`,detail:`Starting Google sign-in`}}},this.updateElement(),this.beginGoogleEmailOtp({idToken:e,authTarget:t,signal:r.signal}).then(e=>{if(n!==this.googleGeneration||r.signal.aborted||this.stateValue.kind===`complete`){e.cancel().catch(()=>{});return}this.googleCancellation=null,e.mode===`login`?this.stateValue={kind:`google_login`,flow:e,viewModel:an({base:i,flow:e})}:this.stateValue={kind:`google_registration`,flow:e,viewModel:on({base:i,flow:e})},this.updateElement()},e=>{n!==this.googleGeneration||r.signal.aborted||this.stateValue.kind===`complete`||(this.googleCancellation=null,this.stateValue={kind:`preparing`,viewModel:{...i,status:x(Y(e))}},this.updateElement())}))}requestExternalAuth(e){if(this.stateValue.kind===`complete`)return null;if(this.stateValue.kind===`recovery`&&this.stateValue.stage===`google_ready`)return this.requestRecoveryGoogleVerification(e,this.stateValue);if(this.stateValue.kind===`recovery`&&this.stateValue.stage===`sign_in_ready`&&this.stateValue.viewModel.target.kind===`google_email_otp`)return this.requestRecoveredGoogleSignIn(e,this.stateValue);let t=this.currentViewModel();if(t.kind!==`passkey`||!this.request.enabledExternalProviders.includes(e)||this.stateValue.kind===`awaiting_external_auth`)return null;let n;if(t.mode===`register`)n={mode:`register`};else{let e=S(t.accountOptions,t.selectedAccount);if(!w(e))return null;n={mode:`login`,loginTarget:e.loginTarget}}this.invalidatePreparation();let i=r(J());if(!i)return null;let a={kind:`hosted_auth_menu_external_auth_request_v1`,authMenuSessionId:this.identity.authMenuSessionId,externalAuthRequestId:i,provider:e,mode:t.mode};return this.stateValue={kind:`awaiting_external_auth`,viewModel:{...t,status:{kind:`busy`,headline:`Waiting for Google login…`,detail:`Waiting for Google sign-in`}},request:a,authTarget:n},this.updateElement(),this.sendToParent({type:`AUTH_MENU_EXTERNAL_AUTH_REQUEST`,requestId:this.identity.requestId,payload:a}),a}acceptExternalAuthResolution(e){let t=this.stateValue;if(t.kind===`recovery`&&t.stage===`google_external_auth`){if(t.request.authMenuSessionId!==e.authMenuSessionId||t.request.externalAuthRequestId!==e.externalAuthRequestId||this.identity.requestId!==e.requestId)return!1;if(e.evidence.kind===`google_id_token`)return this.startRecoveryGoogleVerification(t,e.evidence.idToken),!0;let n=e.evidence.kind===`cancelled`?Qt:x(e.evidence.message);return this.stateValue={kind:`recovery`,stage:`google_ready`,operation:t.operation,returnState:t.returnState,viewModel:X({base:t.viewModel,walletId:Z(t.viewModel),stage:`google_ready`,target:t.operation.target,status:n})},this.updateElement(),!0}if(t.kind!==`awaiting_external_auth`||t.viewModel.kind!==`passkey`||t.request.authMenuSessionId!==e.authMenuSessionId||t.request.externalAuthRequestId!==e.externalAuthRequestId||this.identity.requestId!==e.requestId)return!1;switch(e.evidence.kind){case`google_id_token`:return this.startGoogleFlow(e.evidence.idToken,t.authTarget),!0;case`cancelled`:case`failed`:{let n=e.evidence.kind===`cancelled`?Qt:x(e.evidence.message);return this.stateValue={kind:`preparing`,viewModel:{...t.viewModel,status:n}},this.updateElement(),!0}default:return gn(e.evidence)}}requestRecoveryGoogleVerification(e,t){if(!this.request.enabledExternalProviders.includes(e))return null;let n=r(J());if(!n)return null;let i={kind:`hosted_auth_menu_external_auth_request_v1`,authMenuSessionId:this.identity.authMenuSessionId,externalAuthRequestId:n,provider:e,mode:`login`};return this.stateValue={kind:`recovery`,stage:`google_external_auth`,operation:t.operation,returnState:t.returnState,request:i,viewModel:X({base:t.viewModel,walletId:Z(t.viewModel),stage:`finalizing`,target:t.operation.target,status:{kind:`busy`,headline:`Waiting for Google login…`,detail:`Waiting for Google sign-in`}})},this.updateElement(),this.sendToParent({type:`AUTH_MENU_EXTERNAL_AUTH_REQUEST`,requestId:this.identity.requestId,payload:i}),i}requestRecoveredGoogleSignIn(e,t){if(!this.request.enabledExternalProviders.includes(e))return null;let n=r(J());if(!n)return null;let i={kind:`hosted_auth_menu_external_auth_request_v1`,authMenuSessionId:this.identity.authMenuSessionId,externalAuthRequestId:n,provider:e,mode:`login`};return this.stateValue={kind:`awaiting_external_auth`,request:i,authTarget:{mode:`login`,loginTarget:{kind:`wallet`,walletId:Z(t.viewModel)}},viewModel:{...$t({request:this.request,appearance:t.viewModel.appearance,hostname:t.viewModel.hostname}),status:{kind:`busy`,headline:`Waiting for Google login…`,detail:`Waiting for Google sign-in`}}},this.updateElement(),this.sendToParent({type:`AUTH_MENU_EXTERNAL_AUTH_REQUEST`,requestId:this.identity.requestId,payload:i}),i}cleanup(){this.cleanedUp||(this.cleanedUp=!0,this.invalidatePreparation(),this.measurementReporter?.disconnect(),this.measurementReporter=null,this.surface?.dispose(),this.surface=null)}currentViewModel(){switch(this.stateValue.kind){case`preparing`:case`awaiting_external_auth`:case`ready`:case`performing`:return this.stateValue.viewModel;case`google_login`:case`google_registration`:case`link_device`:case`recovery`:return this.stateValue.viewModel;case`complete`:throw Error(`Completed auth-menu session has no view model`)}}updateElement(){let e=this.currentViewModel();this.reportPresentedError(e),this.surface?.update(e)}reportPresentedError(e){let t=sn(e);if(!t){this.lastReportedError=null;return}let n=`${t.mode}:${t.message}`;if(n===this.lastReportedError)return;this.lastReportedError=n;let r=o({kind:`hosted_auth_menu_error_v1`,authMenuSessionId:this.identity.authMenuSessionId,mode:t.mode,message:t.message});if(!r)throw Error(`Unable to emit hosted auth-menu error event`);this.sendToParent({type:`AUTH_MENU_ERROR`,requestId:this.identity.requestId,payload:r})}selectMode(e){let t=this.stateValue;t.kind===`complete`||t.kind===`performing`||t.kind===`link_device`||(this.modeSelectionSource=`user`,this.currentViewModel().mode!==e&&this.showPasskeyMode(e))}showPasskeyMode(e){if(this.stateValue.kind===`complete`||this.stateValue.kind===`link_device`)return;let t=this.currentViewModel();this.invalidatePreparation();let n=q({request:{...this.request,initialMode:e},appearance:t.appearance,hostname:t.hostname,mode:e});this.stateValue={kind:`preparing`,viewModel:n.kind===`passkey`&&n.mode===`login`?{...n,accountOptions:this.loginAccountOptions,selectedAccount:this.selectedLoginAccount}:n},this.updateElement(),e===`login`?this.activateSelectedLoginMethod():(this.preparePasskey=null,this.startPasskeyPreparation())}back(){if(this.stateValue.kind===`recovery`){if(this.stateValue.stage===`finalizing`)return;if(this.stateValue.stage===`choose_method`){this.returnToRecoveryCode();return}this.closeRecovery();return}if(this.stateValue.kind===`link_device`){this.closeLinkDevice();return}(this.stateValue.kind===`performing`||this.stateValue.kind===`awaiting_external_auth`||this.stateValue.kind===`google_login`||this.stateValue.kind===`google_registration`)&&this.showPasskeyMode(this.stateValue.viewModel.mode)}openRecovery(){let e=this.stateValue;if(e.kind!==`preparing`&&e.kind!==`ready`||e.viewModel.kind!==`passkey`)return;let t={kind:`preparing`,viewModel:{...e.viewModel,status:{kind:`idle`,interaction:`arming`}}};this.invalidatePreparation(),this.recoveryReturnState=t,this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:t,viewModel:X({base:e.viewModel})},this.updateElement()}closeRecovery(){let e=this.stateValue;if(e.kind!==`recovery`)return;let t=e.returnState;this.invalidateRecovery(),this.recoveryReturnState=null,this.stateValue=t,this.updateElement(),this.preparePasskey=t.viewModel.mode===`login`?this.prepareSelectedLogin:null,this.startPasskeyPreparation()}changeRecoveryCode(e){let t=this.stateValue;t.kind!==`recovery`||t.stage!==`enter_code`||(this.stateValue={...t,viewModel:{...t.viewModel,recoveryCode:e,recoveryCodeError:null}},this.updateElement())}submitRecoveryCode(){let e=this.stateValue;if(e.kind!==`recovery`||e.stage!==`enter_code`)return;let t=Jt(e.viewModel.recoveryCode);if(t){this.stateValue={...e,viewModel:{...e.viewModel,recoveryCodeError:t}},this.updateElement();return}this.stateValue={...e,stage:`choose_method`,viewModel:X({base:e.viewModel,recoveryCode:e.viewModel.recoveryCode,stage:`choose_method`})},this.updateElement()}returnToRecoveryCode(){let e=this.stateValue;e.kind!==`recovery`||e.stage!==`choose_method`||(this.stateValue={...e,stage:`enter_code`,viewModel:X({base:e.viewModel,recoveryCode:e.viewModel.recoveryCode})},this.updateElement())}prepareRecovery(e=`passkey`){let t=this.stateValue;if(t.kind!==`recovery`||t.stage!==`choose_method`)return;let n=t.viewModel.recoveryCode.trim(),r;try{r=this.recoveryPort.targetFor(e)}catch{this.stateValue={...t,viewModel:X({base:t.viewModel,recoveryCode:t.viewModel.recoveryCode,stage:`choose_method`,status:$({kind:`refused`})})},this.updateElement();return}let i=++this.recoveryGeneration,a=new AbortController;this.recoveryCancellation=a,this.stateValue={...t,stage:`preparing`,viewModel:X({base:t.viewModel,recoveryCode:t.viewModel.recoveryCode,stage:`preparing`,target:r,status:{kind:`busy`,headline:`Checking recovery code…`}})},this.updateElement();let o;try{o=this.recoveryPort.prepare({recoveryCode:n,target:r,signal:a.signal})}catch{this.rejectRecoveryPreparation(i);return}o.then(this.completeRecoveryPreparation.bind(this,i),this.rejectRecoveryPreparation.bind(this,i))}completeRecoveryPreparation(e,t){let n=this.stateValue;if(e!==this.recoveryGeneration||n.kind!==`recovery`){t.kind===`hosted_recovery_prepared`&&this.recoveryPort.cancel(t).catch(K);return}if(this.recoveryCancellation=null,t.kind!==`hosted_recovery_prepared`){this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:n.returnState,viewModel:X({base:n.viewModel,recoveryCode:n.viewModel.recoveryCode,status:$(t)})},this.updateElement();return}if(Yt(t)){this.stateValue={kind:`recovery`,stage:`passkey_ready`,operation:t,returnState:n.returnState,viewModel:X({base:n.viewModel,walletId:String(t.walletId),recoveryCode:``,stage:`passkey_ready`,target:t.target})},this.createRecoveryPasskey();return}let r={kind:`recovery`,stage:`google_ready`,operation:t,returnState:n.returnState,viewModel:X({base:n.viewModel,walletId:String(t.walletId),recoveryCode:``,stage:`google_ready`,target:t.target})};this.stateValue=r,this.requestRecoveryGoogleVerification(`google`,r)||(this.stateValue={...r,viewModel:X({base:r.viewModel,walletId:Z(r.viewModel),stage:`google_ready`,target:r.operation.target,status:{kind:`recoverable`,reason:`error`,message:`Google sign-in is unavailable. Try again.`}})},this.updateElement())}rejectRecoveryPreparation(e){let t=this.stateValue;e!==this.recoveryGeneration||t.kind!==`recovery`||(this.recoveryCancellation=null,this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:t.returnState,viewModel:X({base:t.viewModel,recoveryCode:t.viewModel.recoveryCode,status:$({kind:`transport_uncertain`})})},this.updateElement())}startRecoveryGoogleVerification(e,t){let n=++this.recoveryGeneration;this.recoveryPort.verifyGoogle(e.operation,t).then(this.completeRecoveryGoogleVerification.bind(this,n),this.rejectRecoveryGoogleVerification.bind(this,n))}completeRecoveryGoogleVerification(e,t){let n=this.stateValue;if(e!==this.recoveryGeneration||n.kind!==`recovery`||n.stage!==`google_external_auth`){t.kind===`hosted_recovery_google_verified`&&this.recoveryPort.cancel(t).catch(K);return}if(t.kind!==`hosted_recovery_google_verified`){this.showRecoveryGoogleVerificationFailure(n,t);return}this.stateValue={kind:`recovery`,stage:`email_code_required`,operation:t,returnState:n.returnState,viewModel:X({base:n.viewModel,walletId:String(t.walletId),stage:`email_code_required`,target:t.target,challengeId:t.challengeId,emailHint:t.delivery.emailHint,delivery:t.delivery})},this.updateElement()}rejectRecoveryGoogleVerification(e){let t=this.stateValue;e!==this.recoveryGeneration||t.kind!==`recovery`||t.stage!==`google_external_auth`||this.showRecoveryGoogleVerificationFailure(t,{kind:`transport_uncertain`})}showRecoveryGoogleVerificationFailure(e,t){this.stateValue={kind:`recovery`,stage:`google_ready`,operation:e.operation,returnState:e.returnState,viewModel:X({base:e.viewModel,walletId:Z(e.viewModel),stage:`google_ready`,target:e.operation.target,status:$(t)})},this.updateElement()}changeRecoveryGoogleOtpCode(e){let t=this.stateValue;if(t.kind!==`recovery`||t.stage!==`email_code_required`)return;let n=e.replace(/\D/g,``).slice(0,6);this.stateValue={...t,viewModel:X({base:t.viewModel,walletId:Z(t.viewModel),stage:`email_code_required`,target:t.operation.target,challengeId:t.operation.challengeId,emailHint:t.operation.delivery.emailHint,delivery:t.operation.delivery,otpCode:n})},this.updateElement(),/^\d{6}$/.test(n)&&this.submitRecoveryGoogleOtp()}submitRecoveryGoogleOtp(){let e=this.stateValue;if(e.kind===`recovery`&&e.stage===`finalizing`&&e.operation.kind===`hosted_recovery_email_otp_verified`&&e.viewModel.status.kind===`recoverable`){this.finishRecovery(e.operation);return}if(e.kind!==`recovery`||e.stage!==`email_code_required`)return;let t=e.viewModel.otpCode.trim();if(!/^\d{6}$/.test(t))return;let n=++this.recoveryGeneration;this.stateValue={...e,viewModel:X({base:e.viewModel,walletId:Z(e.viewModel),stage:`email_code_required`,target:e.operation.target,challengeId:e.operation.challengeId,emailHint:e.operation.delivery.emailHint,delivery:e.operation.delivery,otpCode:t,status:{kind:`busy`,headline:`Verifying email code…`}})},this.updateElement(),this.recoveryPort.verifyEmailOtp(e.operation,{challengeId:e.operation.challengeId,otpCode:t}).then(this.completeRecoveryEmailOtpVerification.bind(this,n),this.rejectRecoveryEmailOtpVerification.bind(this,n))}completeRecoveryEmailOtpVerification(e,t){let n=this.stateValue;if(e!==this.recoveryGeneration||n.kind!==`recovery`||n.stage!==`email_code_required`){t.kind===`hosted_recovery_email_otp_verified`&&this.recoveryPort.cancel(t).catch(K);return}if(t.kind!==`hosted_recovery_email_otp_verified`){this.showRecoveryEmailOtpFailure(n,t);return}this.finishRecovery(t)}rejectRecoveryEmailOtpVerification(e){let t=this.stateValue;e!==this.recoveryGeneration||t.kind!==`recovery`||t.stage!==`email_code_required`||this.showRecoveryEmailOtpFailure(t,{kind:`transport_uncertain`})}showRecoveryEmailOtpFailure(e,t){this.stateValue={...e,viewModel:X({base:e.viewModel,walletId:Z(e.viewModel),stage:`email_code_required`,target:e.operation.target,challengeId:e.operation.challengeId,emailHint:e.operation.delivery.emailHint,delivery:e.operation.delivery,otpCode:e.viewModel.otpCode,status:$(t)})},this.updateElement()}createRecoveryPasskey(){let e=this.stateValue;if(e.kind!==`recovery`)return;if(e.stage===`finalizing`&&e.operation.kind===`hosted_recovery_credential_created`&&e.viewModel.status.kind===`recoverable`){this.finishRecovery(e.operation);return}if(e.stage!==`passkey_ready`)return;let t=++this.recoveryGeneration,n;try{n=this.recoveryPort.createPasskey(e.operation)}catch{this.showRecoveryCreateFailure(e,{kind:`refused`});return}this.stateValue={...e,stage:`finalizing`,viewModel:X({base:e.viewModel,walletId:Z(e.viewModel),stage:`finalizing`,target:Q(e.viewModel),status:{kind:`busy`,headline:`Creating new passkey…`}})},this.updateElement(),n.then(this.completeRecoveryCredentialCreation.bind(this,t),this.rejectRecoveryCredentialCreation.bind(this,t))}completeRecoveryCredentialCreation(e,t){let n=this.stateValue;if(e!==this.recoveryGeneration||n.kind!==`recovery`||n.stage!==`finalizing`||n.operation.kind!==`hosted_recovery_prepared`){t.kind===`hosted_recovery_credential_created`&&this.recoveryPort.cancel(t).catch(K);return}if(t.kind!==`hosted_recovery_credential_created`){this.showRecoveryCreateFailure({returnState:n.returnState,viewModel:n.viewModel,operation:n.operation},t);return}this.finishRecovery(t)}rejectRecoveryCredentialCreation(e){let t=this.stateValue;e!==this.recoveryGeneration||t.kind!==`recovery`||t.stage!==`finalizing`||t.operation.kind!==`hosted_recovery_prepared`||this.showRecoveryCreateFailure({returnState:t.returnState,viewModel:t.viewModel,operation:t.operation},{kind:`refused`})}showRecoveryCreateFailure(e,t){if(!Yt(e.operation)){this.recoveryPort.cancel(e.operation).catch(K),this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:e.returnState,viewModel:X({base:e.viewModel,recoveryCode:``,status:$(t)})},this.updateElement();return}if(t.kind===`refused`){this.recoveryPort.cancel(e.operation).catch(K),this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:e.returnState,viewModel:X({base:e.viewModel,recoveryCode:``,status:$(t)})},this.updateElement();return}this.stateValue={kind:`recovery`,stage:`passkey_ready`,operation:e.operation,returnState:e.returnState,viewModel:X({base:e.viewModel,walletId:Z(e.viewModel),stage:`passkey_ready`,target:e.operation.target,status:un(t)})},this.updateElement()}finishRecovery(e){let t=this.stateValue;if(t.kind!==`recovery`)return;let n=++this.recoveryGeneration;this.stateValue={kind:`recovery`,stage:`finalizing`,operation:e,returnState:t.returnState,viewModel:X({base:t.viewModel,walletId:Z(t.viewModel),stage:`finalizing`,target:Q(t.viewModel),status:{kind:`busy`,headline:`Finishing recovery…`}})},this.updateElement();let r;try{r=this.recoveryPort.finalize(e)}catch{this.rejectRecoveryFinalization(n);return}r.then(this.completeRecoveryFinalization.bind(this,n),this.rejectRecoveryFinalization.bind(this,n))}completeRecoveryFinalization(e,t){let n=this.stateValue;if(!(e!==this.recoveryGeneration||n.kind!==`recovery`||n.stage!==`finalizing`||n.operation.kind!==`hosted_recovery_credential_created`&&n.operation.kind!==`hosted_recovery_email_otp_verified`)){if(t.kind!==`ready_for_sign_in`){t.kind===`refused`?(this.recoveryPort.cancel(n.operation).catch(()=>{}),this.stateValue={kind:`recovery`,stage:`enter_code`,returnState:n.returnState,viewModel:X({base:n.viewModel,status:$(t)})}):this.stateValue={...n,viewModel:X({base:n.viewModel,walletId:Z(n.viewModel),stage:`finalizing`,target:Q(n.viewModel),status:ln()})},this.updateElement();return}if(n.operation.target.kind===`passkey`){this.prepareRecoveredPasskeyLogin(t.walletId,n.returnState);return}this.stateValue={kind:`recovery`,stage:`sign_in_ready`,returnState:n.returnState,viewModel:X({base:n.viewModel,walletId:String(t.walletId),stage:`sign_in_ready`,target:n.operation.target})},this.updateElement()}}rejectRecoveryFinalization(e){let t=this.stateValue;e!==this.recoveryGeneration||t.kind!==`recovery`||t.stage!==`finalizing`||t.operation.kind!==`hosted_recovery_credential_created`&&t.operation.kind!==`hosted_recovery_email_otp_verified`||(this.stateValue={...t,viewModel:X({base:t.viewModel,walletId:Z(t.viewModel),stage:`finalizing`,target:Q(t.viewModel),status:ln()})},this.updateElement())}prepareRecoveredPasskeyLogin(e,t){let n=this.stateValue;if(n.kind!==`recovery`)return;let r=++this.recoveryGeneration,i=new AbortController;this.recoveryCancellation=i;let a=this.prepareRecoveredLogin(e,{kind:`abort_signal`,signal:i.signal});this.stateValue={kind:`recovery`,stage:`sign_in_ready`,returnState:t,viewModel:X({base:n.viewModel,walletId:String(e),stage:`sign_in_ready`,target:Q(n.viewModel),status:{kind:`busy`,headline:`Preparing to unlock…`}})},this.updateElement(),a.then(this.completeRecoveredLoginPreparation.bind(this,r,t),this.rejectRecoveredLoginPreparation.bind(this,r,e,t))}completeRecoveredLoginPreparation(e,n,r){let i=this.stateValue;if(e!==this.recoveryGeneration||i.kind!==`recovery`){G(r);return}if(this.recoveryCancellation=null,r.kind!==`hosted_passkey_owner_login_prepared_v1`&&r.kind!==`hosted_passkey_linked_authority_login_prepared_v1`){G(r);let a=t(Z(i.viewModel));if(!a.ok)return;this.rejectRecoveredLoginPreparation(e,a.value,n);return}this.recoveryLoginPrepared=r,this.stateValue={kind:`recovery`,stage:`sign_in_ready`,returnState:n,viewModel:X({base:i.viewModel,walletId:Z(i.viewModel),stage:`sign_in_ready`,target:Q(i.viewModel)})},this.updateElement()}rejectRecoveredLoginPreparation(e,t,n){let r=this.stateValue;e!==this.recoveryGeneration||r.kind!==`recovery`||(this.recoveryCancellation=null,this.stateValue={kind:`recovery`,stage:`sign_in_ready`,returnState:n,viewModel:X({base:r.viewModel,walletId:String(t),stage:`sign_in_ready`,target:Q(r.viewModel),status:{kind:`recoverable`,reason:`error`,message:`Your wallet was recovered. Unlock it again to continue.`}})},this.updateElement())}signInRecoveredWallet(){let e=this.stateValue;if(e.kind!==`recovery`||e.stage!==`sign_in_ready`)return;if(e.viewModel.target.kind===`google_email_otp`){this.requestExternalAuth(`google`);return}let n=this.recoveryLoginPrepared;if(!n){let n=t(Z(e.viewModel));if(!n.ok)return;this.prepareRecoveredPasskeyLogin(n.value,e.returnState);return}this.recoveryLoginPrepared=null,this.performPreparedPasskey(n)}openLinkDevice(){let e=this.stateValue;if(e.kind!==`preparing`&&e.kind!==`ready`||e.viewModel.kind!==`passkey`)return;let t={kind:`preparing`,viewModel:{...e.viewModel,status:{kind:`idle`,interaction:`arming`}}};this.invalidatePreparation(),this.linkedDeviceActivationInProgress=!1,this.targetPasskeyActivation=null,this.targetEmailOtpActivation=null,this.linkedDeviceEmailOtpSendStarted=!1,this.linkedDeviceTargetFactor={kind:`passkey_prf`},this.linkedDeviceTargetEmailAddress=``,this.stateValue={kind:`link_device`,returnState:t,viewModel:cn(e.viewModel)},this.updateElement()}selectLinkedDeviceTargetFactor(e){let t=this.stateValue;t.kind!==`link_device`||t.viewModel.linkDevice.kind!==`select_factor`||(this.linkedDeviceTargetFactor=e,this.stateValue={...t,viewModel:{...t.viewModel,linkDevice:e.kind===`email_otp`?{kind:`select_factor`,targetFactor:e,targetEmail:this.linkedDeviceTargetEmailAddress}:{kind:`select_factor`,targetFactor:e}}},this.updateElement())}changeLinkedDeviceTargetEmailAddress(e){let t=this.stateValue;t.kind!==`link_device`||t.viewModel.linkDevice.kind!==`select_factor`||t.viewModel.linkDevice.targetFactor.kind!==`email_otp`||(this.linkedDeviceTargetEmailAddress=e,this.stateValue={...t,viewModel:{...t.viewModel,linkDevice:{kind:`select_factor`,targetFactor:t.viewModel.linkDevice.targetFactor,targetEmail:e}}},this.updateElement())}startSelectedDeviceLinking(){let e=this.stateValue;if(e.kind!==`link_device`||e.viewModel.linkDevice.kind!==`select_factor`)return;let t=e.viewModel.linkDevice,n;try{if(t.targetFactor.kind===`email_otp`){let e=t.targetEmail;if(typeof e!=`string`)throw Error(`linked-device target email address is unavailable`);n=Zt({targetFactor:t.targetFactor,targetEmail:e})}else n=Zt({targetFactor:t.targetFactor})}catch(t){this.stateValue={...e,viewModel:{...e.viewModel,linkDevice:{...e.viewModel.linkDevice,error:Y(t)}}},this.updateElement();return}let r=++this.deviceLinkGeneration;this.stateValue={...e,viewModel:{...e.viewModel,linkDevice:{kind:`loading`,message:`Generating QR code...`}}},this.updateElement(),this.startDeviceLinking(n,{onEvent:this.onLinkDeviceEvent.bind(this,r),onTargetFactorRequired:this.onTargetFactorRequired.bind(this,r)}).then(this.completeLinkDeviceOpen.bind(this,r)).catch(this.failLinkDeviceOpen.bind(this,r))}onLinkDeviceEvent(e,t){let n=this.stateValue;if(e!==this.deviceLinkGeneration||n.kind!==`link_device`)return;let r=Ee(t);switch(r.kind){case`active`:if(this.linkedDeviceActivationInProgress)return;this.linkedDeviceActivationInProgress=!0,this.complete({kind:`authenticated`,authMenuSessionId:this.identity.authMenuSessionId,walletId:r.walletId,method:this.linkedDeviceTargetFactor.kind===`email_otp`?`google_email_otp`:`passkey`});return;case`invalid_active`:this.showLinkedDeviceActivationError(n,Error(`Linked-device activation omitted its wallet identity`));return;case`failed`:if(t.error?.code===c.SESSION_EXPIRED){this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:{kind:`expired`,message:`This linking request expired. Start again to link this device.`}}},this.updateElement();return}if(t.error?.code===c.DELIVERY_RECOVERY_REQUIRED){this.showLinkedDeviceActivationError(n,Error(t.message||`Go back and unlock the new linked method to finish setup.`));return}break;case`cancelled`:this.targetPasskeyActivation=null,this.targetEmailOtpActivation=null,this.linkedDeviceEmailOtpSendStarted=!1,this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:{kind:`cancelled`,message:`The other device cancelled this linking request. Go back to try again.`}}},this.updateElement();return;case`pending`:break;default:return pn(r)}let i=t.message?.trim();if(!i)return;let a=n.viewModel.linkDevice,o=a.kind===`email_otp_required`?a:a.kind===`ready`||a.kind===`passkey_required`||a.kind===`creating_passkey`?{...a,message:i}:{kind:`loading`,message:i};this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:o}},this.updateElement()}showLinkedDeviceActivationError(e,t){this.stateValue={...e,viewModel:{...e.viewModel,linkDevice:{kind:`activation_error`,message:Y(t)}}},this.updateElement()}completeLinkDeviceOpen(e,t){let n=this.stateValue;e!==this.deviceLinkGeneration||n.kind!==`link_device`||this.linkedDeviceActivationInProgress||n.viewModel.linkDevice.kind!==`loading`||(this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:this.targetPasskeyActivation?{kind:`passkey_required`,message:`Create a passkey to finish linking this device`}:{kind:`ready`,qrCodeDataURL:t.qrCodeDataURL,message:`Waiting for device to scan`}}},this.updateElement())}onTargetFactorRequired(e,t){switch(t.kind){case`linked_device_target_passkey_activation_v1`:this.onTargetPasskeyActivation(e,t);return;case`linked_device_target_email_otp_activation_v1`:this.onTargetEmailOtpActivation(e,t);return;default:return mn(t)}}onTargetPasskeyActivation(e,t){let n=this.stateValue;e!==this.deviceLinkGeneration||n.kind!==`link_device`||(this.targetPasskeyActivation=t,n.viewModel.linkDevice.kind===`ready`&&(this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:{kind:`passkey_required`,message:`Create a passkey to finish linking this device`}}},this.updateElement()))}onTargetEmailOtpActivation(e,t){let n=this.stateValue;e!==this.deviceLinkGeneration||n.kind!==`link_device`||(this.targetEmailOtpActivation=t,this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:{kind:`email_otp_required`,state:t.state,otpCode:n.viewModel.linkDevice.kind===`email_otp_required`?n.viewModel.linkDevice.otpCode:``}}},this.updateElement(),t.state.kind===`sending`&&!this.linkedDeviceEmailOtpSendStarted&&(this.linkedDeviceEmailOtpSendStarted=!0,t.sendCode().catch(this.failLinkedDeviceEmailOtp.bind(this))))}changeLinkedDeviceEmailOtpCode(e){let t=this.stateValue;if(t.kind!==`link_device`||t.viewModel.linkDevice.kind!==`email_otp_required`)return;let n=e.replace(/\D/g,``).slice(0,6),r=t.viewModel.linkDevice.otpCode,i=t.viewModel.linkDevice.state;this.stateValue={...t,viewModel:{...t.viewModel,linkDevice:{...t.viewModel.linkDevice,otpCode:n}}},this.updateElement(),n.length===6&&n!==r&&(i.kind===`code_input`||i.kind===`incorrect`)&&this.submitLinkedDeviceEmailOtpCode(n)}resendLinkedDeviceEmailOtp(){let e=this.targetEmailOtpActivation;e&&e.resendCode().catch(this.failLinkedDeviceEmailOtp.bind(this))}submitLinkedDeviceEmailOtp(){let e=this.stateValue;e.kind!==`link_device`||e.viewModel.linkDevice.kind!==`email_otp_required`||e.viewModel.linkDevice.otpCode.length!==6||this.submitLinkedDeviceEmailOtpCode(e.viewModel.linkDevice.otpCode)}submitLinkedDeviceEmailOtpCode(e){let t=this.targetEmailOtpActivation;t&&t.submitCode(e).catch(this.failLinkedDeviceEmailOtp.bind(this))}failLinkedDeviceEmailOtp(e){let t=this.stateValue;t.kind===`link_device`&&this.showLinkedDeviceActivationError(t,e)}createLinkedDevicePasskey(){let e=this.stateValue,t=this.targetPasskeyActivation;!t||e.kind!==`link_device`||e.viewModel.linkDevice.kind!==`passkey_required`||(this.targetPasskeyActivation=null,this.stateValue={...e,viewModel:{...e.viewModel,linkDevice:{kind:`creating_passkey`,message:`Follow the passkey prompt on your screen`}}},this.updateElement(),t.createPasskey().catch(this.failTargetPasskeyCreation.bind(this)))}failTargetPasskeyCreation(e){let t=this.stateValue;t.kind===`link_device`&&(this.stateValue={...t,viewModel:{...t.viewModel,linkDevice:{kind:`error`,message:Y(e)}}},this.updateElement())}failLinkDeviceOpen(e,t){let n=this.stateValue;e!==this.deviceLinkGeneration||n.kind!==`link_device`||this.linkedDeviceActivationInProgress||n.viewModel.linkDevice.kind!==`loading`||(this.stateValue={...n,viewModel:{...n.viewModel,linkDevice:{kind:`error`,message:Y(t)}}},this.updateElement())}closeLinkDevice(){let e=this.stateValue;e.kind===`link_device`&&(this.deviceLinkGeneration+=1,this.targetPasskeyActivation=null,this.targetEmailOtpActivation=null,this.linkedDeviceEmailOtpSendStarted=!1,this.cancelDeviceLinking().catch(()=>{}),this.stateValue=e.returnState,this.updateElement(),this.startPasskeyPreparation())}rerollRegistrationWallet(){let e=this.stateValue;e.kind!==`ready`&&e.kind!==`preparing`||e.viewModel.kind!==`passkey`||e.viewModel.mode!==`register`||!e.viewModel.passkeyNameReadOnly||!e.viewModel.showRegistrationInput||(this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...e.viewModel,passkeyName:String(Te()),status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.startPasskeyPreparation())}selectLoginAccount(e,t){let n=this.loginAccountOptions.find(n=>n.walletId===e&&n.authMethod===t);if(!n||n.walletId===this.selectedLoginAccount?.walletId&&n.authMethod===this.selectedLoginAccount.authMethod)return;let r=this.stateValue;if(r.kind!==`preparing`&&r.kind!==`ready`||r.viewModel.kind!==`passkey`||r.viewModel.mode!==`login`)return;let i=n.walletId!==this.selectedLoginAccount?.walletId;if(this.selectedLoginAccount=n,!i){this.updateLoginSelectionViewModel(),this.updateElement();return}this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...r.viewModel,selectedAccount:n,status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.activateSelectedLoginMethod()}retryPreparation(){let e=this.stateValue;e.kind!==`preparing`||e.viewModel.kind!==`passkey`||e.viewModel.status.kind!==`recoverable`||(this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...e.viewModel,status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.startPasskeyPreparation())}updateGoogleOtpCode(e){let t=this.stateValue;if(t.kind!==`google_login`||t.viewModel.submitBusy)return;let n=e.replace(/\D/g,``).slice(0,6);this.stateValue={...t,viewModel:{...t.viewModel,otpCode:n,error:``}},this.updateElement(),/^\d{6}$/.test(n)&&this.submitGoogleOtp()}resendGoogleOtp(){let e=this.stateValue;if(e.kind!==`google_login`||e.viewModel.resendBusy)return;let t=e.flow;this.stateValue={...e,viewModel:{...e.viewModel,status:{kind:`busy`,headline:`Sending a new email code`},resendBusy:!0,error:``}},this.updateElement(),en(t.resend()).then(n=>{if(this.stateValue.kind!==`google_login`||this.stateValue.flow!==t){n.ok&&n.value.cancel().catch(()=>{});return}if(!n.ok){this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},resendBusy:!1,error:n.error.message}},this.updateElement();return}if(n.value.mode!==`login`){n.value.cancel().catch(()=>{}),this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},resendBusy:!1,error:`Google returned an unexpected registration flow.`}},this.updateElement();return}let r=n.value;this.stateValue={kind:`google_login`,flow:r,viewModel:an({base:e.viewModel,flow:r})},this.updateElement()},e=>{this.stateValue.kind!==`google_login`||this.stateValue.flow!==t||(this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},resendBusy:!1,error:Y(e)}},this.updateElement())})}submitGoogleOtp(){let e=this.stateValue;if(e.kind!==`google_login`||e.viewModel.submitBusy)return;let t=e.viewModel.otpCode;if(!/^\d{6}$/.test(t)){this.stateValue={...e,viewModel:{...e.viewModel,status:{kind:`idle`,interaction:`actionable`},error:`Enter the 6-digit code from your email.`}},this.updateElement();return}let n=e.flow;this.stateValue={...e,viewModel:{...e.viewModel,status:{kind:`busy`,headline:`Verifying your email code`},submitBusy:!0,error:``}},this.updateElement(),n.submit({otpCode:t}).then(e=>{if(!(this.stateValue.kind!==`google_login`||this.stateValue.flow!==n)){if(!e.ok){this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},submitBusy:!1,error:e.error.message}},this.updateElement();return}if(e.value.mode!==`login`){this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},submitBusy:!1,error:`Google returned an unexpected registration result.`}},this.updateElement();return}this.complete({kind:`authenticated`,authMenuSessionId:this.identity.authMenuSessionId,walletId:e.value.walletId,method:`google_email_otp`})}},e=>{this.stateValue.kind!==`google_login`||this.stateValue.flow!==n||(this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},submitBusy:!1,error:Y(e)}},this.updateElement())})}rerollGoogleRegistration(){let e=this.stateValue;if(e.kind!==`google_registration`||e.viewModel.rerollBusy)return;let t=e.flow;this.stateValue={...e,viewModel:{...e.viewModel,status:{kind:`busy`,headline:`Generating another wallet name`},rerollBusy:!0,error:``}},this.updateElement(),t.rerollWalletId().then(n=>{if(this.stateValue.kind!==`google_registration`||this.stateValue.flow!==t){n.ok&&n.value.cancel().catch(()=>{});return}if(!n.ok){this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},rerollBusy:!1,error:n.error.message}},this.updateElement();return}if(n.value.mode!==`register`){n.value.cancel().catch(()=>{}),this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},rerollBusy:!1,error:`Google returned an unexpected login flow.`}},this.updateElement();return}let r=n.value;this.stateValue={kind:`google_registration`,flow:r,viewModel:on({base:e.viewModel,flow:r})},this.updateElement()},e=>{this.stateValue.kind!==`google_registration`||this.stateValue.flow!==t||(this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},rerollBusy:!1,error:Y(e)}},this.updateElement())})}completeGoogleRegistration(){let e=this.stateValue;if(e.kind!==`google_registration`||e.viewModel.submitBusy)return;let t=e.flow;this.stateValue={...e,viewModel:{...e.viewModel,status:{kind:`busy`,headline:`Creating your wallet`},submitBusy:!0,error:``}},this.updateElement(),t.completeRegistration().then(e=>{if(!(this.stateValue.kind!==`google_registration`||this.stateValue.flow!==t)){if(!e.ok){this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},submitBusy:!1,error:e.error.message}},this.updateElement();return}this.complete({kind:`registered`,authMenuSessionId:this.identity.authMenuSessionId,walletId:e.value.walletId,method:`google_email_otp`})}},e=>{this.stateValue.kind!==`google_registration`||this.stateValue.flow!==t||(this.stateValue={...this.stateValue,viewModel:{...this.stateValue.viewModel,status:{kind:`idle`,interaction:`actionable`},submitBusy:!1,error:Y(e)}},this.updateElement())})}complete(e){if(this.stateValue.kind===`complete`)return;this.stateValue={kind:`complete`,outcome:e},this.cleanup();let t=this.outcomeResolver;this.outcomeResolver=null,t?.(e)}performPreparedPasskey(e){this.prepared=null;let t=this.currentViewModel();if(this.stateValue={kind:`performing`,prepared:e,viewModel:t.kind===`recovery`?X({base:t,walletId:Z(t),stage:`sign_in_ready`,target:Q(t),status:{kind:`busy`,headline:b(`login`),illustration:`passkey`,detail:`Continue with your passkey`}}):{...t,status:{kind:`busy`,headline:b(t.mode),illustration:`passkey`,detail:`Continue with your passkey`}}},e.kind===`hosted_passkey_owner_login_prepared_v1`||e.kind===`hosted_passkey_linked_authority_login_prepared_v1`){this.updateElement(),this.finishPreparedPasskey(e);return}let n;try{n=this.startPreparedCredential(e)}catch(t){this.updateElement(),this.failPreparedPasskey(e,t);return}this.updateElement(),n.then(()=>this.finishPreparedPasskey(e),t=>this.failPreparedPasskey(e,t))}startPreparedCredential(e){return e.kind===`hosted_passkey_registration_prepared_v1`?Se(e):Ut(e)}async finishPreparedPasskey(e){try{switch(e.kind){case`hosted_passkey_registration_prepared_v1`:{let t=await ve({prepared:e});this.completeRegistrationResult(t);return}case`hosted_passkey_owner_login_prepared_v1`:case`hosted_passkey_linked_authority_login_prepared_v1`:{let t=await Gt(e);this.completeLoginResult(t);return}case`hosted_passkey_account_sync_prepared_v1`:{let t=await Kt(e);this.completeAccountSyncResult(t);return}default:return hn(e)}}catch(t){this.failPreparedPasskey(e,t)}}completeRegistrationResult(e){if(!e.success||e.kind!==`wallet_registered`&&e.kind!==`ecdsa_wallet_registered_near_pending`){this.fail({kind:`error`,error:Error(e.success?`Hosted registration returned an unexpected result`:e.error)});return}let n=t(String(e.walletId));if(!n.ok){this.fail({kind:`error`,error:Error(`Hosted registration returned an invalid wallet id`)});return}this.complete({kind:`registered`,authMenuSessionId:this.identity.authMenuSessionId,walletId:n.value,method:`passkey`})}completeLoginResult(e){let n=e.result;if(!n.success){this.fail(e.cancelledByUser?{kind:`dismissed`}:{kind:`error`,error:Error(n.error)});return}let r=t(String(n.walletId));if(!r.ok){this.fail({kind:`error`,error:Error(`Hosted login returned an invalid wallet id`)});return}this.complete({kind:`authenticated`,authMenuSessionId:this.identity.authMenuSessionId,walletId:r.value,method:`passkey`})}completeAccountSyncResult(e){if(!e.success){this.fail({kind:`error`,error:Error(e.error)});return}let n=t(String(e.walletId));if(!n.ok){this.fail({kind:`error`,error:Error(`Hosted account sync returned an invalid wallet id`)});return}this.complete({kind:`account_synced`,authMenuSessionId:this.identity.authMenuSessionId,walletId:n.value})}failPreparedPasskey(e,t){if(this.stateValue.kind!==`performing`||this.stateValue.prepared!==e)return;if(this.preparationCancellation?.signal.aborted){this.fail({kind:`dismissed`});return}let n=t instanceof Error?t.name:``;if(n===`NotAllowedError`||n===`AbortError`){this.fail({kind:`dismissed`});return}this.fail({kind:`error`,error:t})}fail(e){if(this.stateValue.kind!==`performing`)return;let t=this.stateValue.viewModel;if(G(this.stateValue.prepared),this.prepared=null,t.kind===`recovery`){let n=this.recoveryReturnState;if(!n)return;this.recoveryLoginPrepared=null,this.stateValue={kind:`recovery`,stage:`sign_in_ready`,returnState:n,viewModel:X({base:t,walletId:Z(t),stage:`sign_in_ready`,target:Q(t),status:e.kind===`dismissed`?{kind:`idle`,interaction:`actionable`}:x(Y(e.error))})},this.updateElement();return}if(e.kind===`dismissed`){this.invalidatePreparation(),this.stateValue={kind:`preparing`,viewModel:{...t,status:{kind:`idle`,interaction:`arming`}}},this.updateElement(),this.startPasskeyPreparation();return}this.stateValue={kind:`preparing`,viewModel:{...t,status:x(Y(e.error))}},this.updateElement()}};function fn(e){throw Error(`Unhandled auth-menu intent: ${String(e)}`)}function pn(e){throw Error(`Unhandled link-device flow outcome: ${String(e)}`)}function mn(e){throw Error(`Unhandled linked-device target-factor activation: ${String(e)}`)}function hn(e){throw Error(`Unhandled hosted passkey preparation: ${String(e)}`)}function gn(e){throw Error(`Unhandled hosted external-auth evidence: ${String(e)}`)}function _n(e){return`${e.walletId}:${e.authMethod}`}function vn(e,t){let n=String(e.walletId);switch(e.authMethod){case`passkey`:return{walletId:n,authMethod:`passkey`};case`email_otp`:return{walletId:n,authMethod:`email_otp`,emailAddress:e.emailAddress??(t?.authMethod===`email_otp`?t.emailAddress:null)}}}function yn(e,t=[]){let n=new Map;for(let t of e?.accounts??[]){if(t.authMethod!==m.passkey&&t.authMethod!==m.emailOtp)continue;let e=String(t.walletId||``).trim();if(!e)continue;let r=t.authMethod===m.passkey?{walletId:e,authMethod:`passkey`}:{walletId:e,authMethod:`email_otp`,emailAddress:null};n.set(_n(r),r)}for(let e of t){let t=String(e.walletId||``).trim();if(!t)continue;let r=`${t}:${e.authMethod}`,i=vn(e,n.get(r));n.set(r,i)}return[...n.values()]}function bn(e,t){let n=e?.lastUsedAccount;if(n?.authMethod===m.passkey||n?.authMethod===m.emailOtp){let e=String(n.walletId||``).trim(),r=t.find(t=>t.walletId===e&&t.authMethod===n.authMethod);if(r)return r}return t[0]??null}function xn(e){let t=e?.lastUsedAccount;return!t||t.authMethod!==m.passkey&&t.authMethod!==`linked_device`?null:String(t.walletId||``).trim()||null}async function Sn(e){let t=await import(`./recovery-entrypoint-BULjaFBM.js`),n=e();return t.createHostedRecoveryPort({context:n.getContext(),relayUrl:String(n.configs.network.relayer.url)})}var Cn=class{constructor(e){this.getWalletRuntime=e,this.portPromise=null}targetFor(t){if(t===`google_email_otp`)return{kind:t,googleProvider:`google`};let n=e(this.getWalletRuntime().getContext().signingEngine.getRpId());if(!n.ok)throw Error(`wallet recovery RP ID ${n.error.message}`);return{kind:t,rpId:n.value}}async prepare(e){return await(await this.port()).prepare(e)}async createPasskey(e){return await(await this.port()).createPasskey(e)}async verifyGoogle(e,t){return await(await this.port()).verifyGoogle(e,t)}async verifyEmailOtp(e,t){return await(await this.port()).verifyEmailOtp(e,t)}async finalize(e){return await(await this.port()).finalize(e)}async cancel(e){await(await this.port()).cancel(e)}port(){return this.portPromise??=Sn(this.getWalletRuntime),this.portPromise}};function wn(){try{let e=document.referrer.trim();if(e){let t=new URL(e).hostname.trim();if(t)return t}}catch{}return window.location.hostname||`Wallet`}function Tn(e){switch(e.kind){case`discoverable`:return null;case`wallet`:case`wallet_sync`:return String(e.walletId)}}function En(e){window.setTimeout(e,0)}function Dn(){return new Promise(En)}var On=class{constructor(e){this.deps=e,this.sessions=new Map,this.startDeviceLinking=async(e,t)=>await this.deps.getWalletRuntime().devices.startLinking({...e,options:t}),this.cancelDeviceLinking=async()=>await this.deps.getWalletRuntime().devices.cancelLinking()}async open(e){if(!e.requestId)throw Error(`Hosted auth-menu open request requires requestId`);let t=ge(e.requestId);if(this.sessions.has(e.request.authMenuSessionId))throw Error(`Hosted auth-menu session is already active`);let n=new dn({request:e.request,requestId:t,appearance:this.deps.getAppearance(),hostname:wn(),beginGoogleEmailOtp:async({idToken:e,authTarget:t,signal:n})=>await this.beginGoogleEmailOtp({idToken:e,authTarget:t,signal:n}),startDeviceLinking:this.startDeviceLinking,cancelDeviceLinking:this.cancelDeviceLinking,recoveryPort:new Cn(this.deps.getWalletRuntime),prepareRecoveredLogin:this.prepareRecoveredLogin.bind(this,t,e.request.authMenuSessionId),sendToParent:this.deps.send}),r=n.waitForOutcome(),i=Tn(e.request.loginTarget);this.sessions.set(e.request.authMenuSessionId,n);try{return n.mount(),await Dn(),n.setRegistrationPreparation((r,i,a)=>this.prepareRegistration(e.request,t,n.identity.authMenuSessionId,r,i,a)),i?await this.bootstrapLoginAccounts(n,t,e.request.loginTarget):(n.setLoginPreparation({accountOptions:[],selectedAccount:null,prepare:(r,i)=>this.prepareLogin(t,n.identity.authMenuSessionId,i,r,null,e.request.loginTarget)}),this.bootstrapLoginAccounts(n,t,e.request.loginTarget)),await r}finally{n.cleanup(),this.sessions.delete(e.request.authMenuSessionId)}}async bootstrapLoginAccounts(e,t,n){let[r,i]=await Promise.all([this.deps.getWalletRuntime().auth.getRecentUnlocks().catch(()=>null),f().catch(()=>[])]);if(e.state.kind===`complete`)return;let a=Tn(n),o=yn(r,i),s=a?o.filter(e=>e.walletId===a):o,c=s.length>0||!a?s:[{walletId:a,authMethod:m.passkey}];e.setLoginPreparation({accountOptions:c,selectedAccount:a?c[0]??null:bn(r,c),prepare:(i,a)=>this.prepareLogin(t,e.identity.authMenuSessionId,a,i,r,n)}),i.length>0&&e.defaultToLoginForDetectedLocalWallet()}async prepareLogin(e,t,n,r,i,a){let o=It(this.deps.getWalletRuntime().getContext()),s=i??await this.deps.getWalletRuntime().auth.getRecentUnlocks().catch(()=>null),c=(await f().catch(()=>[])).find(e=>e.authMethod===m.passkey),l=r||xn(s)||c?.walletId||null;return a.kind===`wallet_sync`?await U({context:o,walletId:String(a.walletId),authMenuSessionId:t,requestId:e,cancellation:n}):l?await Ht({context:o,walletId:l,authMenuSessionId:t,requestId:e,cancellation:n}):await U({context:o,walletId:l,authMenuSessionId:t,requestId:e,cancellation:n})}async prepareRecoveredLogin(e,t,n,r){return await Ht({context:It(this.deps.getWalletRuntime().getContext()),walletId:String(n),authMenuSessionId:t,requestId:e,cancellation:r})}async beginGoogleEmailOtp(e){if(e.signal.aborted)throw Error(`Google sign-in was cancelled`);let t=await this.deps.getWalletRuntime().auth.startGoogleSignIn({idToken:e.idToken,...e.authTarget});if(!t.ok)throw Error(t.error.message);let n=t.value;if(e.signal.aborted)throw await n.cancel().catch(()=>{}),Error(`Google sign-in was cancelled`);return n}async prepareRegistration(t,n,r,i,a,o){let s=this.deps.getWalletRuntime().getContext(),c=e(String(s.signingEngine.getRpId()||``));if(!c.ok)throw Error(c.error.message);let l={kind:`provided`,walletId:we(i)},u=be({configs:s.configs,wallet:l,preference:t.registrationAccountInput===`sponsored_named_near_account`?{kind:`relayer_named_subaccount`}:{kind:`implicit_account`}});return await xe({context:s,wallet:l,signerSelection:_e({configs:s.configs,accountProvisioning:u,options:{}}),authMethod:{kind:`passkey`,rpId:c.value},authMenuSessionId:r,requestId:n,cancellation:a,options:{onEvent:o}})}cancel(e){let t=this.sessions.get(e.authMenuSessionId);return!t||t.identity.requestId!==e.requestId?!1:(t.cancel(e.reason),!0)}resolveExternalAuth(e){let t=this.sessions.get(e.authMenuSessionId);return!t||t.identity.requestId!==e.requestId?!1:t.acceptExternalAuthResolution(e)}};function kn(e,t=new On({getWalletRuntime:e.getWalletRuntime,getAppearance:()=>e.getWalletRuntime().configs.ui.appearance,send:e.post})){return{PM_OPEN_AUTH_MENU:async n=>{let r=a(n.payload);if(!r)throw Error(`Hosted auth-menu open request is invalid`);let i=await t.open({request:r,requestId:n.requestId});(i.kind===`authenticated`||i.kind===`registered`||i.kind===`account_synced`)&&await e.publishCurrentSession(),!e.respondIfCancelled(n.requestId)&&p(e,n.requestId,i)},PM_CANCEL_AUTH_MENU:async n=>{let r=i(n.payload);if(!r)throw Error(`Hosted auth-menu cancellation is invalid`);let a=t.cancel(r);p(e,n.requestId,{cancelled:a})},PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH:async n=>{let r=s(n.payload);if(!r)throw Error(`Hosted auth-menu external-auth resolution is invalid`);let i=t.resolveExternalAuth(r);p(e,n.requestId,{accepted:i})}}}function An(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=t.options&&typeof t.options==`object`&&!Array.isArray(t.options)?t.options:null,r=n?.ecdsaKeyFactsInventory&&typeof n.ecdsaKeyFactsInventory==`object`&&!Array.isArray(n.ecdsaKeyFactsInventory)?n.ecdsaKeyFactsInventory:null,i=r?.value&&typeof r.value==`object`&&!Array.isArray(r.value)?r.value:null;if(i&&(Object.prototype.hasOwnProperty.call(i,`walletSessionToken`)||Object.prototype.hasOwnProperty.call(i,`operationCredential`)))throw Error(`wallet iframe unlock requests must not carry a Wallet Session bearer`)}function jn(e,t){let n=e.ecdsaKeyFactsInventory,{ecdsaKeyFactsInventory:r,...i}=e;if(!n)return i;if(n.mode===`webauthn`)return{...i,ecdsaKeyFactsInventory:n};let a=ie(t);if(!a)throw Error(`Hosted-wallet Wallet Session is required for opaque key-facts lookup`);return{...i,ecdsaKeyFactsInventory:{mode:`wallet_session_operation_credential_v1`,operationCredential:a}}}function Mn(e,t){return String(t?.walletId||``).trim()||String(e.preferences.getCurrentWalletId()||``).trim()||void 0}function Nn(e){console.warn(`[WalletIframeHost] Restored-session presignature prefill failed:`,e)}function Pn(e,t,n,r,i){e.respondIfCancelled(n)||(p(e,n,i),r.authenticationRead===`restore`&&t.prefillRestoredWalletSession(i.state).catch(Nn))}function Fn(e){return{...kn(e),PM_UNLOCK:async t=>{let n=e.getWalletRuntime();An(t.payload);let r=Ue(t.payload),i=jn(We(r),n.configs.network.relayer.url);if(e.respondIfCancelled(t.requestId))return;let a=await n.auth.unlock(r.walletId,ce(e,t.requestId,i));e.respondIfCancelled(t.requestId)||(a.success||d(),await e.publishCurrentSession(),!e.respondIfCancelled(t.requestId)&&p(e,t.requestId,a))},PM_LOCK:async t=>{let n=e.getWalletRuntime();d(),await n.auth.lock(),ue(e,t.requestId)},PM_LOCK_EXACT_WALLET_SESSION:async t=>{let n=e.getWalletRuntime(),r=l(t.payload),i=await ne(n,{authenticationRead:`current`,wallet:{kind:`current`}},new je);if(i.kind!==`active_session`&&i.kind!==`expired_session`||!me(i,r)){p(e,t.requestId,{kind:`stale_session`,expected:r,current:i});return}d(),await n.auth.lock(),p(e,t.requestId,{kind:`locked`,identity:r})},...Re(e),PM_GET_WALLET_SESSION:async t=>{let n=e.getWalletRuntime(),r=Mn(n,t.payload),i=await n.auth.getSession(r);p(e,t.requestId,i)},PM_GET_EXACT_WALLET_SESSION_STATE:async t=>{let n=e.getWalletRuntime(),r=t.payload;if(!r||r.authenticationRead!==`restore`&&r.authenticationRead!==`current`||!r.wallet||r.wallet.kind!==`current`&&r.wallet.kind!==`exact`||r.authenticationRead===`restore`&&r.wallet.kind!==`current`)throw Error(`Wallet iframe exact session read mode is invalid`);await e.observeSession(r,Pn.bind(null,e,n,t.requestId,r))},PM_GET_RECENT_UNLOCKS:async t=>{let n=await e.getWalletRuntime().auth.getRecentUnlocks();p(e,t.requestId,n)}}}async function In(e){await te(e,Fn)}export{In as handleWalletHostRuntimeRequest};
|