@seams/wallet 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +3 -3
  2. package/dist/.build-inputs.sha256 +1 -1
  3. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +160 -140
  4. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/linkDeviceBadge.js +90 -0
  5. package/dist/esm/core/config/defaultConfigs.js +1 -1
  6. package/dist/esm/sdk/{host-CHQwi-Nm.js → host-BAeJh9rB.js} +1 -1
  7. package/dist/{public/sdk/presignaturePool-CLHu7HaU.js → esm/sdk/presignaturePool-Bkk6bLFB.js} +1 -1
  8. package/dist/esm/sdk/routerAbNormalSigning-B35zb-P-.js +1 -0
  9. package/dist/esm/sdk/runtime-auth-D7VqiZeg.js +1 -0
  10. package/dist/esm/sdk/{runtime-device-link-DXjabXJb.js → runtime-device-link-BKc_MD5V.js} +1 -1
  11. package/dist/esm/sdk/{runtime-ecdsa-tempo-DlKMIbyP.js → runtime-ecdsa-tempo-DC51NDrh.js} +1 -1
  12. package/dist/esm/sdk/{runtime-email-otp-BBPghU2G.js → runtime-email-otp-C-wopKFf.js} +1 -1
  13. package/dist/esm/sdk/{runtime-export-pw-xJL8o.js → runtime-export-BtGy8BKi.js} +1 -1
  14. package/dist/esm/sdk/{runtime-near-B-vYxGjl.js → runtime-near-nq8pgRAl.js} +1 -1
  15. package/dist/esm/sdk/{runtime-preferences-D-hY0RfC.js → runtime-preferences-778ZfMmT.js} +1 -1
  16. package/dist/esm/sdk/{runtime-recovery-Vg1ND2nl.js → runtime-recovery-B-JsRiN0.js} +1 -1
  17. package/dist/esm/sdk/{secp256k1-C-AETUpI.js → secp256k1-CYQS0rj-.js} +1 -1
  18. package/dist/esm/sdk/{shared-6bpRPbcM.js → shared-B6BCLs8L.js} +1 -1
  19. package/dist/esm/sdk/{signEvmFamily-M0trbeZe.js → signEvmFamily-ttVfV0qm.js} +1 -1
  20. package/dist/{public/sdk/signNear-DGUQZ44s.js → esm/sdk/signNear-bcWIHxEY.js} +1 -1
  21. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  22. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  23. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  24. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  25. package/dist/esm/sdk/wallet-ui.css +1 -1
  26. package/dist/public/headers.manifest.json +1 -1
  27. package/dist/public/sdk/{host-CHQwi-Nm.js → host-BAeJh9rB.js} +1 -1
  28. package/dist/{esm/sdk/presignaturePool-CLHu7HaU.js → public/sdk/presignaturePool-Bkk6bLFB.js} +1 -1
  29. package/dist/public/sdk/routerAbNormalSigning-B35zb-P-.js +1 -0
  30. package/dist/public/sdk/runtime-auth-D7VqiZeg.js +1 -0
  31. package/dist/public/sdk/{runtime-device-link-DXjabXJb.js → runtime-device-link-BKc_MD5V.js} +1 -1
  32. package/dist/public/sdk/{runtime-ecdsa-tempo-DlKMIbyP.js → runtime-ecdsa-tempo-DC51NDrh.js} +1 -1
  33. package/dist/public/sdk/{runtime-email-otp-BBPghU2G.js → runtime-email-otp-C-wopKFf.js} +1 -1
  34. package/dist/public/sdk/{runtime-export-pw-xJL8o.js → runtime-export-BtGy8BKi.js} +1 -1
  35. package/dist/public/sdk/{runtime-near-B-vYxGjl.js → runtime-near-nq8pgRAl.js} +1 -1
  36. package/dist/public/sdk/{runtime-preferences-D-hY0RfC.js → runtime-preferences-778ZfMmT.js} +1 -1
  37. package/dist/public/sdk/{runtime-recovery-Vg1ND2nl.js → runtime-recovery-B-JsRiN0.js} +1 -1
  38. package/dist/public/sdk/{secp256k1-C-AETUpI.js → secp256k1-CYQS0rj-.js} +1 -1
  39. package/dist/public/sdk/{shared-6bpRPbcM.js → shared-B6BCLs8L.js} +1 -1
  40. package/dist/public/sdk/{signEvmFamily-M0trbeZe.js → signEvmFamily-ttVfV0qm.js} +1 -1
  41. package/dist/{esm/sdk/signNear-DGUQZ44s.js → public/sdk/signNear-bcWIHxEY.js} +1 -1
  42. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  43. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  44. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  45. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  46. package/dist/public/sdk/wallet-ui.css +1 -1
  47. package/dist/public/wallet-assets.manifest.json +34 -34
  48. package/dist/public/wallet-service/index.html +4 -4
  49. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +21 -3
  50. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/linkDeviceBadge.d.ts +18 -0
  51. package/package.json +1 -1
  52. package/dist/esm/sdk/routerAbNormalSigning-DVKFBYgV.js +0 -1
  53. package/dist/esm/sdk/runtime-auth-DtpRz88X.js +0 -1
  54. package/dist/public/sdk/routerAbNormalSigning-DVKFBYgV.js +0 -1
  55. package/dist/public/sdk/runtime-auth-DtpRz88X.js +0 -1
@@ -1 +1 @@
1
- import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-ChszYCC0.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-CAycHv-H.js";import{t as y}from"./presignatures-DZm0d6Wy.js";import{i as b,n as x,r as te,u as S}from"./trace-QLsbYdld.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpH-b3jx.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-DVKFBYgV.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
1
+ import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-ChszYCC0.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-CAycHv-H.js";import{t as y}from"./presignatures-DZm0d6Wy.js";import{i as b,n as x,r as te,u as S}from"./trace-QLsbYdld.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpH-b3jx.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-B35zb-P-.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
@@ -0,0 +1 @@
1
+ import{c as e,h as t,k as n}from"./chains-C_X_fNuS.js";import{A as r,D as i,j as a,k as o}from"./primitives-CqrjmIAH.js";import{i as s,r as c,t as l}from"./base64-DW79QA0h.js";import{n as u}from"./sessionPolicy-CBTZQe1n.js";import{d,h as f}from"./capabilityKinds-N8xo_IEh.js";import{$t as p,Qt as m,U as h,W as g,Z as _,ct as v,lt as y}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{t as b}from"./authenticatorOptions-C9aCKgeF.js";import{r as x,t as ee}from"./walletSessionAuthorizationStatus-BLyzJbU8.js";import{t as S}from"./authorizationAdmission-CGinGhXH.js";import{n as te}from"./walletSessionFailure-YuhraC3P.js";const C={enabled:!0,targetDepth:5,lowWatermark:4,maxRefillInFlight:1,refillAttemptTimeoutMs:3e4},ne={network:{chains:[{network:`near-testnet`,rpcUrl:`https://rpc.testnet.fastnear.com`,explorerUrl:`https://testnet.nearblocks.io`},{network:`tempo-testnet`,rpcUrl:`https://rpc.moderato.tempo.xyz`,explorerUrl:`https://explore.tempo.xyz`,chainId:42431},{network:`arc-testnet`,rpcUrl:`https://rpc.testnet.arc.io`,explorerUrl:`https://testnet.arcscan.app`,chainId:5042002},{network:`ethereum-sepolia`,rpcUrl:`https://ethereum-sepolia-rpc.publicnode.com`,explorerUrl:`https://sepolia.etherscan.io`,chainId:11155111}],relayer:{accountId:``,url:``,routes:{delegateAction:`/signed-delegate`}}},registration:{mode:`managed`,projectEnvironmentId:``,publishableKey:``,paymentMode:`disabled`,nearAccountProvisioning:{kind:`implicit_account`}},signing:{sessionDefaults:{ttlMs:u,remainingUses:3},emailOtp:{authPolicy:`session`},sessionPersistenceMode:`none`,sessionSeal:{mode:`none`},routerAb:{normalSigning:{mode:`disabled`}},routerAbEcdsaDerivation:{presignaturePool:C},thresholdEcdsa:{provisioningDefaults:{tempo:{enabled:!0,signingSession:{kind:`jwt`,ttlMs:u,remainingUses:3}},evm:{enabled:!0,signingSession:{kind:`jwt`,ttlMs:u,remainingUses:3}}}}},wallet:{mode:`iframe`,iframe:{origin:`https://wallet.example.localhost`,servicePath:`/wallet-service`,sdkBasePath:`/sdk`,walletHostVariant:`runtime`,rpIdOverride:`example.localhost`}},webauthn:{authenticatorOptions:{userVerification:b.Preferred,originPolicy:{single:void 0,all_subdomains:!0,multiple:void 0}}},ui:{appearance:{theme:{id:`default`,mode:`dark`,colors:{}},palette:`default`}}};async function re(e,t){let r=n(t,`ECDSA prepare response`);if(r.kind!==e.authorization.kind)throw Error(`ECDSA prepare authorization kind does not match the request`);let i=await h(e,r.signing);if(e.authorization.kind===`operation_step_up`){if(Object.keys(r).some(w))throw Error(`Invalid step-up prepare response`);return{kind:`operation_step_up`,signing:i}}if(Object.keys(r).some(ie))throw Error(`Invalid Wallet Session prepare response`);let a=n(r.session_status,`ECDSA prepare session status`),o=d(a.quotaId),s=f(e.authorization.wallet_session_id);if(!o.ok||!s.ok)throw Error(`Invalid prepare session identity`);let c=x(a,{walletSessionId:s.value,quotaId:o.value});if(!c||c.status!==`active`||c.authorization.walletId!==e.scope.wallet_id)throw Error(`ECDSA prepare did not return the admitted Wallet Session`);return{kind:`reusable_wallet_session`,signing:i,sessionStatus:c}}function w(e){return e!==`kind`&&e!==`signing`}function ie(e){return w(e)&&e!==`session_status`}var T=class extends Error{constructor(e){super(`Router A/B signing ${e.path} returned HTTP ${e.status}: ${e.message||e.code}`),this.name=`RouterAbSigningRequestError`,this.code=e.code,this.path=e.path,this.status=e.status}};function ae(e){let t=String(e.code||``).trim(),n=`Router A/B signing ${e.path} returned HTTP ${e.status}: ${e.message||t||`unknown admission failure`}`;if(e.authorizationDecision?.kind===`step_up_required`)return new S({kind:`exhausted`,source:`server_prepare`,detail:n},e.authorizationDecision);switch(t){case`wallet_budget_exhausted`:return new S({kind:`exhausted`,source:`server_prepare`,detail:n},e.authorizationDecision);case`wallet_budget_in_flight`:case`wallet_budget_reserved`:return new S({kind:`in_flight`,source:`server_prepare`,detail:n,retryAfterMs:150});default:return null}}function E(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function D(e,t,n){if(!Array.isArray(e))throw Error(`${t} must be a byte array`);let r=e.map(e=>Number(e));if(!r.every(e=>Number.isInteger(e)&&e>=0&&e<=255))throw Error(`${t} must contain bytes`);if(n!==void 0&&r.length!==n)throw Error(`${t} must contain ${n} bytes`);return r}function O(e,n){let r=t(e,n);if(c(r).length!==32)throw Error(`${n} must decode to 32 bytes`);return r}function k(e,n){let r=t(e,n);if(c(r).length===0)throw Error(`${n} must decode to non-empty bytes`);return r}function A(e,n){let r=t(e,n),i;try{i=l(r)}catch{i=c(r)}if(i.length!==32)throw Error(`${n} must decode to 32 bytes`);return s(i)}function j(e){return{bytes:[...D([...e],`digest bytes`,32)]}}function M(e,t){return s(Uint8Array.from(D(e.bytes,t)))}async function oe(t){return s(await Q(new TextEncoder().encode(e(t))))}function se(e){let n=t(e.message,`nep413.message`),r=t(e.recipient,`nep413.recipient`),i=c(A(e.nonce,`nep413.nonce`)),a=e.callbackUrl==null?void 0:t(e.callbackUrl,`callbackUrl`),o=[];return Z(o,2147484061),q(o,n),Y(o,i),q(o,r),a?(o.push(1),q(o,a)):o.push(0),s(Uint8Array.from(o))}async function ce(e){let n={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`near_transaction_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,transactions:e.transactions.map((e,n)=>({receiver_id:t(e.receiverId,`transactions[${n}].receiverId`),action_fingerprint:t(e.actionFingerprint,`transactions[${n}].actionFingerprint`)})),unsigned_transaction_borsh_b64u:k(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`)},signing_payload:{kind:`near_unsigned_transaction_borsh_v1`,unsigned_transaction_borsh_b64u:k(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`),expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:n,admissionMaterial:await P(n)}}async function le(e){let n=A(e.nonce,`nonce`),r=e.callbackUrl==null?void 0:t(e.callbackUrl,`callbackUrl`),i=se({message:e.message,recipient:e.recipient,nonce:n,...r?{callbackUrl:r}:{}}),a={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`nep413_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,recipient:t(e.recipient,`recipient`),message:t(e.message,`message`),nonce_b64u:n,...r?{callback_url:r}:{}},signing_payload:{kind:`nep413_message_v1`,canonical_message_b64u:i,expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:a,admissionMaterial:await P(a)}}async function ue(e){let n=k(e.delegate.canonicalDelegateBorshB64u,`canonicalDelegateBorshB64u`),r={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`near_delegate_action_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,delegate:{sender_id:t(e.delegate.senderId,`delegate.senderId`),receiver_id:t(e.delegate.receiverId,`delegate.receiverId`),public_key:t(e.delegate.publicKey,`delegate.publicKey`),nonce:t(e.delegate.nonce,`delegate.nonce`),max_block_height:t(e.delegate.maxBlockHeight,`delegate.maxBlockHeight`),action_fingerprint:t(e.delegate.actionFingerprint,`delegate.actionFingerprint`),canonical_delegate_borsh_b64u:n}},signing_payload:{kind:`near_delegate_action_v1`,canonical_delegate_borsh_b64u:n,expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:r,admissionMaterial:await P(r)}}function N(e){let n=I(e.scope,`scope`),r={scope:n,expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),prepare_binding:{server_round1_handle:t(e.prepareResponse.server_round1_handle,`server_round1_handle`),round1_binding_digest:L(e.prepareResponse.round1_binding_digest,`round1_binding_digest`),intent_digest:L(e.admissionMaterial.intentDigest,`intent_digest`),signing_payload_digest:L(e.admissionMaterial.signingPayloadDigest,`signing_payload_digest`)},protocol:{kind:`ed25519_two_party_frost_finalize_v1`,client_commitments:z(e.clientCommitments,`clientCommitments`),server_commitments:z(e.prepareResponse.server_commitments,`serverCommitments`),client_verifying_share_b64u:t(e.clientVerifyingShareB64u,`clientVerifyingShareB64u`),server_verifying_share_b64u:t(e.prepareResponse.server_verifying_share_b64u,`serverVerifyingShareB64u`),client_signature_share_b64u:t(e.clientSignatureShareB64u,`clientSignatureShareB64u`)}};if(n.authorization.kind===`reusable_wallet_session`&&e.prepareResponse.scope.authorization.kind===`reusable_wallet_session`)return{...r,scope:{...n,authorization:n.authorization},authorized_operation:V(e.prepareResponse.authorized_operation,`authorized_operation`)};if(n.authorization.kind===`operation_step_up`&&e.prepareResponse.scope.authorization.kind===`operation_step_up`)return{...r,scope:{...n,authorization:n.authorization},authorized_operation:H(e.prepareResponse.authorized_operation,`authorized_operation`)};throw Error(`Router A/B normal-signing authorization changed after prepare`)}async function P(e){let t=j(await Q(Se(e.intent))),n=j(await Q(Ce(e.signing_payload))),r=j(await Q(we(e.signing_payload))),i=c(Te(e.signing_payload));if(!De(r.bytes,i))throw Error(`Router A/B normal-signing expected signing digest drift`);return{intentDigest:t,signingPayloadDigest:n,admittedSigningDigest:r}}function F(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`${n} has invalid fields`)}function I(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);F(r,[`request_id`,`account_id`,`authorization`,`material_activation`,`signing_worker_id`],n);let i={request_id:t(r.request_id,`${n}.request_id`),account_id:t(r.account_id,`${n}.account_id`),authorization:p(r.authorization),material_activation:m(r.material_activation),signing_worker_id:t(r.signing_worker_id,`${n}.signing_worker_id`)};if(i.material_activation.signing_worker!==i.signing_worker_id)throw Error(`${n} material activation SigningWorker mismatch`);return i}function L(e,t){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`${t} must be an object`);return{bytes:D(n.bytes,`${t}.bytes`,32)}}function R(e,t){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`${t} must be an object`);let r=D(n.bytes,`${t}.bytes`);if(r.length===0)throw Error(`${t}.bytes must be non-empty`);return{bytes:r}}function z(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);return{hiding:t(r.hiding,`${n}.hiding`),binding:t(r.binding,`${n}.binding`)}}function B(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);return{server_id:t(r.server_id,`${n}.server_id`),key_epoch:t(r.key_epoch,`${n}.key_epoch`),recipient_encryption_key:t(r.recipient_encryption_key,`${n}.recipient_encryption_key`)}}function V(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);F(r,[`kind`,`authorized_operation_id`,`operation_id`,`capability_kind`,`operation_kind`,`lane_digest_b64u`,`intent_digest_b64u`,`display_digest_b64u`,`operation_fingerprint_digest`],n);let i=t(r.kind,`${n}.kind`);if(i!==`reusable_wallet_session_authorized_operation_v1`)throw Error(`${n}.kind is invalid`);let a=t(r.capability_kind,`${n}.capability_kind`);if(a!==`near_ed25519_mpc_signing`)throw Error(`${n}.capability_kind is invalid`);let o=t(r.operation_kind,`${n}.operation_kind`);if(o!==`near.sign_transaction`&&o!==`near.sign_delegate_action`&&o!==`near.sign_nep413_message`)throw Error(`${n}.operation_kind is invalid`);return{kind:i,authorized_operation_id:t(r.authorized_operation_id,`${n}.authorized_operation_id`),operation_id:t(r.operation_id,`${n}.operation_id`),capability_kind:a,operation_kind:o,lane_digest_b64u:O(r.lane_digest_b64u,`${n}.lane_digest_b64u`),intent_digest_b64u:O(r.intent_digest_b64u,`${n}.intent_digest_b64u`),display_digest_b64u:O(r.display_digest_b64u,`${n}.display_digest_b64u`),operation_fingerprint_digest:O(r.operation_fingerprint_digest,`${n}.operation_fingerprint_digest`)}}function H(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);if(F(r,[`kind`,`authorization_session_id`,`evidence_set_digest`,`authorized_operation_id`,`operation_id`,`capability_kind`,`operation_kind`,`lane_digest_b64u`,`intent_digest_b64u`,`display_digest_b64u`,`operation_fingerprint_digest`],n),t(r.kind,`${n}.kind`)!==`verified_step_up_authorized_operation_v1`)throw Error(`${n}.kind is invalid`);if(t(r.capability_kind,`${n}.capability_kind`)!==`near_ed25519_mpc_signing`)throw Error(`${n}.capability_kind is invalid`);let i=t(r.operation_kind,`${n}.operation_kind`);if(i!==`near.sign_transaction`&&i!==`near.sign_delegate_action`&&i!==`near.sign_nep413_message`)throw Error(`${n}.operation_kind is invalid`);return{kind:`verified_step_up_authorized_operation_v1`,authorization_session_id:t(r.authorization_session_id,`${n}.authorization_session_id`),evidence_set_digest:O(r.evidence_set_digest,`${n}.evidence_set_digest`),authorized_operation_id:t(r.authorized_operation_id,`${n}.authorized_operation_id`),operation_id:t(r.operation_id,`${n}.operation_id`),capability_kind:`near_ed25519_mpc_signing`,operation_kind:i,lane_digest_b64u:O(r.lane_digest_b64u,`${n}.lane_digest_b64u`),intent_digest_b64u:O(r.intent_digest_b64u,`${n}.intent_digest_b64u`),display_digest_b64u:O(r.display_digest_b64u,`${n}.display_digest_b64u`),operation_fingerprint_digest:O(r.operation_fingerprint_digest,`${n}.operation_fingerprint_digest`)}}function U(e){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`Router A/B normal-signing prepare response must be an object`);let r=t(n.signature_scheme,`signature_scheme`);if(r!==`ed25519_v1`)throw Error(`Unsupported Router A/B normal-signing signature scheme: ${r}`);let i=I(n.scope,`scope`),a={scope:i,signing_payload_digest:L(n.signing_payload_digest,`signing_payload_digest`),round1_binding_digest:L(n.round1_binding_digest,`round1_binding_digest`),signing_worker:B(n.signing_worker,`signing_worker`),server_round1_handle:t(n.server_round1_handle,`server_round1_handle`),server_commitments:z(n.server_commitments,`server_commitments`),server_verifying_share_b64u:t(n.server_verifying_share_b64u,`server_verifying_share_b64u`),signature_scheme:`ed25519_v1`,prepared_at_ms:E(n.prepared_at_ms,`prepared_at_ms`),expires_at_ms:E(n.expires_at_ms,`expires_at_ms`)};switch(i.authorization.kind){case`reusable_wallet_session`:return F(n,[`scope`,`signing_payload_digest`,`round1_binding_digest`,`signing_worker`,`server_round1_handle`,`server_commitments`,`server_verifying_share_b64u`,`signature_scheme`,`prepared_at_ms`,`expires_at_ms`,`authorized_operation`],`Router A/B reusable Wallet Session prepare response`),{...a,scope:{...i,authorization:i.authorization},authorized_operation:V(n.authorized_operation,`authorized_operation`)};case`operation_step_up`:return F(n,[`scope`,`signing_payload_digest`,`round1_binding_digest`,`signing_worker`,`server_round1_handle`,`server_commitments`,`server_verifying_share_b64u`,`signature_scheme`,`prepared_at_ms`,`expires_at_ms`,`authorized_operation`],`Router A/B operation step-up prepare response`),{...a,scope:{...i,authorization:i.authorization},authorized_operation:H(n.authorized_operation,`authorized_operation`)}}}function de(e){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`Router A/B normal-signing response must be an object`);F(n,[`scope`,`signing_payload_digest`,`signing_worker`,`signature_scheme`,`signature`,`signed_at_ms`],`Router A/B normal-signing response`);let r=t(n.signature_scheme,`signature_scheme`);if(r!==`ed25519_v1`)throw Error(`Unsupported Router A/B normal-signing signature scheme: ${r}`);return{scope:I(n.scope,`scope`),signing_payload_digest:L(n.signing_payload_digest,`signing_payload_digest`),signing_worker:B(n.signing_worker,`signing_worker`),signature_scheme:`ed25519_v1`,signature:R(n.signature,`signature`),signed_at_ms:E(n.signed_at_ms,`signed_at_ms`)}}function fe(e){let t=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null;return i({...t?{headers:o(t)}:{},body:e.body})}function pe(e){if(!e.trim())return null;try{let t=JSON.parse(e),n=t&&typeof t==`object`?t:null;if(!n)return null;let r=String(n.code||``).trim(),i=String(n.message||``).trim();if(!r)return null;let a=n.authorization_decision===void 0?void 0:me(n.authorization_decision);return{code:r,message:i,...a?{authorizationDecision:a}:{}}}catch{return null}}function me(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Router A/B owner-operation authorization decision is invalid`);let t=e,n=t.kind;if(n===`step_up_required`){W(t,[`kind`,`reason`,`step_up`],`owner-operation step-up decision`);let e=t.reason;if(e!==`wallet_session_missing`&&e!==`wallet_session_expired`&&e!==`wallet_session_exhausted`&&e!==`wallet_session_ended`&&e!==`wallet_session_superseded`)throw Error(`owner-operation step-up decision reason is invalid`);let r=t.step_up;return r&&typeof r==`object`&&!Array.isArray(r)&&`operation_digests`in r?{kind:n,reason:e,step_up:_(r)}:{kind:n,reason:e,step_up:he(r)}}if(n===`denied`){if(W(t,[`kind`,`denial`],`owner-operation denial decision`),!t.denial||typeof t.denial!=`object`||Array.isArray(t.denial))throw Error(`owner-operation denial is invalid`);let e=t.denial;W(e,[`code`,`message`],`owner-operation denial`);let r=e.code;if(r!==`invalid_identity`&&r!==`invalid_authority`&&r!==`invalid_operation`&&r!==`inactive_material`&&r!==`replayed_step_up`&&r!==`authorization_unavailable`)throw Error(`owner-operation denial code is invalid`);if(typeof e.message!=`string`||e.message.trim()!==e.message)throw Error(`owner-operation denial message is invalid`);return{kind:n,denial:{code:r,message:e.message}}}if(n===`authorized`){if(W(t,[`kind`,`operation`,`source`],`owner-operation decision`),!t.operation||typeof t.operation!=`object`||Array.isArray(t.operation))throw Error(`owner-operation authorized operation is invalid`);let e=t.operation;if(W(e,[`kind`,`operation_id`,`authorized_operation_id`,`operation_fingerprint_digest`],`owner-operation authorized operation`),e.kind!==`authorized_operation`||typeof e.operation_id!=`string`||typeof e.authorized_operation_id!=`string`||typeof e.operation_fingerprint_digest!=`string`)throw Error(`owner-operation authorized operation is invalid`);if(!t.source||typeof t.source!=`object`||Array.isArray(t.source))throw Error(`owner-operation authorized source is invalid`);let r=t.source;if(W(r,[`kind`,`wallet_session_id`,`quota_id`],`owner-operation authorized source`),r.kind!==`reusable_wallet_session`||typeof r.wallet_session_id!=`string`||typeof r.quota_id!=`string`)throw Error(`owner-operation authorized source is invalid`);return{kind:n,operation:{kind:`authorized_operation`,operation_id:e.operation_id,authorized_operation_id:e.authorized_operation_id,operation_fingerprint_digest:e.operation_fingerprint_digest},source:{kind:`reusable_wallet_session`,wallet_session_id:r.wallet_session_id,quota_id:r.quota_id}}}throw Error(`owner-operation authorization decision kind is invalid`)}function he(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Ed25519 operation step-up preparation is invalid`);let t=e;W(t,[`wallet_id`,`operation_kind`,`operation_id`,`request_id`,`account_id`,`material_activation`,`signing_worker_id`,`near_account_id`,`signer_slot`,`participant_ids`,`expires_at_ms`],`Ed25519 owner-operation step-up preparation`);let n=t.operation_kind;if(n!==`near.sign_transaction`&&n!==`near.sign_delegate_action`&&n!==`near.sign_nep413_message`)throw Error(`Ed25519 operation step-up kind is invalid`);if(typeof t.wallet_id!=`string`||typeof t.operation_id!=`string`||typeof t.request_id!=`string`||typeof t.account_id!=`string`||typeof t.signing_worker_id!=`string`||typeof t.near_account_id!=`string`||!Number.isSafeInteger(t.signer_slot)||!Number.isSafeInteger(t.expires_at_ms)||!Array.isArray(t.participant_ids)||t.participant_ids.length!==2||!t.participant_ids.every(e=>Number.isSafeInteger(e)&&Number(e)>0))throw Error(`Ed25519 operation step-up preparation fields are invalid`);let[r,i]=t.participant_ids,a=t.signer_slot,o=t.expires_at_ms;if(typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||typeof o!=`number`)throw Error(`Ed25519 operation step-up participants are invalid`);return{wallet_id:t.wallet_id,operation_kind:n,operation_id:t.operation_id,request_id:t.request_id,account_id:t.account_id,material_activation:m(t.material_activation),signing_worker_id:t.signing_worker_id,near_account_id:t.near_account_id,signer_slot:a,participant_ids:[r,i],expires_at_ms:o}}function W(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} contains unsupported field ${t}`);for(let r of t)if(!Object.hasOwn(e,r))throw Error(`${n} is missing ${r}`)}function ge(e){let t=pe(e.bodyText);return t?ae({code:t.code,message:t.message,path:e.path,status:e.status,authorizationDecision:t.authorizationDecision})||te({code:t.code,message:`Router A/B signing ${e.path} returned HTTP ${e.status}: ${t.message}`})||new T({code:t.code,message:t.message,path:e.path,status:e.status}):Error(`Router A/B signing ${e.path} returned HTTP ${e.status}${e.bodyText?`: ${e.bodyText}`:``}`)}async function G(e){if(typeof fetch!=`function`)throw Error(`fetch is not available for Router A/B normal-signing request`);let n=a(t(e.relayServerUrl,`relayServerUrl`)),i=await r(new Request(`${n}${e.path}`,{...fe({credential:e.credential,body:e.body}),signal:e.signal}));try{e.onServerTiming?.(i.headers.get(`Server-Timing`))}catch{}if(!i.ok){let t=await i.text().catch(()=>``),n=ge({path:e.path,status:i.status,bodyText:t});throw e.credential.kind===`wallet_session_opaque`&&n instanceof S&&n.failure.kind===`exhausted`&&ee.forgetCredential(e.credential.walletSessionToken),n}return e.parse(await i.json())}function _e(e,t){let r=n(t,`Ed25519 prepare response`);if(r.kind!==e.scope.authorization.kind)throw Error(`Ed25519 prepare authorization kind does not match the request`);let i=U(r.signing);if(e.scope.authorization.kind===`operation_step_up`)return W(r,[`kind`,`signing`],`Ed25519 step-up prepare response`),{kind:`operation_step_up`,signing:i};W(r,[`kind`,`signing`,`session_status`],`Ed25519 session prepare response`);let a=n(r.session_status,`Ed25519 prepare session status`),o=f(e.scope.authorization.wallet_session_id),s=d(a.quotaId);if(!o.ok||!s.ok)throw Error(`Invalid Ed25519 prepare session identity`);let c=x(a,{walletSessionId:o.value,quotaId:s.value});if(!c||c.status!==`active`)throw Error(`Ed25519 prepare did not return an active Wallet Session`);return{kind:`reusable_wallet_session`,signing:i,sessionStatus:c}}async function ve(e){return G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ed25519/sign/prepare`,credential:e.credential,body:e.request,parse:_e.bind(null,e.request)})}async function ye(e){return await y(e.request),G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ecdsa-derivation/sign/prepare`,onServerTiming:e.onServerTiming,credential:e.credential,body:e.request,parse:re.bind(null,e.request)})}async function be(e){return G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ed25519/sign`,credential:e.credential,body:e.request,parse:de})}async function xe(e){return await v(e.request),G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ecdsa-derivation/sign`,onServerTiming:e.onServerTiming,credential:e.credential,body:e.request,parse:t=>g(e.request,t)})}function Se(e){let t=[];switch(J(t,$(`router-ab-protocol/ed25519-normal-signing/intent/v2`)),e.kind){case`near_transaction_v1`:J(t,$(`near_transaction_v1`)),K(t,e),X(t,e.transactions.length);for(let n of e.transactions)J(t,$(n.receiver_id)),J(t,$(n.action_fingerprint));return J(t,$(e.unsigned_transaction_borsh_b64u)),Uint8Array.from(t);case`nep413_v1`:return J(t,$(`nep413_v1`)),K(t,e),J(t,$(e.recipient)),J(t,$(e.message)),J(t,$(e.nonce_b64u)),Ee(t,e.callback_url),Uint8Array.from(t);case`near_delegate_action_v1`:return J(t,$(`near_delegate_action_v1`)),K(t,e),J(t,$(e.delegate.sender_id)),J(t,$(e.delegate.receiver_id)),J(t,$(e.delegate.public_key)),J(t,$(e.delegate.nonce)),J(t,$(e.delegate.max_block_height)),J(t,$(e.delegate.action_fingerprint)),J(t,$(e.delegate.canonical_delegate_borsh_b64u)),Uint8Array.from(t)}}function Ce(e){let t=[];switch(J(t,$(`router-ab-protocol/ed25519-normal-signing/payload/v2`)),e.kind){case`near_unsigned_transaction_borsh_v1`:return J(t,$(`near_unsigned_transaction_borsh_v1`)),J(t,$(e.unsigned_transaction_borsh_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t);case`nep413_message_v1`:return J(t,$(`nep413_message_v1`)),J(t,$(e.canonical_message_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t);case`near_delegate_action_v1`:return J(t,$(`near_delegate_action_v1`)),J(t,$(e.canonical_delegate_borsh_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t)}}function we(e){switch(e.kind){case`near_unsigned_transaction_borsh_v1`:return c(e.unsigned_transaction_borsh_b64u);case`nep413_message_v1`:return c(e.canonical_message_b64u);case`near_delegate_action_v1`:return c(e.canonical_delegate_borsh_b64u)}}function Te(e){switch(e.kind){case`near_unsigned_transaction_borsh_v1`:case`nep413_message_v1`:case`near_delegate_action_v1`:return e.expected_signing_digest_b64u}}function K(e,t){J(e,$(t.operation_id)),J(e,$(t.operation_fingerprint)),J(e,$(t.near_account_id)),J(e,$(t.near_network_id))}function Ee(e,t){t?(e.push(1),J(e,$(t))):e.push(0)}function q(e,t){let n=$(t);Z(e,n.length),Y(e,n)}function J(e,t){X(e,t.length),Y(e,t)}function Y(e,t){for(let n of t)e.push(n)}function X(e,t){e.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255)}function Z(e,t){e.push(t&255,t>>>8&255,t>>>16&255,t>>>24&255)}async function Q(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`Web Crypto SHA-256 is unavailable for Router A/B normal signing`);let n=new Uint8Array(e.length);return n.set(e),new Uint8Array(await t.digest(`SHA-256`,n.buffer))}function $(e){return new TextEncoder().encode(e)}function De(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{N as a,ye as c,oe as d,C as f,le as i,ve as l,ue as n,xe as o,ne as p,ce as r,be as s,T as t,M as u};
@@ -0,0 +1 @@
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"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{c as r,l as i,o as a,r as o,s}from"./messages-DgJlG9NU.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-B6BCLs8L.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-CQxxUt5s.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import{a as m}from"./signerDomain-DqLCvI-D.js";import"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{t as Ce}from"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import{a as we,n as Te}from"./registrationIds-ByuReLUc.js";import"./passkey-custody-Cd_yyoRa.js";import{c as Ee,i as De,s as Oe}from"./sdkSentEvents-Dl8fOL50.js";import"./walletCustodyEcdsaContinuity-D-gYxv6e.js";import"./keccak-BArcwgbj.js";import{g as ke,p as Ae}from"./wallet-recovery-LMtGiEL3.js";import"./nearEd25519YaoMaterialActivation-DMGPKrn8.js";import{t as je}from"./walletSessionAuthorizationStatus-BLyzJbU8.js";import"./signNear-bcWIHxEY.js";import{a as Me,i as Ne}from"./adapters-CGvNLOfZ.js";import{t as Pe}from"./surface-measurement-reporter-DvVHPu_O.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-C8JOKu_4.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 r=o(J());if(!r)return null;let i={kind:`hosted_auth_menu_external_auth_request_v1`,authMenuSessionId:this.identity.authMenuSessionId,externalAuthRequestId:r,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:i,authTarget:n},this.updateElement(),this.sendToParent({type:`AUTH_MENU_EXTERNAL_AUTH_REQUEST`,requestId:this.identity.requestId,payload:i}),i}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=o(J());if(!n)return null;let r={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:r,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:r}),r}requestRecoveredGoogleSignIn(e,t){if(!this.request.enabledExternalProviders.includes(e))return null;let n=o(J());if(!n)return null;let r={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:r,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:r}),r}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=s({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-EHY_b7Z-.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=i(n.payload);if(!r)throw Error(`Hosted auth-menu open request is invalid`);let a=await t.open({request:r,requestId:n.requestId});(a.kind===`authenticated`||a.kind===`registered`||a.kind===`account_synced`)&&await e.publishCurrentSession(),!e.respondIfCancelled(n.requestId)&&p(e,n.requestId,a)},PM_CANCEL_AUTH_MENU:async n=>{let r=a(n.payload);if(!r)throw Error(`Hosted auth-menu cancellation is invalid`);let i=t.cancel(r);p(e,n.requestId,{cancelled:i})},PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH:async n=>{let i=r(n.payload);if(!i)throw Error(`Hosted auth-menu external-auth resolution is invalid`);let a=t.resolveExternalAuth(i);p(e,n.requestId,{accepted:a})}}}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};
@@ -1 +1 @@
1
- import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{a as e,i as t}from"./messages-DgJlG9NU.js";import{a as n,n as r,r as i,t as a}from"./shared-6bpRPbcM.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import"./signerDomain-DqLCvI-D.js";import{A as o,N as s,j as c,ot as l}from"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import"./registrationIds-ByuReLUc.js";import"./passkey-custody-Cd_yyoRa.js";import{c as u}from"./sdkSentEvents-Dl8fOL50.js";import"./walletCustodyEcdsaContinuity-D-gYxv6e.js";import"./keccak-BArcwgbj.js";import"./wallet-recovery-LMtGiEL3.js";import"./nearEd25519YaoMaterialActivation-DMGPKrn8.js";import"./signNear-DGUQZ44s.js";import"./jsxRuntime.module-C8JOKu_4.js";function d(e,t,n,r){return n?(e.get(n)?.reject(Error(`A newer Email OTP method selection is required`)),new Promise((i,a)=>{let o=setTimeout(()=>f(e,n,Error(`Email OTP method selection timed out`)),9e5);e.set(n,{choices:r,resolve:e=>{clearTimeout(o),i(e)},reject:e=>{clearTimeout(o),a(e instanceof Error?e:Error(String(e)))}}),t.postProgress(n,{event:`wallet_device_link_email_otp_base_factor_selection_required_v1`,choices:r})})):Promise.reject(Error(`Device-link request id is required`))}function f(e,t,n){if(!t)return;let r=e.get(t);r&&(e.delete(t),r.reject(n))}function p(e,t){let n=e.get(t.scanRequestId);if(!n)throw Error(`Email OTP method selection is unavailable`);switch(t.action.kind){case`cancel`:e.delete(t.scanRequestId),n.reject(Error(`Device linking was cancelled`));return;case`select`:{let r=t.action.baseWalletAuthMethodId;if(!n.choices.some(e=>e.baseWalletAuthMethodId===r))throw Error(`The selected Email OTP method is unavailable for this linked device`);e.delete(t.scanRequestId),n.resolve(r);return}default:throw t.action,Error(`Unsupported Email OTP method selection action`)}}function m(e){switch(e.activation.kind){case`linked_device_target_passkey_activation_v1`:return{event:`wallet_device_link_target_factor_activation_v1`,activationId:e.activationId,activation:{kind:e.activation.kind}};case`linked_device_target_email_otp_activation_v1`:return{event:`wallet_device_link_target_factor_activation_v1`,activationId:e.activationId,activation:{kind:e.activation.kind,state:e.activation.state}};default:throw e.activation,Error(`Unsupported linked-device target-factor activation`)}}async function h(e){switch(e.action.kind){case`create_passkey`:if(e.active.activation.kind!==`linked_device_target_passkey_activation_v1`)throw Error(`linked-device Passkey activation is unavailable`);await e.active.activation.createPasskey();return;case`send_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.sendCode();return;case`resend_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.resendCode();return;case`submit_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.submitCode(e.action.otpCode);return;default:throw e.action,Error(`Unsupported linked-device target-factor action`)}}function g(e,t,n,r,i){e.current={activationId:r,activation:i},t.postProgress(n,m(e.current))}function _(e,t,n,r){t.postProgress(n,r);let i=u(r);(i.kind===`active`||i.kind===`failed`||i.kind===`invalid_active`||i.kind===`cancelled`)&&(e.current=null)}function v(n){let u={current:null},m=new Map;return{PM_START_DEVICE2_LINKING_FLOW:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_START_DEVICE2_LINKING_FLOW requires a payload`);let{ui:a,cameraId:o,options:s}=i,c;if(i.targetFactor.kind===`email_otp`){if(typeof i.targetEmail!=`string`)throw Error(`PM_START_DEVICE2_LINKING_FLOW requires targetEmail for Email OTP`);c={targetFactor:i.targetFactor,targetEmail:i.targetEmail}}else c={targetFactor:i.targetFactor};if(n.respondIfCancelled(e.requestId))return;let l=String(e.requestId||``).trim();if(!l)throw Error(`Device-link target-factor activation id is required`);let d=await t.devices.startLinking({...c,...a?{ui:a}:{},...o?{cameraId:o}:{},options:{...s||{},onEvent:_.bind(null,u,n,e.requestId),onTargetFactorRequired:g.bind(null,u,n,e.requestId,l)}});n.respondIfCancelled(e.requestId)||r(n,e.requestId,d)},PM_DEVICE_LINK_TARGET_FACTOR_ACTION:async t=>{let r=e(t.payload);if(!r)throw Error(`PM_DEVICE_LINK_TARGET_FACTOR_ACTION payload is invalid`);let i=u.current;if(!i||i.activationId!==r.activationId)throw Error(`linked-device target-factor activation is unavailable`);await h({active:i,action:r.action}),a(n,t.requestId)},PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION:async e=>{let r=t(e.payload);if(!r)throw Error(`Email OTP method selection payload is invalid`);p(m,r),a(n,e.requestId)},PM_CANCEL_DEVICE_LINKING:async e=>{let t=n.getWalletRuntime();if(!n.respondIfCancelled(e.requestId)){await t.devices.cancelLinking(),u.current=null;for(let e of[...m.keys()])f(m,e,Error(`Device linking was cancelled`));n.respondIfCancelled(e.requestId)||a(n,e.requestId)}},PM_SCAN_AND_LINK_DEVICE:async e=>{let t=n.getWalletRuntime(),{qrData:a,options:o}=e.payload;if(!n.respondIfCancelled(e.requestId))try{let s=await t.devices.approveLinking(l(a),{...i(n,e.requestId,o||{}),onEmailOtpBaseFactorRequired:t=>d(m,n,e.requestId,t)});if(n.respondIfCancelled(e.requestId))return;r(n,e.requestId,s)}finally{f(m,e.requestId,Error(`Device-link request ended before Email OTP method selection completed`))}},PM_HAS_PASSKEY:async e=>{let t=n.getWalletRuntime(),{walletId:i}=e.payload,a=await t.auth.hasPasskey(i);r(n,e.requestId,a)},PM_LIST_LINKED_DEVICES:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_LIST_LINKED_DEVICES requires a payload`);let a=o({kind:`linked_device_list_request_v1`,walletId:i.walletId,limit:i.limit,cursor:i.cursor}),s=await t.devices.list({walletId:String(a.walletId),limit:a.limit,cursor:a.cursor});r(n,e.requestId,c(s))},PM_REVOKE_LINKED_DEVICE:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_REVOKE_LINKED_DEVICE requires a payload`);if(n.respondIfCancelled(e.requestId))return;let a=await t.devices.remove({walletId:i.walletId,walletAuthMethodId:i.walletAuthMethodId});n.respondIfCancelled(e.requestId)||r(n,e.requestId,s(a))}}}async function y(e){await n(e,v)}export{y as handleWalletHostRuntimeRequest};
1
+ import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{a as e,i as t}from"./messages-DgJlG9NU.js";import{a as n,n as r,r as i,t as a}from"./shared-B6BCLs8L.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import"./signerDomain-DqLCvI-D.js";import{A as o,N as s,j as c,ot as l}from"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import"./registrationIds-ByuReLUc.js";import"./passkey-custody-Cd_yyoRa.js";import{c as u}from"./sdkSentEvents-Dl8fOL50.js";import"./walletCustodyEcdsaContinuity-D-gYxv6e.js";import"./keccak-BArcwgbj.js";import"./wallet-recovery-LMtGiEL3.js";import"./nearEd25519YaoMaterialActivation-DMGPKrn8.js";import"./signNear-bcWIHxEY.js";import"./jsxRuntime.module-C8JOKu_4.js";function d(e,t,n,r){return n?(e.get(n)?.reject(Error(`A newer Email OTP method selection is required`)),new Promise((i,a)=>{let o=setTimeout(()=>f(e,n,Error(`Email OTP method selection timed out`)),9e5);e.set(n,{choices:r,resolve:e=>{clearTimeout(o),i(e)},reject:e=>{clearTimeout(o),a(e instanceof Error?e:Error(String(e)))}}),t.postProgress(n,{event:`wallet_device_link_email_otp_base_factor_selection_required_v1`,choices:r})})):Promise.reject(Error(`Device-link request id is required`))}function f(e,t,n){if(!t)return;let r=e.get(t);r&&(e.delete(t),r.reject(n))}function p(e,t){let n=e.get(t.scanRequestId);if(!n)throw Error(`Email OTP method selection is unavailable`);switch(t.action.kind){case`cancel`:e.delete(t.scanRequestId),n.reject(Error(`Device linking was cancelled`));return;case`select`:{let r=t.action.baseWalletAuthMethodId;if(!n.choices.some(e=>e.baseWalletAuthMethodId===r))throw Error(`The selected Email OTP method is unavailable for this linked device`);e.delete(t.scanRequestId),n.resolve(r);return}default:throw t.action,Error(`Unsupported Email OTP method selection action`)}}function m(e){switch(e.activation.kind){case`linked_device_target_passkey_activation_v1`:return{event:`wallet_device_link_target_factor_activation_v1`,activationId:e.activationId,activation:{kind:e.activation.kind}};case`linked_device_target_email_otp_activation_v1`:return{event:`wallet_device_link_target_factor_activation_v1`,activationId:e.activationId,activation:{kind:e.activation.kind,state:e.activation.state}};default:throw e.activation,Error(`Unsupported linked-device target-factor activation`)}}async function h(e){switch(e.action.kind){case`create_passkey`:if(e.active.activation.kind!==`linked_device_target_passkey_activation_v1`)throw Error(`linked-device Passkey activation is unavailable`);await e.active.activation.createPasskey();return;case`send_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.sendCode();return;case`resend_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.resendCode();return;case`submit_email_otp`:if(e.active.activation.kind!==`linked_device_target_email_otp_activation_v1`)throw Error(`linked-device Email OTP activation is unavailable`);await e.active.activation.submitCode(e.action.otpCode);return;default:throw e.action,Error(`Unsupported linked-device target-factor action`)}}function g(e,t,n,r,i){e.current={activationId:r,activation:i},t.postProgress(n,m(e.current))}function _(e,t,n,r){t.postProgress(n,r);let i=u(r);(i.kind===`active`||i.kind===`failed`||i.kind===`invalid_active`||i.kind===`cancelled`)&&(e.current=null)}function v(n){let u={current:null},m=new Map;return{PM_START_DEVICE2_LINKING_FLOW:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_START_DEVICE2_LINKING_FLOW requires a payload`);let{ui:a,cameraId:o,options:s}=i,c;if(i.targetFactor.kind===`email_otp`){if(typeof i.targetEmail!=`string`)throw Error(`PM_START_DEVICE2_LINKING_FLOW requires targetEmail for Email OTP`);c={targetFactor:i.targetFactor,targetEmail:i.targetEmail}}else c={targetFactor:i.targetFactor};if(n.respondIfCancelled(e.requestId))return;let l=String(e.requestId||``).trim();if(!l)throw Error(`Device-link target-factor activation id is required`);let d=await t.devices.startLinking({...c,...a?{ui:a}:{},...o?{cameraId:o}:{},options:{...s||{},onEvent:_.bind(null,u,n,e.requestId),onTargetFactorRequired:g.bind(null,u,n,e.requestId,l)}});n.respondIfCancelled(e.requestId)||r(n,e.requestId,d)},PM_DEVICE_LINK_TARGET_FACTOR_ACTION:async t=>{let r=e(t.payload);if(!r)throw Error(`PM_DEVICE_LINK_TARGET_FACTOR_ACTION payload is invalid`);let i=u.current;if(!i||i.activationId!==r.activationId)throw Error(`linked-device target-factor activation is unavailable`);await h({active:i,action:r.action}),a(n,t.requestId)},PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION:async e=>{let r=t(e.payload);if(!r)throw Error(`Email OTP method selection payload is invalid`);p(m,r),a(n,e.requestId)},PM_CANCEL_DEVICE_LINKING:async e=>{let t=n.getWalletRuntime();if(!n.respondIfCancelled(e.requestId)){await t.devices.cancelLinking(),u.current=null;for(let e of[...m.keys()])f(m,e,Error(`Device linking was cancelled`));n.respondIfCancelled(e.requestId)||a(n,e.requestId)}},PM_SCAN_AND_LINK_DEVICE:async e=>{let t=n.getWalletRuntime(),{qrData:a,options:o}=e.payload;if(!n.respondIfCancelled(e.requestId))try{let s=await t.devices.approveLinking(l(a),{...i(n,e.requestId,o||{}),onEmailOtpBaseFactorRequired:t=>d(m,n,e.requestId,t)});if(n.respondIfCancelled(e.requestId))return;r(n,e.requestId,s)}finally{f(m,e.requestId,Error(`Device-link request ended before Email OTP method selection completed`))}},PM_HAS_PASSKEY:async e=>{let t=n.getWalletRuntime(),{walletId:i}=e.payload,a=await t.auth.hasPasskey(i);r(n,e.requestId,a)},PM_LIST_LINKED_DEVICES:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_LIST_LINKED_DEVICES requires a payload`);let a=o({kind:`linked_device_list_request_v1`,walletId:i.walletId,limit:i.limit,cursor:i.cursor}),s=await t.devices.list({walletId:String(a.walletId),limit:a.limit,cursor:a.cursor});r(n,e.requestId,c(s))},PM_REVOKE_LINKED_DEVICE:async e=>{let t=n.getWalletRuntime(),i=e.payload;if(!i)throw Error(`PM_REVOKE_LINKED_DEVICE requires a payload`);if(n.respondIfCancelled(e.requestId))return;let a=await t.devices.remove({walletId:i.walletId,walletAuthMethodId:i.walletAuthMethodId});n.respondIfCancelled(e.requestId)||r(n,e.requestId,s(a))}}}async function y(e){await n(e,v)}export{y as handleWalletHostRuntimeRequest};