@seams/wallet 0.28.0 → 0.30.0

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 (425) hide show
  1. package/README.md +29 -4
  2. package/dist/.build-inputs.sha256 +1 -1
  3. package/dist/esm/SeamsWeb/SeamsWeb.js +2 -0
  4. package/dist/esm/SeamsWeb/publicApi/createPublicApi.js +11 -0
  5. package/dist/esm/SeamsWeb/publicApi/near.js +3 -0
  6. package/dist/esm/SeamsWeb/publicApi/ownerNearOperation.js +175 -0
  7. package/dist/esm/SeamsWeb/walletIframe/client/inboundMessages.js +9 -0
  8. package/dist/esm/SeamsWeb/walletIframe/client/nearCommands.js +4 -0
  9. package/dist/esm/SeamsWeb/walletIframe/client/ownerNearOperation.js +67 -0
  10. package/dist/esm/SeamsWeb/walletIframe/client/progress/on-events-progress-bus.js +27 -17
  11. package/dist/esm/SeamsWeb/walletIframe/client/router.js +60 -7
  12. package/dist/esm/SeamsWeb/walletIframe/client/sessionCommands.js +4 -0
  13. package/dist/esm/SeamsWeb/walletIframe/coordinator.js +18 -0
  14. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +88 -47
  15. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.js +67 -0
  16. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.js +13 -0
  17. package/dist/esm/SeamsWeb/walletIframe/host/walletMutationGuard.js +6 -0
  18. package/dist/esm/SeamsWeb/walletIframe/shared/exactSessionState.js +15 -1
  19. package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +20 -6
  20. package/dist/esm/SeamsWeb/walletIframe/shared/ownerNearOperation.js +152 -0
  21. package/dist/esm/SeamsWeb/walletIframe/shared/walletAlternatives.js +109 -0
  22. package/dist/esm/core/accountData/near/accountProjection.js +1 -1
  23. package/dist/esm/core/config/configBuilder.js +1 -1
  24. package/dist/esm/core/config/defaultConfigs.js +9 -2
  25. package/dist/esm/core/indexedDB/seamsWalletDB/repositories.js +4 -3
  26. package/dist/esm/core/rpcClients/relayer/walletRegistration.js +1 -1
  27. package/dist/esm/core/signingEngine/flows/registration/accountLifecycle.js +1 -1
  28. package/dist/esm/core/signingEngine/flows/shared/signingConfirmation.js +1 -1
  29. package/dist/esm/core/signingEngine/flows/signEvmFamily/signEvmFamily.js +1 -1
  30. package/dist/esm/core/signingEngine/flows/signEvmFamily/signingFlow.js +1 -1
  31. package/dist/esm/core/signingEngine/flows/signNear/shared/ed25519YaoNormalSigning.js +2 -2
  32. package/dist/esm/core/signingEngine/flows/signNear/signDelegate.js +2 -2
  33. package/dist/esm/core/signingEngine/flows/signNear/signNear.js +3 -8
  34. package/dist/esm/core/signingEngine/flows/signNear/signNep413.js +1 -1
  35. package/dist/esm/core/signingEngine/flows/signNear/signTransactions.js +3 -4
  36. package/dist/esm/core/signingEngine/session/identity/exactSigningLaneIdentity.js +1 -1
  37. package/dist/esm/core/ui/messages.js +3 -1
  38. package/dist/esm/core/ui/walletIcon.js +10 -0
  39. package/dist/esm/externalEvm/boundary.js +4 -2
  40. package/dist/esm/index.js +3 -2
  41. package/dist/esm/react/boundWallet.js +24 -0
  42. package/dist/esm/react/components/HostedSeamsAuthMenu/shell.js +26 -6
  43. package/dist/esm/react/components/HostedSeamsAuthMenu/walletAlternatives.js +178 -0
  44. package/dist/esm/react/context/useLoginStateRefresher.js +1 -0
  45. package/dist/esm/react/hooks/useAccountInput.js +1 -1
  46. package/dist/esm/react/hooks/useOwnerNearOperation.js +10 -0
  47. package/dist/esm/react/index.js +3 -3
  48. package/dist/esm/react/styles/styles.css +0 -183
  49. package/dist/esm/react/styles.css +0 -1
  50. package/dist/esm/sdk/{ConfirmationDrawer-MJoE0AAo.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
  51. package/dist/esm/sdk/NonceCoordinator-C1lw03Ce.js +1 -0
  52. package/dist/esm/sdk/{SeamsWordmark-DwvPx2UA.js → SeamsWordmark-CeEi2RlU.js} +1 -1
  53. package/dist/esm/sdk/accountLifecycle-B5a9SCM7.js +1 -0
  54. package/dist/{public/sdk/activeWalletSession-BJ4B-nJo.js → esm/sdk/activeWalletSession-HAOgRKzn.js} +1 -1
  55. package/dist/{public/sdk/adapters-C-g_hkkZ.js → esm/sdk/adapters-BY1wGpm5.js} +1 -1
  56. package/dist/esm/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
  57. package/dist/esm/sdk/authorization-D_NueqAv.js +1 -0
  58. package/dist/esm/sdk/clientSessionPersistenceState-B3gU3515.js +1 -0
  59. package/dist/esm/sdk/{collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js → collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js} +1 -1
  60. package/dist/esm/sdk/{commitQueue-CYruPlkm.js → commitQueue-CbyuhEW9.js} +1 -1
  61. package/dist/esm/sdk/confirm-ui-DWFcGTsT.js +2 -0
  62. package/dist/{public/sdk/device-linking-DiCNt3iA.js → esm/sdk/device-linking-BL2aDEUF.js} +1 -1
  63. package/dist/esm/sdk/{deviceLinkApproval-x3WkiYrd.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
  64. package/dist/{public/sdk/digestEncoding-CqNXPZY9.js → esm/sdk/digestEncoding-Rx8Vjy4J.js} +1 -1
  65. package/dist/esm/sdk/{display-D0EPmU4w.js → display-8NGPOhQT.js} +1 -1
  66. package/dist/{public/sdk/ecdsaCapabilityManifest-DAJEVjlP.js → esm/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
  67. package/dist/esm/sdk/{ecdsaDerivationClientWasm-AYOJgTJm.js → ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
  68. package/dist/esm/sdk/ecdsaDerivationExport-jm2VBMz_.js +1 -0
  69. package/dist/esm/sdk/{ecdsaWalletRecords-WLyq414E.js → ecdsaWalletRecords-CKaXfsVu.js} +1 -1
  70. package/dist/esm/sdk/ed25519OperationFingerprint-Dev4P6Og.js +1 -0
  71. package/dist/esm/sdk/{emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
  72. package/dist/esm/sdk/{enrichDisplayModelWithAbi-O6Mw4i2E.js → enrichDisplayModelWithAbi-JeAcpa7r.js} +1 -1
  73. package/dist/esm/sdk/{evmCryptoWasm-BUPb4hBH.js → evmCryptoWasm-CeH6Qeaa.js} +1 -1
  74. package/dist/esm/sdk/{export-viewer-host-BSTfHhau.js → export-viewer-host-TzgdJQuZ.js} +1 -1
  75. package/dist/esm/sdk/exportKeypairOperation-B9_ulzNz.js +1 -0
  76. package/dist/esm/sdk/host-Csu5L7VF.js +1 -0
  77. package/dist/{public/sdk/icons-BlMXolHv.js → esm/sdk/icons-pSZJ5Xrm.js} +1 -1
  78. package/dist/esm/sdk/indexedDB-BqsYXybq.js +1 -0
  79. package/dist/esm/sdk/{intentDigest-HvRsBQ1z.js → intentDigest-gM3r4SVX.js} +1 -1
  80. package/dist/esm/sdk/{lanes-BU-fGqY4.js → lanes-0WT2w1Xz.js} +1 -1
  81. package/dist/esm/sdk/{localOnly-Xs89Xajm.js → localOnly-DFrtrfdO.js} +1 -1
  82. package/dist/{public/sdk/mountExportPrivateKeySurface-CsUEKeum.js → esm/sdk/mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
  83. package/dist/esm/sdk/{mountRecoveryCodeBackupSurface-kFLo5zLk.js → mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
  84. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-Cz2Gb95g.js +1 -0
  85. package/dist/esm/sdk/{nonceLaneKeys-BF_UpvIy.js → nonceLaneKeys-DtBpxubF.js} +1 -1
  86. package/dist/esm/sdk/{normalization-Df9fZWJC.js → normalization-DmfGvZ_3.js} +1 -1
  87. package/dist/esm/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
  88. package/dist/esm/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
  89. package/dist/{public/sdk/pendingWalletRecoveryCodeBackup-B-R_U34I.js → esm/sdk/pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
  90. package/dist/esm/sdk/{presignaturePool-BbvqRWYw.js → presignaturePool-CaI45td2.js} +1 -1
  91. package/dist/{public/sdk/presignatures-BCeq56DG.js → esm/sdk/presignatures-B9KnQyfE.js} +1 -1
  92. package/dist/{public/sdk/recovery-entrypoint-DJbMDC_m.js → esm/sdk/recovery-entrypoint-DA2FGLG6.js} +1 -1
  93. package/dist/esm/sdk/registration-C7w_51wE.js +1 -0
  94. package/dist/esm/sdk/{registration-C2fb9kRQ.js → registration-XNyt1YRK.js} +1 -1
  95. package/dist/esm/sdk/{registrationAccounts-4r74gX1l.js → registrationAccounts-Bso0ntMs.js} +1 -1
  96. package/dist/{public/sdk/registrationIntent-Do1tD1V7.js → esm/sdk/registrationIntent-Cb3tggIM.js} +1 -1
  97. package/dist/{public/sdk/registrationSignerPlan-DK2b3N_p.js → esm/sdk/registrationSignerPlan-CeMidFme.js} +1 -1
  98. package/dist/esm/sdk/{requireStepUpAuth-COqCGb1i.js → requireStepUpAuth-ByMTPBu4.js} +1 -1
  99. package/dist/esm/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
  100. package/dist/esm/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
  101. package/dist/esm/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  102. package/dist/esm/sdk/runtime-auth-BMT_gIKI.js +1 -0
  103. package/dist/esm/sdk/runtime-device-link-DQe0aqRi.js +1 -0
  104. package/dist/esm/sdk/runtime-ecdsa-tempo-DKkeMMpm.js +1 -0
  105. package/dist/esm/sdk/runtime-email-otp-CzTe7r9I.js +1 -0
  106. package/dist/esm/sdk/runtime-export-BiyLbdCe.js +1 -0
  107. package/dist/esm/sdk/runtime-near-Kk0n1FSf.js +1 -0
  108. package/dist/esm/sdk/runtime-preferences-B-A3hddU.js +1 -0
  109. package/dist/esm/sdk/runtime-recovery-C9p1TU1w.js +1 -0
  110. package/dist/esm/sdk/{runtime-recovery-codes-si1fGktB.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
  111. package/dist/esm/sdk/runtimeContext-ChuvOC0h.js +7 -0
  112. package/dist/esm/sdk/{secp256k1-CE7-q9Sn.js → secp256k1-sDDAa4Ga.js} +1 -1
  113. package/dist/esm/sdk/signEvmFamily-CMrXkVsZ.js +1 -0
  114. package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
  115. package/dist/esm/sdk/{signEvmWithUiConfirm-CGrLtMV6.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
  116. package/dist/esm/sdk/signNear-DyFk--I3.js +1 -0
  117. package/dist/esm/sdk/{signatureUses-kSrUHSSH.js → signatureUses-BLOoPRsb.js} +1 -1
  118. package/dist/{public/sdk/signingFlow-BcetvUeS.js → esm/sdk/signingFlow-DTP4D19E.js} +2 -2
  119. package/dist/{public/sdk/signingQueue-dMFOFOP5.js → esm/sdk/signingQueue-Dy5mYMus.js} +1 -1
  120. package/dist/esm/sdk/{thresholdEcdsa-CqR1fFA-.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
  121. package/dist/esm/sdk/{trace--mRP2OQc.js → trace-BA8jya7O.js} +1 -1
  122. package/dist/esm/sdk/{transaction-activity-DCzHGg3b.js → transaction-activity-BXSxMp1E.js} +1 -1
  123. package/dist/esm/sdk/{transactionState-29T9xfvL.js → transactionState-BCbaT2hO.js} +1 -1
  124. package/dist/esm/sdk/tx-confirm-ui.js +3 -1
  125. package/dist/esm/sdk/{types-f7dyj5N6.js → types-D2Zk1W7I.js} +1 -1
  126. package/dist/esm/sdk/{unlockedEd25519ExportRootCapability-yzxQjIFd.js → unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
  127. package/dist/esm/sdk/voiceid-host.js +1 -1
  128. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  129. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  130. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  131. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  132. package/dist/{public/sdk/wallet-recovery-BZB2Vu3X.js → esm/sdk/wallet-recovery-Bfm-oUoP.js} +1 -1
  133. package/dist/esm/sdk/wallet-ui.css +1 -1
  134. package/dist/esm/sdk/{walletAuthMethodRecord-DLBB5fez.js → walletAuthMethodRecord--fvGr8r1.js} +1 -1
  135. package/dist/{public/sdk/walletAuthority-BTGAuOi8.js → esm/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
  136. package/dist/esm/sdk/{walletCapabilityBindings-D5YYB7nN.js → walletCapabilityBindings-mPx-6_r-.js} +1 -1
  137. package/dist/{public/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js → esm/sdk/walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
  138. package/dist/esm/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
  139. package/dist/esm/sdk/{walletCustodyOperation-DimzAbCB.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
  140. package/dist/{public/sdk/walletOwnershipGeneration-CgjCtPrV.js → esm/sdk/walletOwnershipGeneration-B3uE9GRG.js} +1 -1
  141. package/dist/esm/sdk/walletRecoveryAdminProof-BmZaP0Q8.js +1 -0
  142. package/dist/esm/sdk/walletRecoveryCommit-CSYNbYNd.js +1 -0
  143. package/dist/{public/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js → esm/sdk/walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
  144. package/dist/esm/sdk/{walletSessionAuthorizationStore-B9Vwkshr.js → walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
  145. package/dist/esm/sdk/{webauthnP256-BsQQPurm.js → webauthnP256-BGHikiNl.js} +1 -1
  146. package/dist/esm/shared-ts/src/auth/externalAuth.js +2 -2
  147. package/dist/esm/shared-ts/src/utils/index.js +3 -3
  148. package/dist/esm/voiceid-host.js +1 -1
  149. package/dist/esm/wasm/near_signer/pkg/wasm_signer_worker_bg.wasm +0 -0
  150. package/dist/esm/wasm/router_ab_ecdsa_client/pkg/router_ab_ecdsa_client_bg.wasm +0 -0
  151. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client_bg.wasm +0 -0
  152. package/dist/public/headers.manifest.json +1 -1
  153. package/dist/public/sdk/{ConfirmationDrawer-MJoE0AAo.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
  154. package/dist/public/sdk/NonceCoordinator-C1lw03Ce.js +1 -0
  155. package/dist/public/sdk/{SeamsWordmark-DwvPx2UA.js → SeamsWordmark-CeEi2RlU.js} +1 -1
  156. package/dist/public/sdk/accountLifecycle-B5a9SCM7.js +1 -0
  157. package/dist/{esm/sdk/activeWalletSession-BJ4B-nJo.js → public/sdk/activeWalletSession-HAOgRKzn.js} +1 -1
  158. package/dist/{esm/sdk/adapters-C-g_hkkZ.js → public/sdk/adapters-BY1wGpm5.js} +1 -1
  159. package/dist/public/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
  160. package/dist/public/sdk/authorization-D_NueqAv.js +1 -0
  161. package/dist/public/sdk/clientSessionPersistenceState-B3gU3515.js +1 -0
  162. package/dist/public/sdk/{collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js → collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js} +1 -1
  163. package/dist/public/sdk/{commitQueue-CYruPlkm.js → commitQueue-CbyuhEW9.js} +1 -1
  164. package/dist/public/sdk/confirm-ui-DWFcGTsT.js +2 -0
  165. package/dist/{esm/sdk/device-linking-DiCNt3iA.js → public/sdk/device-linking-BL2aDEUF.js} +1 -1
  166. package/dist/public/sdk/{deviceLinkApproval-x3WkiYrd.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
  167. package/dist/{esm/sdk/digestEncoding-CqNXPZY9.js → public/sdk/digestEncoding-Rx8Vjy4J.js} +1 -1
  168. package/dist/public/sdk/{display-D0EPmU4w.js → display-8NGPOhQT.js} +1 -1
  169. package/dist/{esm/sdk/ecdsaCapabilityManifest-DAJEVjlP.js → public/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
  170. package/dist/public/sdk/{ecdsaDerivationClientWasm-AYOJgTJm.js → ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
  171. package/dist/public/sdk/ecdsaDerivationExport-jm2VBMz_.js +1 -0
  172. package/dist/public/sdk/{ecdsaWalletRecords-WLyq414E.js → ecdsaWalletRecords-CKaXfsVu.js} +1 -1
  173. package/dist/public/sdk/ed25519OperationFingerprint-Dev4P6Og.js +1 -0
  174. package/dist/public/sdk/{emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
  175. package/dist/public/sdk/{enrichDisplayModelWithAbi-O6Mw4i2E.js → enrichDisplayModelWithAbi-JeAcpa7r.js} +1 -1
  176. package/dist/public/sdk/{evmCryptoWasm-BUPb4hBH.js → evmCryptoWasm-CeH6Qeaa.js} +1 -1
  177. package/dist/public/sdk/{export-viewer-host-BSTfHhau.js → export-viewer-host-TzgdJQuZ.js} +1 -1
  178. package/dist/public/sdk/exportKeypairOperation-B9_ulzNz.js +1 -0
  179. package/dist/public/sdk/host-Csu5L7VF.js +1 -0
  180. package/dist/{esm/sdk/icons-BlMXolHv.js → public/sdk/icons-pSZJ5Xrm.js} +1 -1
  181. package/dist/public/sdk/indexedDB-BqsYXybq.js +1 -0
  182. package/dist/public/sdk/{intentDigest-HvRsBQ1z.js → intentDigest-gM3r4SVX.js} +1 -1
  183. package/dist/public/sdk/{lanes-BU-fGqY4.js → lanes-0WT2w1Xz.js} +1 -1
  184. package/dist/public/sdk/{localOnly-Xs89Xajm.js → localOnly-DFrtrfdO.js} +1 -1
  185. package/dist/{esm/sdk/mountExportPrivateKeySurface-CsUEKeum.js → public/sdk/mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
  186. package/dist/public/sdk/{mountRecoveryCodeBackupSurface-kFLo5zLk.js → mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
  187. package/dist/public/sdk/nearEd25519YaoSigningPreparation-Cz2Gb95g.js +1 -0
  188. package/dist/public/sdk/{nonceLaneKeys-BF_UpvIy.js → nonceLaneKeys-DtBpxubF.js} +1 -1
  189. package/dist/public/sdk/{normalization-Df9fZWJC.js → normalization-DmfGvZ_3.js} +1 -1
  190. package/dist/public/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
  191. package/dist/public/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
  192. package/dist/{esm/sdk/pendingWalletRecoveryCodeBackup-B-R_U34I.js → public/sdk/pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
  193. package/dist/public/sdk/{presignaturePool-BbvqRWYw.js → presignaturePool-CaI45td2.js} +1 -1
  194. package/dist/{esm/sdk/presignatures-BCeq56DG.js → public/sdk/presignatures-B9KnQyfE.js} +1 -1
  195. package/dist/{esm/sdk/recovery-entrypoint-DJbMDC_m.js → public/sdk/recovery-entrypoint-DA2FGLG6.js} +1 -1
  196. package/dist/public/sdk/registration-C7w_51wE.js +1 -0
  197. package/dist/public/sdk/{registration-C2fb9kRQ.js → registration-XNyt1YRK.js} +1 -1
  198. package/dist/public/sdk/{registrationAccounts-4r74gX1l.js → registrationAccounts-Bso0ntMs.js} +1 -1
  199. package/dist/{esm/sdk/registrationIntent-Do1tD1V7.js → public/sdk/registrationIntent-Cb3tggIM.js} +1 -1
  200. package/dist/{esm/sdk/registrationSignerPlan-DK2b3N_p.js → public/sdk/registrationSignerPlan-CeMidFme.js} +1 -1
  201. package/dist/public/sdk/{requireStepUpAuth-COqCGb1i.js → requireStepUpAuth-ByMTPBu4.js} +1 -1
  202. package/dist/public/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
  203. package/dist/public/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
  204. package/dist/public/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  205. package/dist/public/sdk/runtime-auth-BMT_gIKI.js +1 -0
  206. package/dist/public/sdk/runtime-device-link-DQe0aqRi.js +1 -0
  207. package/dist/public/sdk/runtime-ecdsa-tempo-DKkeMMpm.js +1 -0
  208. package/dist/public/sdk/runtime-email-otp-CzTe7r9I.js +1 -0
  209. package/dist/public/sdk/runtime-export-BiyLbdCe.js +1 -0
  210. package/dist/public/sdk/runtime-near-Kk0n1FSf.js +1 -0
  211. package/dist/public/sdk/runtime-preferences-B-A3hddU.js +1 -0
  212. package/dist/public/sdk/runtime-recovery-C9p1TU1w.js +1 -0
  213. package/dist/public/sdk/{runtime-recovery-codes-si1fGktB.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
  214. package/dist/public/sdk/runtimeContext-ChuvOC0h.js +7 -0
  215. package/dist/public/sdk/{secp256k1-CE7-q9Sn.js → secp256k1-sDDAa4Ga.js} +1 -1
  216. package/dist/public/sdk/signEvmFamily-CMrXkVsZ.js +1 -0
  217. package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
  218. package/dist/public/sdk/{signEvmWithUiConfirm-CGrLtMV6.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
  219. package/dist/public/sdk/signNear-DyFk--I3.js +1 -0
  220. package/dist/public/sdk/{signatureUses-kSrUHSSH.js → signatureUses-BLOoPRsb.js} +1 -1
  221. package/dist/{esm/sdk/signingFlow-BcetvUeS.js → public/sdk/signingFlow-DTP4D19E.js} +2 -2
  222. package/dist/{esm/sdk/signingQueue-dMFOFOP5.js → public/sdk/signingQueue-Dy5mYMus.js} +1 -1
  223. package/dist/public/sdk/{thresholdEcdsa-CqR1fFA-.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
  224. package/dist/public/sdk/{trace--mRP2OQc.js → trace-BA8jya7O.js} +1 -1
  225. package/dist/public/sdk/{transaction-activity-DCzHGg3b.js → transaction-activity-BXSxMp1E.js} +1 -1
  226. package/dist/public/sdk/{transactionState-29T9xfvL.js → transactionState-BCbaT2hO.js} +1 -1
  227. package/dist/public/sdk/tx-confirm-ui.js +3 -1
  228. package/dist/public/sdk/{types-f7dyj5N6.js → types-D2Zk1W7I.js} +1 -1
  229. package/dist/public/sdk/{unlockedEd25519ExportRootCapability-yzxQjIFd.js → unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
  230. package/dist/public/sdk/voiceid-host.js +1 -1
  231. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  232. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  233. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  234. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  235. package/dist/{esm/sdk/wallet-recovery-BZB2Vu3X.js → public/sdk/wallet-recovery-Bfm-oUoP.js} +1 -1
  236. package/dist/public/sdk/wallet-ui.css +1 -1
  237. package/dist/public/sdk/{walletAuthMethodRecord-DLBB5fez.js → walletAuthMethodRecord--fvGr8r1.js} +1 -1
  238. package/dist/{esm/sdk/walletAuthority-BTGAuOi8.js → public/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
  239. package/dist/public/sdk/{walletCapabilityBindings-D5YYB7nN.js → walletCapabilityBindings-mPx-6_r-.js} +1 -1
  240. package/dist/{esm/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js → public/sdk/walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
  241. package/dist/public/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
  242. package/dist/public/sdk/{walletCustodyOperation-DimzAbCB.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
  243. package/dist/{esm/sdk/walletOwnershipGeneration-CgjCtPrV.js → public/sdk/walletOwnershipGeneration-B3uE9GRG.js} +1 -1
  244. package/dist/public/sdk/walletRecoveryAdminProof-BmZaP0Q8.js +1 -0
  245. package/dist/public/sdk/walletRecoveryCommit-CSYNbYNd.js +1 -0
  246. package/dist/{esm/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js → public/sdk/walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
  247. package/dist/public/sdk/{walletSessionAuthorizationStore-B9Vwkshr.js → walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
  248. package/dist/public/sdk/{webauthnP256-BsQQPurm.js → webauthnP256-BGHikiNl.js} +1 -1
  249. package/dist/public/sdk/workers/email_otp_runtime_bg.wasm +0 -0
  250. package/dist/public/sdk/workers/evm_crypto_bg.wasm +0 -0
  251. package/dist/public/sdk/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  252. package/dist/public/sdk/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  253. package/dist/public/sdk/workers/shamir3pass_runtime_bg.wasm +0 -0
  254. package/dist/public/sdk/workers/tempo_signer_bg.wasm +0 -0
  255. package/dist/public/sdk/workers/wallet_custody_ceremony_bg.wasm +0 -0
  256. package/dist/public/sdk/workers/wasm_signer_worker_bg.wasm +0 -0
  257. package/dist/public/wallet-assets.manifest.json +264 -264
  258. package/dist/public/wallet-service/index.html +4 -4
  259. package/dist/types/shared-ts/src/auth/externalAuth.d.ts +51 -8
  260. package/dist/types/shared-ts/src/authorization/index.d.ts +1 -1
  261. package/dist/types/shared-ts/src/authorization/walletOwnerOperation.d.ts +10 -0
  262. package/dist/types/shared-ts/src/utils/registrationEstablishedSession.d.ts +4 -0
  263. package/dist/types/shared-ts/src/utils/registrationIntent.d.ts +2 -0
  264. package/dist/types/shared-ts/src/utils/walletManagementProtocol.d.ts +1 -1
  265. package/dist/types/wallet/src/SeamsWeb/index.d.ts +1 -0
  266. package/dist/types/wallet/src/SeamsWeb/operations/registration/pendingRegistrationRecovery.d.ts +1 -0
  267. package/dist/types/wallet/src/SeamsWeb/operations/registration/registration.d.ts +1 -0
  268. package/dist/types/wallet/src/SeamsWeb/operations/registration/registrationPasskeyMaterial.d.ts +24 -0
  269. package/dist/types/wallet/src/SeamsWeb/publicApi/auth.d.ts +1 -1
  270. package/dist/types/wallet/src/SeamsWeb/publicApi/createPublicApi.d.ts +1 -0
  271. package/dist/types/wallet/src/SeamsWeb/publicApi/nearCommands.d.ts +2 -0
  272. package/dist/types/wallet/src/SeamsWeb/publicApi/ownerNearOperation.d.ts +58 -0
  273. package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +17 -6
  274. package/dist/types/wallet/src/SeamsWeb/signingSurface/BrowserSigningSurface.d.ts +57 -56
  275. package/dist/types/wallet/src/SeamsWeb/signingSurface/nearOwnerOperation.d.ts +16 -0
  276. package/dist/types/wallet/src/SeamsWeb/signingSurface/nearPasskeyOperationMaterial.d.ts +72 -0
  277. package/dist/types/wallet/src/SeamsWeb/signingSurface/types.d.ts +3 -0
  278. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/inboundMessages.d.ts +5 -0
  279. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/ownerNearOperation.d.ts +25 -0
  280. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +7 -1
  281. package/dist/types/wallet/src/SeamsWeb/walletIframe/coordinator.d.ts +6 -0
  282. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/WalletHostRuntime.d.ts +5 -1
  283. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/controller.d.ts +2 -0
  284. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/domain.d.ts +3 -0
  285. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/session.d.ts +4 -0
  286. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/createNearCommands.d.ts +2 -1
  287. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/createSessionCommands.d.ts +6 -2
  288. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/externalAuth.d.ts +10 -8
  289. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/externalOwnerApproval.d.ts +24 -0
  290. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ownerNearOperation.d.ts +12 -0
  291. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/requestRouter.d.ts +2 -2
  292. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +5 -0
  293. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.d.ts +13 -0
  294. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.d.ts +3 -0
  295. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/exactSessionState.d.ts +8 -0
  296. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +26 -9
  297. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/ownerNearOperation.d.ts +51 -0
  298. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/walletAlternatives.d.ts +52 -0
  299. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/registrationSetup.d.ts +1 -0
  300. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/repositories.d.ts +4 -0
  301. package/dist/types/wallet/src/core/rpcClients/near/NearClient.d.ts +4 -0
  302. package/dist/types/wallet/src/core/rpcClients/relayer/walletRecoveryRotate.d.ts +2 -2
  303. package/dist/types/wallet/src/core/rpcClients/relayer/walletRegistration.d.ts +1 -0
  304. package/dist/types/wallet/src/core/signingEngine/session/passkey/ed25519YaoLocalMaterial.d.ts +21 -0
  305. package/dist/types/wallet/src/core/types/seams.d.ts +9 -2
  306. package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
  307. package/dist/types/wallet/src/core/ui/walletIcon.d.ts +3 -0
  308. package/dist/types/wallet/src/index.d.ts +3 -0
  309. package/dist/types/wallet/src/react/boundWallet.d.ts +21 -1
  310. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/public.d.ts +1 -0
  311. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/types.d.ts +4 -0
  312. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/walletAlternatives.d.ts +48 -0
  313. package/dist/types/wallet/src/react/hooks/useOwnerNearOperation.d.ts +4 -0
  314. package/dist/types/wallet/src/react/index.d.ts +4 -2
  315. package/dist/workers/email_otp_runtime_bg.wasm +0 -0
  316. package/dist/workers/evm_crypto_bg.wasm +0 -0
  317. package/dist/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  318. package/dist/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  319. package/dist/workers/shamir3pass_runtime_bg.wasm +0 -0
  320. package/dist/workers/tempo_signer_bg.wasm +0 -0
  321. package/dist/workers/wallet_custody_ceremony_bg.wasm +0 -0
  322. package/dist/workers/wasm_signer_worker_bg.wasm +0 -0
  323. package/package.json +1 -1
  324. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.css +0 -182
  325. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.js +0 -315
  326. package/dist/esm/sdk/NonceCoordinator-3YhmDTS5.js +0 -1
  327. package/dist/esm/sdk/accountLifecycle-6DHYWf0v.js +0 -1
  328. package/dist/esm/sdk/appearance-token-vars-01eH9pgA.js +0 -1
  329. package/dist/esm/sdk/clientSessionPersistenceState-BCkJAYSz.js +0 -1
  330. package/dist/esm/sdk/confirm-ui-em0vkd2m.js +0 -2
  331. package/dist/esm/sdk/ecdsaDerivationExport-DJKOzDbS.js +0 -1
  332. package/dist/esm/sdk/exportKeypairOperation-CjST_NUK.js +0 -1
  333. package/dist/esm/sdk/host-C51z-AxP.js +0 -1
  334. package/dist/esm/sdk/indexedDB-C4SDsyOG.js +0 -1
  335. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +0 -1
  336. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +0 -1
  337. package/dist/esm/sdk/registration-Byl4l4yZ.js +0 -1
  338. package/dist/esm/sdk/resealedEnvelopeResult-CLW00Vbw.js +0 -1
  339. package/dist/esm/sdk/routerAbNormalSigning-D-UZmCBS.js +0 -1
  340. package/dist/esm/sdk/runtime-auth-ufbVur2p.js +0 -1
  341. package/dist/esm/sdk/runtime-device-link-CagI2Q62.js +0 -1
  342. package/dist/esm/sdk/runtime-ecdsa-tempo-Rctxr0yM.js +0 -1
  343. package/dist/esm/sdk/runtime-email-otp-BQtcG-LF.js +0 -1
  344. package/dist/esm/sdk/runtime-export-wTeEaqlk.js +0 -1
  345. package/dist/esm/sdk/runtime-near-59yU_3ud.js +0 -1
  346. package/dist/esm/sdk/runtime-preferences-B9qLHX8W.js +0 -1
  347. package/dist/esm/sdk/runtime-recovery-DNyzdMBj.js +0 -1
  348. package/dist/esm/sdk/runtimeContext-ByeM6Z4Z.js +0 -6
  349. package/dist/esm/sdk/sessionObservationRevision-ihBwjS3y.js +0 -1
  350. package/dist/esm/sdk/signEvmFamily-BY5jlZEG.js +0 -1
  351. package/dist/esm/sdk/signNear-DMpJFkwF.js +0 -1
  352. package/dist/esm/sdk/signer-worker-BNodGJKY.js +0 -1
  353. package/dist/esm/sdk/walletRecoveryAdminProof-B4Ic07jY.js +0 -1
  354. package/dist/esm/sdk/walletRecoveryCommit-Cc2LAkCS.js +0 -1
  355. package/dist/public/sdk/NonceCoordinator-3YhmDTS5.js +0 -1
  356. package/dist/public/sdk/accountLifecycle-6DHYWf0v.js +0 -1
  357. package/dist/public/sdk/appearance-token-vars-01eH9pgA.js +0 -1
  358. package/dist/public/sdk/clientSessionPersistenceState-BCkJAYSz.js +0 -1
  359. package/dist/public/sdk/confirm-ui-em0vkd2m.js +0 -2
  360. package/dist/public/sdk/ecdsaDerivationExport-DJKOzDbS.js +0 -1
  361. package/dist/public/sdk/exportKeypairOperation-CjST_NUK.js +0 -1
  362. package/dist/public/sdk/host-C51z-AxP.js +0 -1
  363. package/dist/public/sdk/indexedDB-C4SDsyOG.js +0 -1
  364. package/dist/public/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +0 -1
  365. package/dist/public/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +0 -1
  366. package/dist/public/sdk/registration-Byl4l4yZ.js +0 -1
  367. package/dist/public/sdk/resealedEnvelopeResult-CLW00Vbw.js +0 -1
  368. package/dist/public/sdk/routerAbNormalSigning-D-UZmCBS.js +0 -1
  369. package/dist/public/sdk/runtime-auth-ufbVur2p.js +0 -1
  370. package/dist/public/sdk/runtime-device-link-CagI2Q62.js +0 -1
  371. package/dist/public/sdk/runtime-ecdsa-tempo-Rctxr0yM.js +0 -1
  372. package/dist/public/sdk/runtime-email-otp-BQtcG-LF.js +0 -1
  373. package/dist/public/sdk/runtime-export-wTeEaqlk.js +0 -1
  374. package/dist/public/sdk/runtime-near-59yU_3ud.js +0 -1
  375. package/dist/public/sdk/runtime-preferences-B9qLHX8W.js +0 -1
  376. package/dist/public/sdk/runtime-recovery-DNyzdMBj.js +0 -1
  377. package/dist/public/sdk/runtimeContext-ByeM6Z4Z.js +0 -6
  378. package/dist/public/sdk/sessionObservationRevision-ihBwjS3y.js +0 -1
  379. package/dist/public/sdk/signEvmFamily-BY5jlZEG.js +0 -1
  380. package/dist/public/sdk/signNear-DMpJFkwF.js +0 -1
  381. package/dist/public/sdk/signer-worker-BNodGJKY.js +0 -1
  382. package/dist/public/sdk/walletRecoveryAdminProof-B4Ic07jY.js +0 -1
  383. package/dist/public/sdk/walletRecoveryCommit-Cc2LAkCS.js +0 -1
  384. package/dist/types/shared-ts/src/authorization/walletCustodyOperation.d.ts +0 -10
  385. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.d.ts +0 -31
  386. /package/dist/esm/sdk/{accountIds-CW2BP-d9.js → accountIds-DGWFzEnw.js} +0 -0
  387. /package/dist/esm/sdk/{actions-DrtSTGus.js → actions-7SvZZut1.js} +0 -0
  388. /package/dist/esm/sdk/{authenticatorOptions-WCDKYRux.js → authenticatorOptions-B4q62CLs.js} +0 -0
  389. /package/dist/esm/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
  390. /package/dist/esm/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
  391. /package/dist/esm/sdk/{confirmTypes-BvVtQs-M.js → confirmTypes-DmEPoxys.js} +0 -0
  392. /package/dist/esm/sdk/{csp-stylesheet-DUSqfXvZ.js → csp-stylesheet-5LU6VGKK.js} +0 -0
  393. /package/dist/esm/sdk/{ecdsaChainTarget-Bm5X4k-V.js → ecdsaChainTarget-BoRVQtjQ.js} +0 -0
  394. /package/dist/esm/sdk/{executeWorkerOperation-C9FOCCR7.js → executeWorkerOperation-CAYSt0NA.js} +0 -0
  395. /package/dist/esm/sdk/{helpers-Dubwo5uK.js → helpers-B7c1zc7h.js} +0 -0
  396. /package/dist/esm/sdk/{jsonRpc-BVDv1wfm.js → jsonRpc-DGzeiNSa.js} +0 -0
  397. /package/dist/esm/sdk/{keccak-mS0Mejjx.js → keccak-DGHI1G6t.js} +0 -0
  398. /package/dist/esm/sdk/{keyMaterialEnvelope-Dm2ZEilb.js → keyMaterialEnvelope-Czkks9Ki.js} +0 -0
  399. /package/dist/esm/sdk/{profileAccountProjection-C5sNt-s2.js → profileAccountProjection-dvLchPBo.js} +0 -0
  400. /package/dist/esm/sdk/{registrationAuthMethodInput-BR1WVbK3.js → registrationAuthMethodInput-C4o7yFBJ.js} +0 -0
  401. /package/dist/esm/sdk/{sdkSentEvents-DjOlKtdW.js → sdkSentEvents-BFwv3mBw.js} +0 -0
  402. /package/dist/esm/sdk/{signerDomain-BAsLT3XN.js → signerDomain-D-EUTlLK.js} +0 -0
  403. /package/dist/esm/sdk/{signerSlot-D2RZnb27.js → signerSlot-BlijMq8C.js} +0 -0
  404. /package/dist/esm/sdk/{surface-measurement-reporter-DXsvq401.js → surface-measurement-reporter-DJ_dQhBV.js} +0 -0
  405. /package/dist/esm/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
  406. /package/dist/public/sdk/{accountIds-CW2BP-d9.js → accountIds-DGWFzEnw.js} +0 -0
  407. /package/dist/public/sdk/{actions-DrtSTGus.js → actions-7SvZZut1.js} +0 -0
  408. /package/dist/public/sdk/{authenticatorOptions-WCDKYRux.js → authenticatorOptions-B4q62CLs.js} +0 -0
  409. /package/dist/public/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
  410. /package/dist/public/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
  411. /package/dist/public/sdk/{confirmTypes-BvVtQs-M.js → confirmTypes-DmEPoxys.js} +0 -0
  412. /package/dist/public/sdk/{csp-stylesheet-DUSqfXvZ.js → csp-stylesheet-5LU6VGKK.js} +0 -0
  413. /package/dist/public/sdk/{ecdsaChainTarget-Bm5X4k-V.js → ecdsaChainTarget-BoRVQtjQ.js} +0 -0
  414. /package/dist/public/sdk/{executeWorkerOperation-C9FOCCR7.js → executeWorkerOperation-CAYSt0NA.js} +0 -0
  415. /package/dist/public/sdk/{helpers-Dubwo5uK.js → helpers-B7c1zc7h.js} +0 -0
  416. /package/dist/public/sdk/{jsonRpc-BVDv1wfm.js → jsonRpc-DGzeiNSa.js} +0 -0
  417. /package/dist/public/sdk/{keccak-mS0Mejjx.js → keccak-DGHI1G6t.js} +0 -0
  418. /package/dist/public/sdk/{keyMaterialEnvelope-Dm2ZEilb.js → keyMaterialEnvelope-Czkks9Ki.js} +0 -0
  419. /package/dist/public/sdk/{profileAccountProjection-C5sNt-s2.js → profileAccountProjection-dvLchPBo.js} +0 -0
  420. /package/dist/public/sdk/{registrationAuthMethodInput-BR1WVbK3.js → registrationAuthMethodInput-C4o7yFBJ.js} +0 -0
  421. /package/dist/public/sdk/{sdkSentEvents-DjOlKtdW.js → sdkSentEvents-BFwv3mBw.js} +0 -0
  422. /package/dist/public/sdk/{signerDomain-BAsLT3XN.js → signerDomain-D-EUTlLK.js} +0 -0
  423. /package/dist/public/sdk/{signerSlot-D2RZnb27.js → signerSlot-BlijMq8C.js} +0 -0
  424. /package/dist/public/sdk/{surface-measurement-reporter-DXsvq401.js → surface-measurement-reporter-DJ_dQhBV.js} +0 -0
  425. /package/dist/public/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
@@ -0,0 +1,7 @@
1
+ import{r as e}from"./chunk-dVx5-UGu.js";import{A as t,C as n,E as r,H as i,M as a,N as o,O as s,P as c,S as l,T as u,V as d,d as f,f as p,g as m,h,i as g,k as _,l as v,m as y,n as b,r as x,u as S,w as C,x as w,y as T}from"./domainIds-t1lp25yU.js";import{S as E,b as D,f as O,g as k,h as A,i as j,o as M,r as ee,s as te,t as ne,v as re,w as N}from"./digests-BIaE0DMd.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,t as de,u as fe}from"./participants-BXdREC5k.js";import{i as pe,n as me}from"./configBuilder-DpChXfDO.js";import{t as he}from"./theme-os0Salmo.js";import{i as P,n as ge,r as F}from"./base64-BmKR3UqU.js";import{n as _e,r as ve}from"./secureRandomId-8LSc91aN.js";import{a as ye,c as be,i as xe,n as Se,o as Ce,s as we}from"./walletDbName-B6-CV_Rq.js";import{A as Te,D as Ee,E as De,I as Oe,J as ke,M as Ae,N as je,O as Me,P as Ne,Q as Pe,X as Fe,Z as Ie,a as Le,h as Re,i as ze,j as Be,k as Ve,r as He,t as Ue,z as We}from"./activeWalletSession-HAOgRKzn.js";import{o as Ge,s as Ke,t as qe}from"./chains-B72I4PDH.js";import{n as Je,t as Ye}from"./configHelpers-CXDY3bKC.js";import{a as Xe,c as Ze,d as Qe,n as $e,s as et,t as tt}from"./signingSessionSeal-BFOBKj-J.js";import{r as nt}from"./configuration-BAad7ngq.js";import{r as rt}from"./transactionReviewAdmission-Cf_qUZJt.js";import{A as it,C as at,D as ot,E as st,O as ct,a as lt,c as ut,d as dt,f as ft,i as pt,l as mt,n as ht,p as gt,r as _t,s as vt,t as yt,u as bt}from"./ownerNearOperation-DCxxHcwX.js";import{t as xt}from"./walletIframeIdentity-Cz82I_Uh.js";import{a as St,d as Ct,g as wt,h as Tt,i as Et,l as Dt,m as Ot,n as kt,o as At,r as jt,t as Mt}from"./capabilityKinds-Cafn86Y1.js";import{a as Nt,r as Pt}from"./canonicalPrimitives-DKeS3M40.js";import{i as Ft,n as It,o as Lt,s as I,t as L}from"./errors-BJBDbwHk.js";import{s as Rt}from"./ed25519OperationFingerprint-Dev4P6Og.js";import{a as R,c as zt,d as Bt,f as Vt,h as Ht,i as Ut,m as Wt,n as z,o as Gt,p as Kt,r as qt,s as Jt,u as Yt}from"./signerDomain-D-EUTlLK.js";import{c as Xt,n as Zt,r as Qt,s as $t}from"./types-D2Zk1W7I.js";import{a as en,d as tn,i as nn,r as rn,t as B}from"./accountIds-DGWFzEnw.js";import{a as an,t as on}from"./actions-7SvZZut1.js";import{n as sn,t as cn}from"./csp-stylesheet-5LU6VGKK.js";import{E as ln,f as un,g as dn,h as fn,m as pn,p as mn,r as hn,v as gn,w as _n,x as vn}from"./registrationIntent-Cb3tggIM.js";import{n as yn,t as bn}from"./presignatures-B9KnQyfE.js";import{a as xn,c as V,i as Sn,n as Cn,o as H,s as wn,t as Tn,u as En}from"./ecdsaChainTarget-BoRVQtjQ.js";import{s as Dn,t as On}from"./normalization-DmfGvZ_3.js";import{$ as kn,A as An,B as jn,C as Mn,D as Nn,E as Pn,F as Fn,G as In,H as Ln,I as Rn,J as zn,K as Bn,L as Vn,M as Hn,N as Un,O as Wn,P as Gn,Q as Kn,R as qn,S as Jn,T as Yn,U as Xn,V as Zn,W as Qn,X as $n,Y as er,Z as tr,_ as nr,a as rr,b as ir,c as ar,d as or,et as sr,f as cr,g as lr,h as ur,i as dr,j as fr,k as pr,l as mr,m as hr,n as gr,o as _r,p as vr,r as yr,s as br,u as xr,w as Sr,x as Cr,y as wr,z as Tr}from"./device-linking-BL2aDEUF.js";import{A as Er,D as Dr,G as Or,H as kr,K as Ar,M as jr,N as Mr,O as Nr,U as Pr,W as Fr,Y as Ir,Z as Lr,b as Rr,f as zr,n as Br,nt as Vr,o as Hr,p as Ur,r as Wr,s as Gr,t as Kr,tt as qr,v as Jr,w as Yr,y as Xr}from"./walletAuthority-CU9nO0Ze.js";import{A as Zr,Dt as Qr,Et as $r,Ft as ei,G as ti,I as ni,K as ri,Nt as ii,Ot as ai,Pt as oi,Q as si,S as ci,Tt as li,W as ui,X as di,Y as fi,Z as pi,_ as mi,at as hi,ct as gi,it as _i,kt as vi,lt as yi,nt as bi,q as xi,rt as Si,ut as U,x as Ci}from"./digestEncoding-Rx8Vjy4J.js";import{n as wi,r as Ti,t as Ei}from"./walletAuthMethodRecord--fvGr8r1.js";import{a as Di,i as Oi,o as ki,t as Ai}from"./signerSlot-BlijMq8C.js";import{C as ji,D as Mi,E as Ni,I as Pi,M as Fi,N as Ii,P as Li,R as Ri,T as zi,V as Bi,j as Vi,k as Hi,w as Ui,z as Wi}from"./ecdsaCapabilityManifest-BbPXL-qh.js";import{d as Gi,f as Ki,g as qi,h as Ji,l as Yi,m as Xi,o as W,r as Zi,s as G,t as Qi}from"./sdkSentEvents-BFwv3mBw.js";import{D as $i,F as ea,I as ta,d as na,f as ra,l as ia,n as aa,r as oa,t as K,u as sa,v as ca,y as la}from"./indexedDB-BqsYXybq.js";import"./keccak-DGHI1G6t.js";import{c as ua,t as da}from"./registrationSignerPlan-CeMidFme.js";import{a as fa,c as pa,o as ma,s as ha,t as ga,u as _a}from"./walletCapabilityBindings-mPx-6_r-.js";import{n as va}from"./authenticatorOptions-B4q62CLs.js";import{i as ya}from"./walletOwnershipGeneration-B3uE9GRG.js";import{A as ba,C as xa,O as Sa,S as Ca,T as wa,_ as Ta,c as Ea,d as Da,f as Oa,h as ka,j as Aa,k as ja,l as Ma,m as Na,o as Pa,s as Fa,v as Ia,x as La}from"./emailOtpEcdsaDerivationIdentity-DJmMyqL-.js";import{o as q,t as Ra}from"./walletSessionAuthorizationStore-CGt-s5fX.js";import{a as za,c as Ba,l as Va,o as Ha,r as Ua,s as Wa,t as Ga,u as Ka}from"./resealedEnvelopeResult-DKY5fVNY.js";import{n as qa,t as Ja}from"./walletSessionAuthorizationStatus-CQ3qA9tI.js";import{t as Ya}from"./executeWorkerOperation-CAYSt0NA.js";import{a as Xa,c as Za,i as Qa,l as $a,n as eo,o as to,r as no,s as ro,t as io,u as ao}from"./unlockedEd25519ExportRootCapability-BbGMlikr.js";import{A as oo,D as so,E as co,O as lo,S as uo,T as fo,_ as po,b as mo,d as ho,k as go,l as _o,r as vo,s as yo,u as bo,w as xo}from"./authorization-D_NueqAv.js";import{i as So}from"./profileAccountProjection-dvLchPBo.js";import{a as Co,i as wo,l as To,n as Eo,o as Do,s as Oo,t as ko}from"./walletCustodyEcdsaContinuity-BUdDyRl_.js";import{$ as Ao,A as jo,At as Mo,B as No,Bt as Po,C as Fo,Ct as Io,D as Lo,Dt as Ro,E as zo,Et as Bo,F as Vo,Ft as Ho,G as Uo,Gt as Wo,H as Go,Ht as Ko,I as qo,It as Jo,J as Yo,Jt as Xo,K as Zo,Kt as Qo,L as $o,Lt as es,M as ts,Mt as ns,N as rs,Nt as is,O as as,Ot as os,P as ss,Pt as cs,Q as ls,R as us,Rt as ds,S as fs,St as ps,T as ms,Tt as hs,U as gs,Ut as _s,V as vs,Vt as ys,W as bs,Wt as xs,X as Ss,Xt as Cs,Y as ws,Yt as Ts,Z as Es,Zt as Ds,_ as Os,_t as ks,a as As,at as js,b as Ms,bt as Ns,c as Ps,ct as Fs,d as Is,dt as Ls,et as Rs,f as zs,ft as Bs,g as Vs,gt as Hs,h as Us,ht as Ws,it as Gs,j as Ks,jt as qs,kt as Js,l as Ys,lt as Xs,m as Zs,mt as Qs,nt as $s,ot as ec,p as tc,pt as nc,q as rc,qt as ic,rt as ac,st as oc,t as sc,tt as cc,u as lc,ut as uc,v as dc,vt as fc,w as pc,wt as mc,x as hc,xt as gc,y as _c,yt as vc,z as yc,zt as bc}from"./registration-C7w_51wE.js";import{c as xc,l as Sc,o as Cc,s as wc,u as Tc}from"./helpers-B7c1zc7h.js";import{A as Ec,C as Dc,D as Oc,E as kc,M as Ac,O as jc,P as Mc,S as Nc,T as Pc,_ as Fc,a as Ic,b as Lc,c as Rc,g as zc,i as Bc,j as Vc,k as Hc,l as Uc,n as Wc,o as Gc,r as Kc,s as qc,t as Jc,v as Yc,w as Xc,x as Zc,y as Qc}from"./accountLifecycle-B5a9SCM7.js";import{C as $c,D as el,M as tl,N as nl,O as rl,P as il,_ as al,a as ol,c as sl,d as cl,f as ll,h as ul,i as dl,j as fl,k as pl,l as ml,m as hl,n as gl,p as _l,r as vl,s as yl,t as bl,u as xl,v as Sl,w as Cl}from"./nearEd25519YaoSigningPreparation-Cz2Gb95g.js";import{a as wl,i as Tl,o as El,r as Dl,t as Ol}from"./pendingWalletRecoveryCodeBackup-8iMhQU-E.js";import{c as kl,i as Al,o as jl,r as Ml,s as Nl,t as Pl}from"./wallet-recovery-Bfm-oUoP.js";import{t as Fl}from"./walletOwnerOperation-BJPxzo-k.js";import{n as Il,t as Ll}from"./prfCache-DEHaUPSW.js";import{u as Rl}from"./trace-BA8jya7O.js";import{o as zl,r as Bl}from"./walletSessionAuthorizationProjection-BzUH6gHV.js";import{_ as Vl,a as Hl,c as Ul,f as Wl,g as Gl,h as Kl,i as ql,l as Jl,m as Yl,n as Xl,o as Zl,p as Ql,r as $l,s as eu,t as tu,u as nu,v as ru,y as iu}from"./adapters-BY1wGpm5.js";import{_ as au,a as ou,c as su,d as cu,f as lu,g as uu,h as du,i as fu,l as pu,m as mu,n as hu,o as gu,p as _u,s as vu,u as yu,y as bu}from"./ecdsaDerivationExport-jm2VBMz_.js";import{i as xu,n as Su,r as Cu}from"./intentDigest-gM3r4SVX.js";import{n as wu,r as Tu,t as Eu}from"./deviceLinkApproval-C4T8XAmi.js";import{i as Du}from"./walletRecoveryCommit-CSYNbYNd.js";import{t as Ou}from"./NonceCoordinator-C1lw03Ce.js";import{A as ku,C as Au,D as ju,E as Mu,F as Nu,I as Pu,L as Fu,M as Iu,N as Lu,O as Ru,P as zu,R as Bu,S as Vu,T as Hu,_ as Uu,b as Wu,c as Gu,f as Ku,g as qu,h as Ju,j as Yu,k as Xu,l as Zu,m as Qu,o as $u,p as ed,r as td,s as nd,t as rd,v as id,w as ad,y as od}from"./ecdsaDerivationClientWasm-GCt9yVsd.js";import{a as sd,n as cd,o as ld,r as ud,s as dd,t as fd}from"./presignaturePool-CaI45td2.js";import{i as pd,t as md}from"./walletSessionFailure-CxsVtroW.js";import{_ as hd,a as gd,b as _d,c as vd,d as yd,f as bd,g as xd,h as Sd,i as Cd,l as wd,m as Td,n as Ed,o as Dd,p as Od,r as kd,t as Ad,u as jd,v as Md,y as Nd}from"./signEvmFamily-CMrXkVsZ.js";import{a as Pd,c as Fd,d as Id,f as Ld,i as Rd,l as zd,o as Bd,s as Vd,t as Hd,u as Ud}from"./signingQueue-Dy5mYMus.js";import{_ as Wd,c as Gd,d as Kd,g as qd,h as Jd,i as Yd,o as Xd,r as Zd,s as Qd,t as $d,u as ef,v as tf}from"./clientSessionPersistenceState-B3gU3515.js";import{_ as nf,a as rf,c as af,d as of,f as sf,g as cf,h as lf,i as uf,l as df,m as ff,o as pf,p as mf,r as hf,s as gf,t as _f,v as vf}from"./signNear-DyFk--I3.js";import{i as yf,t as bf}from"./collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js";import{c as xf,d as Sf,f as Cf,i as wf,o as Tf,s as Ef,t as Df}from"./signingFlow-DTP4D19E.js";import{t as Of}from"./types-C4OErbBf.js";import{S as kf,_ as Af,d as jf,f as J,m as Mf,p as Nf}from"./requireStepUpAuth-ByMTPBu4.js";import{t as Pf}from"./commitQueue-CbyuhEW9.js";import{n as Y,t as Ff}from"./confirmTypes-DmEPoxys.js";import{a as If,c as Lf,i as Rf,l as zf,n as Bf,o as Vf,r as Hf,s as Uf,t as Wf,u as Gf}from"./walletRecoveryAdminProof-BmZaP0Q8.js";import{c as Kf,l as qf,o as Jf,r as Yf,s as Xf}from"./confirm-ui-DWFcGTsT.js";import{i as Zf,n as Qf,r as $f,t as ep}from"./transaction-activity-BXSxMp1E.js";import"./appearance-token-vars-CzlRDVQ7.js";import{t as tp}from"./registration-XNyt1YRK.js";function np(){let e=typeof window<`u`&&window.location?.origin?window.location.origin:``;try{let t=window?.__SEAMS_WALLET_SDK_BASE__;if(t){let n=new URL(t,e||`https://invalid.local`).origin;if(n===e)return n}}catch{}return e}function rp(e,t){let n=t.worker,r=t.baseOrigin||np()||(typeof window<`u`?window.location.origin:``)||`https://invalid.local`;try{let t=typeof window<`u`?window:{},i;switch(n){case`signer`:i=t.__SEAMS_SIGNER_WORKER_URL__;break;case`ecdsaDerivationClient`:i=t.__SEAMS_ECDSA_DERIVATION_CLIENT_WORKER_URL__;break;case`ecdsaPresignClient`:i=t.__SEAMS_ECDSA_PRESIGN_CLIENT_WORKER_URL__;break;case`ecdsaOnlineClient`:i=t.__SEAMS_ECDSA_ONLINE_CLIENT_WORKER_URL__;break;case`touchConfirm`:i=t.__SEAMS_TOUCH_CONFIRM_WORKER_URL__;break;case`passkeyMpcExport`:i=t.__SEAMS_PASSKEY_MPC_EXPORT_WORKER_URL__;break;case`passkeyMpcSession`:i=t.__SEAMS_PASSKEY_MPC_SESSION_WORKER_URL__;break;case`deviceLinking`:i=t.__SEAMS_DEVICE_LINKING_WORKER_URL__;break;default:}let a=typeof i==`string`&&i?i:e||ap(n);return ip(/^https?:\/\//i.test(a)?new URL(a):new URL(a,r),i).toString()}catch{try{return new URL(e||ap(n),r).toString()}catch{}return e||ap(n)}}function ip(e,t){if(typeof t==`string`&&t.length>0)return e;let n=st(),r=ot();if(!n||!r||e.searchParams.has(`v`))return e;try{let t=new URL(r);if(e.origin!==t.origin||!e.pathname.startsWith(t.pathname))return e;e.searchParams.set(`v`,n)}catch{}return e}function ap(e){switch(e){case`signer`:return`/sdk/workers/near-signer.worker.js`;case`ecdsaDerivationClient`:return`/sdk/workers/ecdsa-derivation-client.worker.js`;case`ecdsaPresignClient`:return`/sdk/workers/ecdsa-presign-client.worker.js`;case`ecdsaOnlineClient`:return`/sdk/workers/ecdsa-online-client.worker.js`;case`touchConfirm`:return`/sdk/workers/passkey-confirm.worker.js`;case`passkeyMpcExport`:return`/sdk/workers/passkey-mpc-export.worker.js`;case`passkeyMpcSession`:return`/sdk/workers/passkey-mpc-session.worker.js`;case`deviceLinking`:return`/sdk/workers/device-linking-key.worker.js`;default:throw Error(`Unsupported dedicated worker kind`)}}var X=class extends Error{name=`DeviceLinkingError`;constructor(e,t,n){super(e),this.code=t,this.phase=n}};let Z=function(e){return e.INVALID_QR_DATA=`INVALID_QR_DATA`,e.ACCOUNT_NOT_OWNED=`ACCOUNT_NOT_OWNED`,e.AUTHORIZATION_TIMEOUT=`AUTHORIZATION_TIMEOUT`,e.INSUFFICIENT_BALANCE=`INSUFFICIENT_BALANCE`,e.REGISTRATION_FAILED=`REGISTRATION_FAILED`,e.WALLET_UNLOCK_REQUIRED=`WALLET_UNLOCK_REQUIRED`,e.DELIVERY_RECOVERY_REQUIRED=`DELIVERY_RECOVERY_REQUIRED`,e.SESSION_EXPIRED=`SESSION_EXPIRED`,e.UNSUPPORTED=`UNSUPPORTED`,e}({});function op(e){let t=u(e);if(!t.ok)throw Error(`Device-link target email address is invalid: ${t.error.message}`);return t.value}function sp(e){try{return op(e),!0}catch{return!1}}async function cp(e,t){let n=e.find(lp.bind(null,t));if(!n)throw Error(`Enable the authentication method plugin before using it.`);switch(t){case`voiceid`:return await up(n.transcriptionModel??`citrinet`)}throw Error(`Authentication method plugin is unavailable in this Wallet host.`)}function lp(e,t){return t.kind===e}async function up(e){let t;try{t=await import(`/sdk/voiceid/host.js`)}catch(e){throw await dp(e)}if(!k(t)||t.hostApiVersion!==3||typeof t.createVoiceIdHostPlugin!=`function`)throw Error(`VoiceID is incompatible with this Wallet host. Install matching package versions.`);let n=t.createVoiceIdHostPlugin(e);if(!fp(n))throw Error(`VoiceID host implementation is invalid.`);return n}async function dp(e){let t=Error(`VoiceID could not load. Check your connection and retry. If it still fails, reload the page or use a passkey.`,{cause:e}),n;try{n=await fetch(`/sdk/voiceid/host.js`,{cache:`no-cache`,credentials:`omit`,signal:AbortSignal.timeout(1e4)}),await n.body?.cancel()}catch{return t}return n.status===404||n.status===410?Error(`VoiceID is missing from this Wallet host. Install @seams/voiceid on this Wallet host, or use a passkey.`,{cause:e}):t}function fp(e){return k(e)&&typeof e.unlock==`function`&&typeof e.activate==`function`&&typeof e.review==`function`}async function pp(e,t){return mp(e,t,3)}async function mp(e,t,n){let{walletId:r}=e;if(n===0)return Tp(r,`superseded`);let i;try{i=await t.resolveSelectedWalletAuthority(String(e.walletId))}catch{return Tp(e.walletId,`unavailable`)}switch(i.kind){case`missing_selection`:return{kind:`wallet_locked`};case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return Tp(e.walletId,`invalid`);case`resolved`:break}let{selection:a,authMethod:o,authority:s}=i;if(a.walletId!==e.walletId||a.walletAuthMethodId!==o.walletAuthMethodId||o.walletId!==e.walletId||o.walletAuthorityId!==s.authorityId||s.walletId!==e.walletId)return Tp(e.walletId,`invalid`);if(a.lockState===`locked`)return{kind:`wallet_locked`};if(o.status!==`active`||s.state!==`active`||o.kind===`voiceid`)return Tp(e.walletId,`invalid`);let c=await _p(t,{walletId:e.walletId,authorityId:s.authorityId,authMethodId:o.walletAuthMethodId});switch(c.kind){case`missing`:return Tp(e.walletId,`absent`);case`corrupt`:return Tp(e.walletId,`invalid`);case`persistence_unavailable`:return Tp(e.walletId,`unavailable`);case`upgrade_required`:return Tp(e.walletId,`upgrade_required`);case`found`:break}let{record:l,operationCredential:u}=c;if(!gp({walletId:e.walletId,authorization:l,operationCredential:u,selected:i}))return Tp(e.walletId,`invalid`);let d=t.nowMs();if(l.expiresAtMs<=d)return yp(e.walletId,o.kind,l,u);let f;try{f=await t.readStatus({authorization:l,operationCredential:u})}catch{return Tp(e.walletId,`unavailable`)}let p;try{p=await t.resolveSelectedWalletAuthority(e.walletId)}catch{return Tp(e.walletId,`unavailable`)}if(p.kind!==`resolved`||p.selection.lockState!==`unlocked`||p.selection.lockGeneration!==a.lockGeneration||p.selection.walletAuthMethodId!==a.walletAuthMethodId||p.authMethod.status!==`active`||p.authMethod.kind!==o.kind||p.authority.state!==`active`||!gp({walletId:r,authorization:l,operationCredential:u,selected:p}))return mp(e,t,n-1);let m=await _p(t,{walletId:r,authorityId:s.authorityId,authMethodId:o.walletAuthMethodId});return m.kind!==`found`||!Ue(m.record,l)||m.operationCredential.walletSessionId!==u.walletSessionId||m.operationCredential.token!==u.token?mp(e,t,n-1):l.expiresAtMs<=t.nowMs()?yp(r,o.kind,l,u):bp(f,l,u)?xp({walletId:e.walletId,authMethod:o.kind,authorization:l,operationCredential:u,status:f}):Tp(e.walletId,`invalid`)}function hp(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Wallet iframe exact session identity must be an object`);return Cp(e)}function gp(e){let{authorization:t,operationCredential:n,selected:r}=e;return t.walletId===e.walletId&&t.authorityId===r.authority.authorityId&&t.authMethodId===r.authMethod.walletAuthMethodId&&t.authorityDigestB64u===r.authority.authorityDigestB64u&&t.authorityRevocationEpoch===r.authority.revocationEpoch&&n.kind===`opaque_wallet_session_operation_credential_v1`&&n.token.trim().length>0&&String(t.authorizationId)!==String(n.walletSessionId)}async function _p(e,t){try{return await e.readExactActiveForWallet(t)}catch{return{kind:`persistence_unavailable`}}}function vp(e,t,n,r){return{walletId:e,authorizationId:n.authorizationId,walletSessionId:r.walletSessionId,authMethod:t,expiresAtMs:n.expiresAtMs}}function yp(e,t,n,r){return{kind:`expired_session`,...vp(e,t,n,r)}}function bp(e,t,n){if(e.walletSessionId!==n.walletSessionId||e.quotaId!==t.quotaId)return!1;switch(e.status){case`missing`:case`invalid`:return!0;case`active`:case`exhausted`:case`expired`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:return e.expiresAtMs===t.expiresAtMs&&Ue(e.authorization,t)}}function xp(e){switch(e.status.status){case`active`:return e.status.remainingUses<=0?Tp(e.walletId,`invalid`):{kind:`active_session`,status:`active`,...vp(e.walletId,e.authMethod,e.authorization,e.operationCredential)};case`exhausted`:return Tp(e.walletId,`exhausted`);case`expired`:return yp(e.walletId,e.authMethod,e.authorization,e.operationCredential);case`missing`:return{kind:`wallet_unlocked_without_signing_session`,walletId:e.walletId,reason:`not_found`,authorizationId:e.authorization.authorizationId,walletSessionId:e.operationCredential.walletSessionId,authMethod:e.authMethod};case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:return Tp(e.walletId,`superseded`);case`invalid`:return Tp(e.walletId,`invalid`)}}function Sp(e,t){return e.walletId===t.walletId&&e.authorizationId===t.authorizationId&&e.walletSessionId===t.walletSessionId}function Cp(e){let t=Tt(Reflect.get(e,`walletSessionId`));if(!t.ok)throw Error(`Wallet iframe walletSessionId is invalid`);let n=Reflect.get(e,`expiresAtMs`);if(!Dp(n))throw Error(`Wallet iframe expiresAtMs is invalid`);let r=Ep(Reflect.get(e,`walletId`)),i=Ot(Reflect.get(e,`authorizationId`));if(!i.ok)throw Error(`Wallet iframe authorizationId is invalid`);let a=Reflect.get(e,`authMethod`);if(!Gt(a))throw Error(`Wallet iframe authMethod is invalid`);return wp(i.value,t.value),{walletId:r,authorizationId:i.value,walletSessionId:t.value,authMethod:a,expiresAtMs:n}}function wp(e,t){if(String(e)===String(t))throw Error(`Wallet iframe authorization and Wallet Session IDs must be distinct`)}function Tp(e,t){return{kind:`wallet_unlocked_without_signing_session`,walletId:e,reason:t}}function Ep(e){let t=_(e);if(!t.ok)throw Error(`Wallet iframe walletId is invalid`);return t.value}function Dp(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}async function Op(e,t){let n;try{n=await t.resolveSelectedWalletAuthority(String(e.walletId))}catch{return{kind:`failed`,reason:`unavailable`}}let r=kp(e.walletId,n);if(r.kind!==`context`)return r;let i;try{i=await t.listWalletAuthMethodsV2ForWallet(String(e.walletId))}catch{return{kind:`failed`,reason:`unavailable`}}let a=new Set;for(let e of i){let n=await Ap({context:r,method:e,seenMethodIds:a},t);if(n.kind===`failed`)return n}return{kind:`reconciled`}}function kp(e,t){switch(t.kind){case`missing_selection`:return{kind:`skipped`};case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return{kind:`failed`,reason:`invalid`};case`resolved`:break}return t.selection.walletId!==e||t.authMethod.walletId!==e||t.authority.walletId!==e||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.walletAuthorityId!==t.authority.authorityId?{kind:`failed`,reason:`invalid`}:t.selection.lockState===`locked`?{kind:`skipped`}:t.authMethod.status!==`active`||t.authority.state!==`active`?{kind:`failed`,reason:`invalid`}:{kind:`context`,walletId:e,selected:t}}async function Ap(e,t){let{context:n,method:r,seenMethodIds:i}=e,a=String(r.walletAuthMethodId);if(i.has(a)||(i.add(a),r.walletId!==n.walletId))return{kind:`failed`,reason:`invalid`};if(r.walletAuthorityId!==n.selected.authority.authorityId||r.status!==`active`)return{kind:`skipped`};let o;try{o=await t.resolveWalletAuthorityForMethod(String(n.walletId),a)}catch{return{kind:`failed`,reason:`unavailable`}}if(o.kind!==`resolved`||!jp(o,n,r))return{kind:`failed`,reason:`invalid`};let s;try{s=await t.readExactActiveForWallet({walletId:n.walletId,authorityId:o.authority.authorityId,authMethodId:o.authMethod.walletAuthMethodId})}catch{return{kind:`failed`,reason:`unavailable`}}switch(s.kind){case`missing`:return{kind:`skipped`};case`upgrade_required`:case`corrupt`:return{kind:`failed`,reason:`invalid`};case`persistence_unavailable`:return{kind:`failed`,reason:`unavailable`};case`found`:break}if(!Mp(s.record,s.operationCredential,o))return{kind:`failed`,reason:`invalid`};let c;try{c=await t.readStatus({authorization:s.record,operationCredential:s.operationCredential})}catch{return{kind:`failed`,reason:`unavailable`}}let l=Np(c,s.record,s.operationCredential);if(l.kind===`failed`||l.kind===`skipped`)return l;if(!Ue(l.authorization,s.record)){try{if(await t.refreshExactWithOperationCredential({expected:s.record,record:l.authorization,operationCredential:s.operationCredential})===`superseded`)return{kind:`skipped`}}catch{return{kind:`failed`,reason:`unavailable`}}return{kind:`reconciled`}}return{kind:`reconciled`}}function jp(e,t,n){return e.selection.walletId===t.walletId&&e.authMethod.walletAuthMethodId===n.walletAuthMethodId&&e.authMethod.walletId===t.walletId&&e.authMethod.walletAuthorityId===t.selected.authority.authorityId&&e.authMethod.status===`active`&&e.authority.authorityId===t.selected.authority.authorityId&&e.authority.walletId===t.walletId&&e.authority.state===`active`&&e.authority.authorityDigestB64u===t.selected.authority.authorityDigestB64u&&e.authority.revocationEpoch===t.selected.authority.revocationEpoch}function Mp(e,t,n){try{return ze(t),e.walletId===n.authority.walletId&&e.authorityId===n.authority.authorityId&&e.authMethodId===n.authMethod.walletAuthMethodId}catch{return!1}}function Np(e,t,n){if(e.walletSessionId!==n.walletSessionId||e.quotaId!==t.quotaId)return{kind:`failed`,reason:`invalid`};switch(e.status){case`missing`:return{kind:`skipped`};case`invalid`:return{kind:`failed`,reason:`invalid`};case`active`:if(e.remainingUses<=0||e.quotaLifecycle!==`active`)return{kind:`failed`,reason:`invalid`};break;case`exhausted`:if(e.remainingUses!==0||e.quotaLifecycle!==`exhausted`)return{kind:`failed`,reason:`invalid`};break;case`expired`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:break}return e.authorization.walletId!==t.walletId||e.authorization.authorityId!==t.authorityId||e.authorization.authMethodId!==t.authMethodId||e.authorization.authorizationId!==t.authorizationId||e.authorization.quotaId!==t.quotaId||e.authorization.issuedAtMs!==t.issuedAtMs||e.authorization.expiresAtMs!==t.expiresAtMs||e.expiresAtMs!==e.authorization.expiresAtMs?{kind:`failed`,reason:`invalid`}:{kind:`reconciled`,authorization:e.authorization}}async function Pp(e,t,n){let r=String(e||``).trim();if(!r)throw Error(`Wallet iframe relayer URL is required`);return await t.read({relayerUrl:r,operationCredential:n.operationCredential},{walletSessionId:n.operationCredential.walletSessionId,quotaId:n.authorization.quotaId})}function Fp(e,t){return{resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),listWalletAuthMethodsV2ForWallet:K.listWalletAuthMethodsV2ForWallet.bind(K),resolveWalletAuthorityForMethod:K.resolveWalletAuthorityForMethod.bind(K),readExactActiveForWallet:q.readExactActiveForWallet.bind(q),readStatus:Pp.bind(null,e,t),refreshExactWithOperationCredential:q.refreshExactWithOperationCredential.bind(q),nowMs:Date.now}}function Ip(e){e.changed=!0}async function Lp(e){let t=String(e.preferences.getCurrentWalletId()||``).trim();if(t)return t;let n={changed:!1},r=e.preferences.onCurrentWalletChange(Ip.bind(null,n));try{let t=await e.auth.getRecentUnlocks();if(n.changed)return e.preferences.getCurrentWalletId()??void 0;let r=String(t.lastUsedAccount?.walletId||``).trim(),i=t.walletIds.map(e=>String(e).trim()).filter(Boolean),a=r||(i.length===1?i[0]:void 0);return a&&e.preferences.setCurrentWallet(V(a)),a}finally{r()}}async function Rp(e,t,n){let r;switch(t.wallet.kind){case`current`:r=t.authenticationRead===`restore`?await Lp(e):e.preferences.getCurrentWalletId()??void 0;break;case`exact`:if(r=t.wallet.walletId.trim(),!r)throw Error(`Wallet iframe exact session walletId is invalid`);break}if(!r)return{kind:`wallet_locked`};let i=Fp(e.configs.network.relayer.url,n),a=await Op({walletId:V(r)},i);return a.kind===`failed`?{kind:`wallet_unlocked_without_signing_session`,walletId:V(r),reason:a.reason}:await pp({walletId:V(r)},i)}var zp=class{lifecycle=`active`;refresh={kind:`idle`};invalidationRevision=0;activeOperations=0;externalExpiryTimer=null;pendingObservations=new Map;unsubscribeAuthority;unsubscribeSelection;constructor(e,t,n,r){this.runtime=e,this.post=t,this.expiredSessions=n,this.readSession=r,this.unsubscribeAuthority=yn.onWalletAuthorityChange(this.invalidate.bind(this)),this.unsubscribeSelection=e.preferences.onCurrentWalletChange(this.invalidate.bind(this))}dispose(){this.externalExpiryTimer!==null&&clearTimeout(this.externalExpiryTimer),this.lifecycle=`disposed`,this.unsubscribeAuthority(),this.unsubscribeSelection()}beginOperation(){this.assertActive(),this.activeOperations+=1}endOperation(){--this.activeOperations,this.lifecycle===`active`&&this.activeOperations===0&&this.refresh.kind===`pending`&&this.requestRefresh()}onLifecycleEvent(e){if(this.lifecycle===`disposed`)return;let t=bt();e.event===`signing_session.expired`&&(this.invalidationRevision+=1),this.post({type:`SDK_LIFECYCLE_EVENT`,payload:{revision:t,event:e}}),e.event===`signing_session.expired`&&this.requestRefresh()}publishCurrentSession(){return this.observe({authenticationRead:`current`,wallet:{kind:`current`}},this.publishSnapshot.bind(this))}async observe(e,t){for(let n=0;n<3;n+=1){this.assertActive();let n=this.invalidationRevision,r=yn.getWalletAuthorityRevision(),i={changed:!1},a=this.runtime.preferences.onCurrentWalletChange(Ip.bind(null,i));try{let{revision:a,state:o,session:s}=await this.readObservation(e,r);if(this.assertActive(),i.changed&&s.authentication.kind!==`external_authenticated`&&this.runtime.preferences.getCurrentWalletId()===null){t({revision:bt(),walletId:null,state:{kind:`wallet_locked`},session:dt()});return}if(i.changed||n!==this.invalidationRevision||r!==yn.getWalletAuthorityRevision())continue;t({revision:a,walletId:s.authentication.kind===`external_authenticated`?s.authentication.walletId:e.wallet.kind===`exact`?V(e.wallet.walletId):this.runtime.preferences.getCurrentWalletId(),state:this.projectExpiry(o),session:s});return}finally{a()}}throw Error(`Wallet authority changed repeatedly during session observation`)}readObservation(e,t){let n=this.runtime.preferences.getCurrentWalletId(),r=e.wallet.kind===`exact`?e.wallet.walletId:n,i=JSON.stringify([e.authenticationRead,r,n,t,this.invalidationRevision]),a=this.pendingObservations.get(i);if(a)return a;let o=this.resolveObservation(e).finally(this.finishObservation.bind(this,i));return this.pendingObservations.set(i,o),o}async resolveObservation(e){let t=bt(),n=Ja.forHostObservation(),r=await this.runtime.readExternalSession(e.wallet.kind===`exact`?e.wallet.walletId:void 0);if(r?.authentication.kind===`external_authenticated`)return{revision:t,state:{kind:`external_read`,walletId:r.authentication.walletId,externalSessionId:r.authentication.sessionId,expiresAtMs:r.authentication.expiresAtMs},session:r};let i=await Rp(this.runtime,e,n);return{revision:t,state:i,session:i.kind===`wallet_locked`?dt():await this.readSession(i.walletId,n)}}finishObservation(e){this.pendingObservations.delete(e)}projectExpiry(e){return e.kind!==`active_session`||!this.expiredSessions.get(e.walletId)?.has(e.walletSessionId)?e:{kind:`expired_session`,walletId:e.walletId,authorizationId:e.authorizationId,walletSessionId:e.walletSessionId,authMethod:e.authMethod,expiresAtMs:e.expiresAtMs}}assertActive(){if(this.lifecycle===`disposed`)throw Error(`Wallet session observer is disposed`)}invalidate(){this.lifecycle!==`disposed`&&(this.invalidationRevision+=1,this.requestRefresh())}requestRefresh(){if(this.refresh.kind===`running`){this.refresh.pending=!0;return}if(this.activeOperations>0){this.refresh={kind:`pending`};return}this.refresh={kind:`running`,pending:!1},this.refreshSession().catch(this.reportRefreshFailure.bind(this))}async refreshSession(){try{do{if(this.refresh.kind!==`running`)return;this.refresh.pending=!1;try{await this.publishCurrentSession()}catch(e){this.reportRefreshFailure(e)}}while(this.lifecycle===`active`&&this.refresh.kind===`running`&&this.refresh.pending)}finally{this.refresh={kind:`idle`}}}publishSnapshot(e){this.assertActive(),this.externalExpiryTimer!==null&&clearTimeout(this.externalExpiryTimer),this.externalExpiryTimer=null,e.session.authentication.kind===`external_authenticated`&&(this.externalExpiryTimer=setTimeout(this.requestRefresh.bind(this),Math.max(1,e.session.authentication.expiresAtMs-Date.now()))),this.refresh.kind===`running`?this.refresh.pending=!1:this.refresh.kind===`pending`&&(this.refresh={kind:`idle`}),this.post({type:`SESSION_CHANGED`,payload:e})}reportRefreshFailure(e){this.lifecycle===`active`&&console.warn(`[WalletIframeHost] Session refresh failed:`,e)}};function Bp(e){let t=e.override?.ttlMs??e.defaults.ttlMs,n=typeof t==`number`?Math.floor(t):Math.floor(Number(t)||0),r=be({requestedRemainingUses:e.override?.remainingUses??e.defaults.remainingUses??xe});return!(n>0)||r===null?{kind:`disabled`,ttlMs:0,unlockRemainingUses:null}:{kind:`enabled`,ttlMs:n,unlockRemainingUses:r}}async function Vp(e){try{let t=e.runtime.activationReceipt.normalSigning.scope,n=_d({routerAbState:e.runtime.activationReceipt.normalSigning}),r=await Na({ecdsaThresholdKeyId:t.ecdsa_threshold_key_id,signingRootId:t.signing_root_id,signingRootVersion:t.signing_root_version});if(Ld(e.runtime)!==e.runtime)return;let i=ud({relayerUrl:e.relayerUrl,keyHandle:Wi(r),ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,clientVerifyingShareB64u:n.clientVerifier33B64u,clientSigningMaterial:dd(e.runtime.holderHandleId),thresholdEcdsaPublicKeyB64u:n.thresholdVerifier33B64u,relayerVerifyingShareB64u:n.serverVerifier33B64u,credential:{kind:`wallet_session_opaque`,walletSessionToken:e.operationCredential.token,home:e.operationCredential.home,ownershipGeneration:e.operationCredential.ownershipGeneration},authorization:{kind:`reusable_wallet_session`,wallet_session_id:e.operationCredential.walletSessionId},materialActivation:oi(e.runtime.materialActivation),routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:t,ceremonyExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:Date.now()+bn},workerCtx:e.workerCtx});Rl(`evm-family`,{event:`ecdsa_linked_device_prefill`,scheduled:i.scheduled,reason:i.reason,depth:i.depth,targetDepth:i.targetDepth})}catch{Rl(`evm-family`,{event:`ecdsa_linked_device_prefill`,scheduled:!1,reason:`unexpected_error`})}}var Hp=class extends Error{constructor(e){super(`[OwnerLaneScope] ${e}`),this.name=`OwnerLaneScopeIntegrityError`}};function Up(e){return{walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.walletAuthMethodId}}function Wp(e){let t=String(e.providerSubjectId||``).trim();if(!t)throw new Hp(`active Email OTP method has no exact local factor`);let n=hi({walletId:e.authMethod.walletId,factor:{kind:`email_otp`,provider:t.startsWith(`google:`)?`google`:`email`,providerUserId:t},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:e.authMethod.emailHashHex},bindingId:e.authMethod.walletAuthMethodId});if(!n)throw new Hp(`active Email OTP method has no exact local factor`);return n}function Gp(e){let t=e.localMethods.filter(t=>t.kind===`email_otp`&&t.status===`active`&&t.walletId===e.authMethod.walletId&&t.emailHashHex===e.authMethod.emailHashHex),n=t[0],r=n?hi(n.authority):null;if(t.length!==1||!r||r.walletId!==e.authMethod.walletId||r.bindingId!==e.authMethod.walletAuthMethodId||r.verifier.emailHashHex!==e.authMethod.emailHashHex)throw new Hp(`active Email OTP method has no exact local factor`);return r}async function Kp(e){let t=String(e.authMethod.walletId);try{return Gp({authMethod:e.authMethod,localMethods:await e.stores.listWalletAuthMethodsForWallet(t)})}catch(n){if(!e.stores.readEmailOtpProviderSubjectForWallet)throw n;let r=await e.stores.readEmailOtpProviderSubjectForWallet(t);if(!r)throw n;return Wp({authMethod:e.authMethod,providerSubjectId:r})}}function qp(e){if(e.authority.walletId!==e.authMethod.walletId||e.authority.bindingId!==e.authMethod.walletAuthMethodId)throw new Hp(`active wallet auth method does not have an exact factor authority binding`);return e.authority}async function Jp(e){return e.authMethod.kind===`passkey`?qp({authMethod:e.authMethod,authority:Up(e.authMethod)}):e.authMethod.kind===`voiceid`?si({walletId:e.authMethod.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,deviceKeyId:e.authMethod.deviceKeyId}):qp({authMethod:e.authMethod,authority:await Kp({authMethod:e.authMethod,stores:e.stores})})}function Yp(e){return{auth:{kind:`passkey`,rpId:wa(e.authMethod.rpId),credentialIdB64u:e.authMethod.credentialIdB64u},signerSlot:e.signerSlot}}function Xp(e){return{auth:{kind:`passkey`,rpId:wa(e.authMethod.rpId),credentialIdB64u:e.authMethod.credentialIdB64u},keyFamily:`ecdsa`}}function Zp(e){if(e.factorAuthority.walletId!==e.authMethod.walletId||e.factorAuthority.bindingId!==e.authMethod.walletAuthMethodId||e.factorAuthority.verifier.emailHashHex!==e.authMethod.emailHashHex||e.authorityRef.walletId!==e.authMethod.walletId||e.authorityRef.walletAuthMethodId!==e.authMethod.walletAuthMethodId)throw new Hp(`linked Email OTP authority does not match the selected V2 method`);return{auth:{kind:`email_otp`,providerSubjectId:String(e.factorAuthority.factor.providerUserId)},ownerAuthority:{walletAuthMethodId:e.authorityRef.walletAuthMethodId,authorityDigest:e.authorityRef.authorityDigest}}}async function Qp(e){let t=await e.stores.getWalletPasskeyAuthenticator({walletId:String(e.authMethod.walletId),credentialId:e.authMethod.credentialIdB64u});if(!t||t.credentialId!==e.authMethod.credentialIdB64u)throw new Hp(`active Passkey auth method has no exact local authenticator`);let n=Ai(t.signerSlot,{min:1});if(n===null)throw new Hp(`local authenticator signer slot is invalid`);return Yp({authMethod:e.authMethod,signerSlot:n})}async function $p(e){if(e.authMethod.kind===`passkey`)return await Qp({authMethod:e.authMethod,stores:e.stores});if(e.authMethod.kind===`voiceid`){let t=await U({authority:si({walletId:e.authMethod.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,deviceKeyId:e.authMethod.deviceKeyId})});return{auth:{kind:`voiceid`,walletAuthMethodId:e.authMethod.walletAuthMethodId,deviceKeyId:e.authMethod.deviceKeyId},ownerAuthority:{walletAuthMethodId:t.walletAuthMethodId,authorityDigest:t.authorityDigest}}}let t=await Kp({authMethod:e.authMethod,stores:e.stores}),n=await U({authority:t});return{auth:{kind:`email_otp`,providerSubjectId:String(t.factor.providerUserId)},ownerAuthority:{walletAuthMethodId:n.walletAuthMethodId,authorityDigest:n.authorityDigest}}}function em(e){let t=e.available.capability,n=t.manifest.signer;if(!n.scope.targetMemberships.some(t=>H(t)===H(e.chainTarget)))return null;let r=n.registeredPublicFacts,i={capability:t,key:Pa({walletId:n.walletId,ecdsaThresholdKeyId:t.manifest.durableMaterial.roleLocalBinding.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,participantIds:r.participantIds,thresholdOwnerAddress:r.thresholdOwnerAddress}),materialActivation:t.manifest.activation.materialActivation,publicFacts:r,curve:`ecdsa`,chainTarget:e.chainTarget,source:`canonical_capability`},a=e.available.kind===`authorized_evm_family_ecdsa_signing_capability`?e.available.authorization:null;if(Si(t.authority)){let e={kind:`passkey`,rpId:wa(t.authority.verifier.rpId),credentialIdB64u:t.authority.factor.credentialIdB64u},o=Oa({walletId:n.walletId,publicFacts:r,authBinding:Da(e)});return a?{...i,auth:e,resolvedKey:o,state:`ready`,authorization:a,remainingUses:a.runtime.remainingUses,expiresAtMs:a.runtime.expiresAtMs}:{...i,auth:e,resolvedKey:o,state:`deferred`}}let o;if(_i(t.authority))o={kind:`voiceid`,walletAuthMethodId:t.authority.bindingId,deviceKeyId:t.authority.factor.deviceKeyId};else if(bi(t.authority))o={kind:`email_otp`,providerSubjectId:t.authority.factor.providerUserId};else return null;return a?{...i,auth:o,state:`ready`,authorization:a,remainingUses:a.runtime.remainingUses,expiresAtMs:a.runtime.expiresAtMs}:{...i,auth:o,state:`deferred`}}function tm(e){throw Error(`Unsupported persisted Ed25519 auth method: ${String(e)}`)}async function nm(e,t,n,r){return await cm(e,{...t,ecdsaChainTargets:n,requiredEcdsaCapability:`sign`},r,`all`)}async function rm(e,t,n){return await cm(e,{walletId:t.walletId,authMethod:Xt(t.ownerScope.auth),ownerScope:t.ownerScope,ecdsaChainTargets:t.ecdsaChainTargets,requiredEcdsaCapability:t.requiredEcdsaCapability,...t.nowMs===void 0?{}:{nowMs:t.nowMs}},n,`all`)}async function im(e,t,n){if(t.curve===`ecdsa`){let{curve:r,...i}=t,a=new Map;for(let e of[...t.ecdsaChainTargets,...n])a.set(H(e),e);return await cm(e,{...i,ecdsaChainTargets:[...a.values()],requiredEcdsaCapability:`sign`},new Ja,`ecdsa`)}let{curve:r,...i}=t;return await nm(e,i,[],new Ja)}function am(e){return String(e.thresholdSessionIds?.ed25519||``).trim().length>0}function om(e,t){let n=e.ecdsaRestore?.chainTarget;if(!n)return!1;let r=H(n);for(let e of t)if(r===H(e))return!0;return!1}function sm(e,t){let n=[];for(let r of e)`recordKind`in r||am(r)&&(t.length>0&&!om(r,t)||n.push(r));return n}async function cm(e,t,n,r){let i=String(V(t.walletId)).trim();return await qd({...t,walletId:i,ecdsaChainTargets:t.ecdsaChainTargets},{listPublicCapabilityReferences:r===`all`&&e.ed25519YaoPublicCapabilityLanes?e.ed25519YaoPublicCapabilityLanes.listLanes.bind(e.ed25519YaoPublicCapabilityLanes):void 0,isPublicCapabilityActive:e.isEd25519YaoPublicCapabilityActive,readActiveWalletSessionAuthorization:r===`all`?e.readActiveWalletSessionAuthorization?.bind(null,n):void 0,listSealedRecordsForWallet:async({walletId:e,filter:n})=>{if(r===`ecdsa`)return[];let i=async n=>{if(n===`voiceid`)return[];let r=await hs({walletId:e,filter:{authMethod:n,curve:`ed25519`}});switch(n){case z.passkey:return r;case z.emailOtp:{let n=sm(await mc({walletId:e,filter:{authMethod:z.emailOtp,curve:`ecdsa`}}),t.ecdsaChainTargets);return[...r,...n]}default:return tm(n)}};if(n.authMethod)return await i(n.authMethod);let[a,o]=await Promise.all([i(z.emailOtp),i(z.passkey)]);return[...a,...o]},listCanonicalEcdsaLanesForWallet:async({walletId:r})=>{let i=[],a=new Set,o=await e.listEcdsaSigningCapabilitiesForWallet({walletId:r,chainTargets:t.ecdsaChainTargets,...t.authMethod?{authMethod:t.authMethod}:{}},n);for(let e of o)for(let n of t.ecdsaChainTargets){let t=em({available:e,chainTarget:n});if(!t)continue;let r=Kd(t);!r||a.has(r)||(a.add(r),i.push(t))}return i},listActiveWalletAuthorityEcdsaLanesForWallet:async({walletId:n,chainTargets:r})=>(await Promise.all(r.map(async r=>{let i=await Vd({ports:e.activeWalletAuthorityEcdsaRuntimeReadPorts,input:{walletId:V(n),chainTarget:r,requiredCapability:t.requiredEcdsaCapability}});return i.kind===`resolved`&&i.lane?i.lane:null}))).filter(e=>e!==null).map(Xd)})}function lm(e,t){let n=String(e||``).trim();if(!n)throw Error(`[WalletSessionStatus] ${t} is required`);return n}function um(e){let t=Tt(e.walletSessionId),n=Ct(e.quotaId);return!t.ok||!n.ok?null:{walletSessionId:t.value,quotaId:n.value}}function dm(e){let t=um(e.authorization);if(!t)throw Error(`[WalletSessionStatus] canonical Wallet Session identity is invalid`);return{kind:`wallet_session_status_check`,owner:e.owner,authorization:t}}function fm(e){return{curve:`ed25519`,walletId:V(e)}}function pm(e){return e.walletId}function mm(e){return`${e.curve}:${pm(e)}`}function hm(e){return`${e.walletSessionId}:${e.quotaId}`}function gm(e){let t=String(e.walletSessionId);switch(e.status){case`active`:return{sessionId:t,status:`active`,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs};case`exhausted`:return{sessionId:t,status:`exhausted`,remainingUses:0,expiresAtMs:e.expiresAtMs};case`expired`:return{sessionId:t,status:`expired`,expiresAtMs:e.expiresAtMs};case`missing`:case`superseded`:return{sessionId:t,status:`not_found`,statusCode:e.status};case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:return{sessionId:t,status:`unavailable`,statusCode:e.status,expiresAtMs:e.expiresAtMs};case`invalid`:return{sessionId:t,status:`status_unknown`,statusCode:`invalid_wallet_session_status`};default:throw Error(`[WalletSessionStatus] unsupported canonical status`)}}async function _m(e,t){return await e.getAvailableStatus(t).catch(()=>null)}function vm(e,t){if(!t||t.status===`status_unknown`)return e;if(t.status!==`active`)return{...e,...t,sessionId:e.sessionId};let n=Math.max(0,Math.floor(Number(t.remainingUses)||0)),r=Math.floor(Number(e.expiresAtMs)||0),i=Math.floor(Number(t.expiresAtMs)||0);return{...e,status:`active`,remainingUses:n,expiresAtMs:r>0&&i>0?Math.min(r,i):r||i,...t.authMethod?{authMethod:t.authMethod}:{},...t.retention?{retention:t.retention}:{}}}function ym(e){return dm(e)}function bm(e){return async t=>{let n=t.authorization,r=await e.readAuthorization(t.owner.walletId);switch(r.kind){case`missing`:case`corrupt`:case`persistence_unavailable`:case`upgrade_required`:return null;case`found`:break;default:return r}if(!xm(n,t.owner.walletId,r))return null;let i=String(e.relayerUrl||``).trim();if(!i)return null;let a=await qa({relayerUrl:i,operationCredential:r.operationCredential}).read(n).catch(()=>null);return a?gm(a):null}}function xm(e,t,n){return n.record.walletId===t&&n.record.quotaId===e.quotaId&&n.operationCredential.walletSessionId===e.walletSessionId}function Sm(e,t,n){let r=String(e||``).trim();if(!r)throw Error(`[signer-core-command] ${t} is required`);if(F(r).length!==n)throw Error(`[signer-core-command] ${t} must decode to ${n} bytes`);return r}function Cm(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`[signer-core-command] ${t} must be an object`);return e}function wm(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(`[signer-core-command] ${n} fields are invalid`)}function Tm(e,t){if(typeof e!=`string`)throw Error(`[signer-core-command] ${t} must be a string`);let n=e.trim();if(!n)throw Error(`[signer-core-command] ${t} is required`);return n}function Em(e){return Sm(e,`derivationClientSharePublicKey33B64u`,33)}function Dm(e){return Sm(e,`relayerPublicKey33B64u`,33)}function Om(e,t){return Sm(e,t,33)}function km(e){let t=String(e||``).trim();if(!/^0x[0-9a-fA-F]{40}$/.test(t))throw Error(`[signer-core-command] ethereumAddress must be 0x-prefixed 20-byte hex`);return t}function Am(e){let t=Cm(e,`ECDSA pending state blob`);if(wm(t,[`kind`,`curve`,`encoding`,`producer`,`stateBlobB64u`],`ECDSA pending state blob`),Reflect.get(t,`kind`)!==`ecdsa_role_local_pending_state_blob_v1`||Reflect.get(t,`curve`)!==`secp256k1`||Reflect.get(t,`encoding`)!==`base64url`||Reflect.get(t,`producer`)!==`signer_core`)throw Error(`[signer-core-command] invalid ECDSA pending state blob envelope`);return{kind:`ecdsa_role_local_pending_state_blob_v1`,curve:`secp256k1`,encoding:`base64url`,producer:`signer_core`,stateBlobB64u:Tm(Reflect.get(t,`stateBlobB64u`),`pendingStateBlob.stateBlobB64u`)}}function jm(e){if(e.kind!==`ecdsa_role_local_state_blob_v1`||e.curve!==`secp256k1`||e.encoding!==`base64url`||e.producer!==`signer_core`)throw Error(`[signer-core-command] invalid ECDSA ready state blob envelope`);return e}function Mm(e){return{kind:e.kind,algorithm:e.algorithm,context:{applicationBindingDigestB64u:e.context.applicationBindingDigestB64u},participants:{clientParticipantId:e.participants.clientParticipantId,relayerParticipantId:e.participants.relayerParticipantId,participantIds:[...e.participants.participantIds]},secretSource:{kind:`threshold_prf_x_client_base`,xClientBaseB64u:Sm(e.secretSource.xClientBaseB64u,`secretSource.xClientBaseB64u`,32)}}}function Nm(e){if(e.clientBootstrap.participantId!==1)throw Error(`[signer-core-command] ECDSA client bootstrap participantId must be 1`);let t=Em(e.clientBootstrap.derivationClientSharePublicKey33B64u);return{pendingStateBlob:Am(e.pendingStateBlob),clientBootstrap:{contextBinding32B64u:Sm(e.clientBootstrap.contextBinding32B64u,`contextBinding32B64u`,32),derivationClientSharePublicKey33B64u:t,clientShareRetryCounter:e.clientBootstrap.clientShareRetryCounter,participantId:1},publicFacts:{derivationClientSharePublicKey33B64u:Em(e.publicFacts.derivationClientSharePublicKey33B64u),clientVerifyingShareB64u:Om(e.publicFacts.clientVerifyingShareB64u,`clientVerifyingShareB64u`)}}}function Pm(e){return{kind:e.kind,pendingStateBlob:e.pendingStateBlob,relayerPublicIdentity:{relayerKeyId:e.relayerPublicIdentity.relayerKeyId,relayerPublicKey33B64u:e.relayerPublicIdentity.relayerPublicKey33B64u,groupPublicKey33B64u:e.relayerPublicIdentity.groupPublicKey33B64u,ethereumAddress:e.relayerPublicIdentity.ethereumAddress,relayerShareRetryCounter:e.relayerPublicIdentity.relayerShareRetryCounter}}}function Fm(e){return{stateBlob:jm(e.stateBlob),publicFacts:{contextBinding32B64u:Sm(e.publicFacts.contextBinding32B64u,`contextBinding32B64u`,32),derivationClientSharePublicKey33B64u:Em(e.publicFacts.derivationClientSharePublicKey33B64u),clientVerifyingShareB64u:Om(e.publicFacts.clientVerifyingShareB64u,`clientVerifyingShareB64u`),relayerPublicKey33B64u:Dm(e.publicFacts.relayerPublicKey33B64u),groupPublicKey33B64u:Om(e.publicFacts.groupPublicKey33B64u,`groupPublicKey33B64u`),ethereumAddress:km(e.publicFacts.ethereumAddress)}}}function Im(e){return{ok:!1,code:`unavailable`,message:e}}function Lm(e,t){return{ok:!1,failure:`invocation`,code:e,message:t}}function Rm(e,t){return{ok:!1,failure:`command`,code:e,message:t}}function zm(e){let t=F(e),n=new ArrayBuffer(t.byteLength);return new Uint8Array(n).set(t),n}function Bm(e){return{challenge:zm(e.challengeB64u),rp:{id:e.rpId,name:e.rpId},user:{id:zm(e.user.idB64u),name:e.user.name,displayName:e.user.displayName},pubKeyCredParams:e.pubKeyCredParams.map(e=>({type:e.type,alg:e.alg})),authenticatorSelection:e.authenticatorSelection,timeout:e.timeoutMs,attestation:e.attestation,excludeCredentials:e.excludeCredentials.map(e=>({type:e.type,id:zm(e.id)})),extensions:{prf:{eval:{first:F(e.extensions.prf.eval.firstB64u),second:F(e.extensions.prf.eval.secondB64u)}}}}}function Vm(e){return/wasm (initialization|initialize|instantiation)|webassembly|module_or_path|failed to (load|compile|instantiate) wasm|derivation client wasm initialization failed/i.test(e)}function Hm(e){let t=Bu(e),n=Fu(e),r=L(e);if(n===`ECDSA_DERIVATION_WASM_INIT_FAILURE`||Vm(r))return Lm(`native_binding_failure`,r);switch(t){case`TIMEOUT`:return Lm(`timeout`,r);case`WORKER_POSTMESSAGE_ERROR`:case`WORKER_PROTOCOL_ERROR`:case`WORKER_RUNTIME_ERROR`:return Lm(`worker_transport_failure`,r);default:break}return/timed out/i.test(r)?Lm(`timeout`,r):/postMessage|worker runtime|worker response|worker protocol|Malformed worker|Unknown worker/i.test(r)?Lm(`worker_transport_failure`,r):null}function Um(e){let t=L(e);return/relayer|public identity|group public key|ethereum address|threshold public key/i.test(t)?Rm(`public_identity_mismatch`,t):Rm(`invalid_pending_state`,t)}function Wm(e){return{kind:`durable_record_store`,async loadEcdsaRoleLocalReadyRecord(t){let n=zi(t);try{let r=await e.getAppState(n);if(r!=null){let e=Mi(r);return Ui({record:e,input:t})?{ok:!0,value:{kind:`found`,record:e}}:{ok:!0,value:{kind:`malformed`,cleanup:{...t,reason:`Stored ECDSA role-local record identity does not match lookup input`},message:`Stored ECDSA role-local record identity does not match lookup input`}}}return{ok:!0,value:{kind:`not_found`}}}catch(e){let n=L(e);return{ok:!0,value:{kind:`malformed`,cleanup:{...t,reason:n},message:n}}}},async persistEcdsaRoleLocalReadyRecord(t){try{let n=Mi(t.record);return Ui({record:n,input:t.storageKeyFacts})?(await e.setAppState(zi(t.storageKeyFacts),Hi(n)),{ok:!0,value:{kind:`persisted`}}):{ok:!1,code:`invalid_record`,message:`ECDSA role-local ready record identity does not match storageKeyFacts`}}catch(e){return{ok:!1,code:`invalid_record`,message:L(e)}}},async cleanupMalformedEcdsaRoleLocalRecord(t){try{return await e.setAppState(zi(t),null),{ok:!0,value:{kind:`deleted`}}}catch(e){return{ok:!1,code:`unavailable`,message:L(e)}}}}}function Gm(){return{kind:`secure_secret_store`,async seal(){return Im(`Browser secure secret store is not wired yet`)},async unseal(){return Im(`Browser secure secret store is not wired yet`)},async delete(){return Im(`Browser secure secret store is not wired yet`)}}}function Km(e){return e instanceof DOMException?e.name===`NotAllowedError`?{ok:!1,code:`not_allowed`,message:e.message||`Passkey operation was not allowed`}:{ok:!1,code:`platform_error`,message:e.message||e.name}:{ok:!1,code:`platform_error`,message:e instanceof Error?e.message:String(e)}}function qm(){return{prf:{eval:{first:tt,second:$e}}}}function Jm(){return{ok:!1,code:`prf_unavailable`,message:`Required passkey PRF.first output is unavailable`}}function Ym(e){return/Missing PRF/i.test(L(e))?Jm():null}function Xm(e){return!!(e&&typeof e==`object`&&`rawId`in e&&`response`in e&&typeof e.getClientExtensionResults==`function`)}async function Zm(e,t,n){return e===`create`?n.create({publicKey:t}):n.get({publicKey:t})}function Qm(e){return{kind:`authenticator`,async run(t){if(!e)return{ok:!1,code:`unavailable`,message:`navigator.credentials is unavailable`};try{switch(t.kind){case`create_passkey`:{let n=t.registrationOptions,r=await Zm(`create`,Bm(n),e);if(!Xm(r))return{ok:!1,code:`invalid_credential`,message:`Passkey creation returned an invalid credential`};let i;try{i=xc({credential:r})}catch(e){if(t.requirePrfFirst){let t=Ym(e);if(t)return t}throw e}let a=Sc(i);if(t.requirePrfFirst&&!a)return Jm();if(t.requirePrfFirst){let e=a||``;return{ok:!0,operation:`create_passkey`,requirePrfFirst:!0,credential:i,credentialIdB64u:i.rawId,rawIdB64u:i.rawId,rpId:wa(n.rpId),prf:{kind:`required`,prfFirstB64u:e}}}return{ok:!0,operation:`create_passkey`,requirePrfFirst:!1,credential:i,credentialIdB64u:i.rawId,rawIdB64u:i.rawId,rpId:wa(n.rpId),prf:a?{kind:`available_without_requirement`,prfFirstB64u:a}:{kind:`not_requested_or_unavailable`}}}case`get_passkey`:{let n=await Zm(`get`,{rpId:t.rpId,challenge:zm(t.challengeB64u),allowCredentials:[{type:`public-key`,id:zm(t.credentialIdB64u)}],userVerification:`preferred`,extensions:qm()},e);if(!Xm(n))return{ok:!1,code:`invalid_credential`,message:`Passkey assertion returned an invalid credential`};let r;try{r=wc({credential:n})}catch(e){if(t.requirePrfFirst){let t=Ym(e);if(t)return t}throw e}let i=Sc(r);if(t.requirePrfFirst&&!i)return Jm();if(t.requirePrfFirst){let e=i||``;return{ok:!0,operation:`get_passkey`,requirePrfFirst:!0,credential:r,credentialIdB64u:r.rawId,rawIdB64u:r.rawId,rpId:t.rpId,prf:{kind:`required`,prfFirstB64u:e}}}return{ok:!0,operation:`get_passkey`,requirePrfFirst:!1,credential:r,credentialIdB64u:r.rawId,rawIdB64u:r.rawId,rpId:t.rpId,prf:i?{kind:`available_without_requirement`,prfFirstB64u:i}:{kind:`not_requested_or_unavailable`}}}}}catch(e){return Km(e)}}}}function $m(e){return{kind:`signer_crypto`,async createRouterAbEcdsaRegistrationCeremony(t){if(!e)throw Error(`ECDSA derivation client worker context is unavailable`);return $u({command:t,workerCtx:e})},async verifyRouterAbEcdsaRegistrationClientProofs(t){if(!e)throw Error(`ECDSA derivation client worker context is unavailable`);return Yu({command:t,workerCtx:e})},async persistInitialCanonicalEcdsaActivation(t){if(!e)throw Error(`ECDSA derivation client worker context is unavailable`);return Qu({command:t,workerCtx:e})},async finalizeRouterAbEcdsaRegistrationActivation(t){if(!e)throw Error(`ECDSA derivation client worker context is unavailable`);return Ku({command:t,workerCtx:e})},async closeRouterAbEcdsaRegistrationCeremony(t){if(!e)throw Error(`ECDSA derivation client worker context is unavailable`);return td({command:t,workerCtx:e})},async prepareEcdsaClientBootstrap(t){if(!e)return Lm(`unavailable`,`ECDSA client bootstrap worker context is unavailable`);try{return{ok:!0,value:Nm(await Ju({command:Mm(t),workerCtx:e}))}}catch(e){let t=L(e);return t.includes(`unsupported ECDSA bootstrap secret source`)?Rm(`unsupported_secret_source`,t):Hm(e)||Rm(`crypto_failure`,t)}},async finalizeEcdsaClientBootstrap(t){if(t.pendingStateBlob.kind!==`ecdsa_role_local_pending_state_blob_v1`||t.pendingStateBlob.curve!==`secp256k1`||t.pendingStateBlob.encoding!==`base64url`||t.pendingStateBlob.producer!==`signer_core`)return Rm(`invalid_pending_state`,`ECDSA client bootstrap pending blob envelope is invalid`);if(!e)return Lm(`unavailable`,`ECDSA client bootstrap worker context is unavailable`);try{return{ok:!0,value:Fm(await Zu({command:Pm(t),workerCtx:e}))}}catch(e){return Hm(e)||Um(e)}},async storeEcdsaRoleLocalSigningMaterial(t){if(t.stateBlob.kind!==`ecdsa_role_local_state_blob_v1`||t.stateBlob.curve!==`secp256k1`||t.stateBlob.encoding!==`base64url`||t.stateBlob.producer!==`signer_core`)return Rm(`invalid_ready_state`,`ECDSA role-local ready blob envelope is invalid`);if(!e)return Lm(`unavailable`,`ECDSA role-local material worker context is unavailable`);try{let n=await od({materialHandle:t.handle.materialHandle,bindingDigest:t.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e});return{ok:!0,value:{handle:{kind:`ecdsa_role_local_worker_handle_v1`,materialHandle:Ii(n.materialHandle),durableMaterialRef:Fi(n.materialHandle),bindingDigest:Vi(n.bindingDigest)}}}}catch(e){return Hm(e)||Rm(`crypto_failure`,L(e))}}}}function eh(e){return{kind:`http_transport`,async request(t){if(!e)return{ok:!1,code:`network_error`,message:`fetch is unavailable`};let n=new AbortController,r=t.timeoutMs&&t.timeoutMs>0?setTimeout(()=>n.abort(),t.timeoutMs):null;try{let r=await e(t.url,{method:t.method,headers:t.headers,body:t.body==null?void 0:JSON.stringify(t.body),signal:n.signal}),i=(r.headers.get(`content-type`)||``).includes(`application/json`)?await r.json().catch(()=>null):await r.text().catch(()=>``);return{ok:!0,value:{status:r.status,body:i}}}catch(e){return{ok:!1,code:n.signal.aborted?`timeout`:`network_error`,message:e instanceof Error?e.message:String(e)}}finally{r&&clearTimeout(r)}}}}function th(e){return{kind:`clock`,nowMs:e||(()=>Date.now())}}function nh(e){return{kind:`random_source`,randomBytes(t){if(!e?.getRandomValues)throw Error(`Browser crypto.getRandomValues is unavailable`);let n=new Uint8Array(t);return e.getRandomValues(n),n}}}function rh(e={}){return{kind:`browser`,storage:Wm(e.indexedDB||K),secrets:Gm(),authenticator:Qm(e.credentials||globalThis.navigator?.credentials),signerCrypto:$m(e.workerCtx),http:eh(e.fetch||globalThis.fetch?.bind(globalThis)),clock:th(e.nowMs),random:nh(e.crypto||globalThis.crypto)}}function ih(e){throw Error(`[threshold-ed25519] unsupported wallet auth factor kind: ${String(e)}`)}function ah(e){return Si(e.authority)?e.authority:bi(e.authority)||_i(e.authority)?null:(e.authority,ih(e.authority))}async function oh(e){let t=ah(e.authority),n=t?String(t.verifier.rpId||``).trim():``;if(t&&!n)return{ok:!1,code:`invalid_args`,message:`Missing rpId for WebAuthn`};let{policy:r,sessionPolicyDigest32:i}=await ye({nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,authority:e.authority,relayerKeyId:e.relayerKeyId,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},routerAbNormalSigning:e.routerAbNormalSigning,participantIds:e.participantIds,thresholdSessionId:e.thresholdSessionId,ttlMs:e.ttlMs,remainingUses:e.remainingUses}),a=e.auth;if(!a){if(!t)return{ok:!1,code:`invalid_args`,message:`Email OTP Ed25519 session mint requires explicit route authorization`};a={kind:`threshold_session_policy_webauthn`,policySecretSource:ff({credential:await bf({credentialStore:e.credentialStore,touchIdPrompt:e.touchIdPrompt,nearAccountId:e.nearAccountId,challengeB64u:i}),rpId:n})}}let o=lf(a);if(!o)return{ok:!1,code:`unsupported`,message:`Missing PRF.first output from credential (requires a PRF-enabled passkey)`};let s=await cf({relayerUrl:e.relayerUrl,sessionKind:`opaque`,relayerKeyId:e.relayerKeyId,sessionPolicy:r,auth:a,projectEnvironmentId:e.runtimeScopeBootstrap?.projectEnvironmentId,publishableKey:e.runtimeScopeBootstrap?.publishableKey,...e.existingOperationCredential?{existingOperationCredential:e.existingOperationCredential}:{}});if(!s.ok)return s.code===`already_committed`?s:{ok:!1,code:s.code,message:s.message};let c=r.thresholdSessionId,l=s.thresholdSessionId||c,u=s.expiresAtMs,d=s.remainingUses,f=s.runtimePolicyScope;if(!l||!s.authorizationId||!s.walletSessionId||!s.quotaId||!f)return{ok:!1,code:`invalid_response`,message:`Threshold Ed25519 session mint returned incomplete lifecycle metadata`};let p={ok:!0,thresholdSessionId:Qt.thresholdEd25519Session(l),authorizationId:s.authorizationId,walletSessionId:s.walletSessionId,quotaId:s.quotaId,expiresAtMs:u,remainingUses:d,runtimePolicyScope:f,routerAbNormalSigning:e.routerAbNormalSigning,passkeyPrfFirstB64u:o};switch(s.sessionKind){case`issued_exact_wallet_session`:return s.operationCredential.walletSessionId===s.walletSessionId?{...p,sessionKind:s.sessionKind,operationCredential:s.operationCredential}:{ok:!1,code:`invalid_response`,message:`Threshold Ed25519 session mint credential does not identify its session`};case`already_committed_exact_wallet_session`:return{...p,sessionKind:s.sessionKind};default:return sh(s)}}function sh(e){throw Error(`[threshold-ed25519] unsupported Wallet Session mint kind: ${String(e)}`)}function ch(e){return{curve:`ed25519`,authMethod:`passkey`,walletId:e.walletId,relayerUrl:e.relayerUrl,walletSessionToken:e.walletSessionToken,ed25519Restore:e.ed25519Restore}}function lh(e){let t=String(e.authority.factor.credentialIdB64u||``).trim();if(!t)throw Error(`[threshold-ed25519] passkey authority credential id is required`);return t}function uh(e){switch(e.kind){case`fresh_ed25519_provisioning`:return{kind:`fresh`,walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,thresholdSessionId:Qt.thresholdEd25519Session(Il(`threshold-ed25519`))};case`exact_ed25519_provisioning`:{let t=tl(e.laneIdentity,`exact Ed25519 capability provisioning`);return{kind:`exact`,walletId:String(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:String(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,thresholdSessionId:e.laneIdentity.thresholdSessionId,walletSessionId:e.laneIdentity.walletSessionId,quotaId:e.laneIdentity.quotaId}}}throw Error(`[threshold-ed25519] unsupported Ed25519 provisioning kind`)}function dh(e){switch(e.requested.kind){case`fresh`:return!1;case`exact`:return e.returnedThresholdSessionId!==e.requested.thresholdSessionId||e.returnedWalletSessionId!==e.requested.walletSessionId||e.returnedQuotaId!==e.requested.quotaId}throw e.requested,Error(`[threshold-ed25519] unsupported resolved provisioning identity`)}function fh(e){switch(e.connected.sessionKind){case`issued_exact_wallet_session`:return e.connected.operationCredential.walletSessionId===e.connected.walletSessionId?{ok:!0,operationCredential:e.connected.operationCredential}:{ok:!1,code:`invalid_result`,message:`Threshold Ed25519 session mint credential does not identify its session`};case`already_committed_exact_wallet_session`:{if(e.protocol.kind!==`exact`||!e.existingOperationCredential)return{ok:!1,code:`unlock_exact_method`,message:`Threshold Ed25519 session reuse returned no credential; exact-method unlock is required`};let t=e.existingOperationCredential;return t.walletSessionId===e.connected.walletSessionId?{ok:!0,operationCredential:t}:{ok:!1,code:`unlock_exact_method`,message:`Threshold Ed25519 reused session credential identifies another session`}}default:return ph(e.connected)}}function ph(e){throw Error(`[threshold-ed25519] unsupported connected session kind: ${String(e)}`)}async function mh(e,t){let n=uh(t);if(t.kind===`exact_ed25519_provisioning`&&t.operationCredential.walletSessionId!==t.laneIdentity.walletSessionId)return{ok:!1,code:`invalid_args`,message:`Threshold Ed25519 exact credential identifies another Wallet Session`};let r=B(n.nearAccountId),i=String(t.relayerUrl||e.defaultRelayerUrl||``).trim(),a=ue(t.participantIds);if(!i)throw Error(`Missing relayer url (configs.network.relayer.url)`);if(!a)throw Error(`Missing participantIds for threshold Ed25519 session provision`);let o=e.getSignerWorkerContext(),s=await oh({credentialStore:e.credentialStore,touchIdPrompt:e.touchIdPrompt,relayerUrl:i,relayerKeyId:t.relayerKeyId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,authority:t.authority,...t.auth?{auth:t.auth}:{},...t.runtimePolicyScope?{runtimePolicyScope:t.runtimePolicyScope}:{},routerAbNormalSigning:t.routerAbNormalSigning,...t.runtimeScopeBootstrap?{runtimeScopeBootstrap:t.runtimeScopeBootstrap}:{},nearAccountId:r,participantIds:a,thresholdSessionId:n.thresholdSessionId,ttlMs:t.ttlMs,remainingUses:t.remainingUses,workerCtx:o,...t.kind===`exact_ed25519_provisioning`?{existingOperationCredential:t.operationCredential}:{}});if(!s.ok)return{ok:!1,code:String(s.code||`worker_error`).trim()||`worker_error`,message:String(s.message||``).trim()||`Threshold Ed25519 session mint failed`};let c=s.thresholdSessionId||n.thresholdSessionId,l=Number(s.expiresAtMs),u=Number(s.remainingUses),d=String(s.passkeyPrfFirstB64u||``).trim(),f=s.runtimePolicyScope;if(!c||!s.walletSessionId||!s.authorizationId||!s.quotaId||!Number.isFinite(l)||!Number.isFinite(u))return{ok:!1,code:`invalid_result`,message:`Threshold Ed25519 session mint returned incomplete public session metadata`};if(dh({requested:n,returnedThresholdSessionId:c,returnedWalletSessionId:s.walletSessionId,returnedQuotaId:s.quotaId}))return{ok:!1,code:`invalid_result`,message:`Threshold Ed25519 exact provisioning returned a different lifecycle identity`};let p=fh({connected:s,protocol:n,existingOperationCredential:t.kind===`exact_ed25519_provisioning`?t.operationCredential:void 0});if(!p.ok)return p;let{operationCredential:m}=p,h=m.token,g={kind:`minted_ed25519_wallet_session_authority`,thresholdSessionId:c,walletSessionId:s.walletSessionId,authorizationId:s.authorizationId,quotaId:s.quotaId,expiresAtMs:l,remainingUses:u,runtimePolicyScope:f,operationCredential:m},_=e.touchIdPrompt.getRpId();if(d&&t.source===`email_otp`)return{ok:!1,code:`invalid_result`,message:`Passkey PRF material cannot seal an Email OTP Ed25519 session`};if(await t.onWalletSessionAuthorityReady?.(g),d&&t.source!==`email_otp`){let o=lh(t.authority),s=es({rpId:_,nearAccountId:String(r),nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,relayerKeyId:t.relayerKeyId,participantIds:a,runtimePolicyScope:f,signerSlot:n.signerSlot,routerAbNormalSigning:t.routerAbNormalSigning,credentialIdB64u:o,materialActivation:t.materialActivation}),p=ch({walletId:n.walletId,relayerUrl:i,walletSessionToken:h,ed25519Restore:s});try{await Ll(e.touchConfirm,{thresholdSessionId:String(c),prfFirstB64u:d,expiresAtMs:l,remainingUses:u,transport:p})}catch(e){return{ok:!1,code:`warm_session_cache_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||``).trim()||`Threshold Ed25519 session material could not be cached`}}}return{ok:!0,sessionKind:s.sessionKind,thresholdSessionId:c,walletSessionId:s.walletSessionId,authorizationId:s.authorizationId,quotaId:s.quotaId,expiresAtMs:l,remainingUses:u,runtimePolicyScope:f,operationCredential:m}}function hh(e){if(!e)return null;switch(e.materialKind){case`role_local_worker_handle`:return e.roleLocalMaterialRef;case`role_local_durable_sealed_ref`:return e.roleLocalMaterialRef;case`role_local_durable_public_anchor`:case`role_local_ready_state_blob`:case`metadata_only`:return null}}function gh(e){let t=e.bootstrap.thresholdEcdsaKeyRef,n=t.keyHandle,r=t.ecdsaThresholdKeyId,i=t.backendBinding?.ecdsaRoleLocalReadyRecord,a=t.backendBinding?.materialKind===`role_local_worker_handle`?t.backendBinding.publicFacts:i?.publicFacts;if(!a)throw Error(`[SigningEngine] threshold-ecdsa bootstrap did not provide role-local public facts`);let o=La({record:{signingRootId:a.signingRootId,signingRootVersion:a.signingRootVersion}}),s=String(o.signingRootId),c=String(o.signingRootVersion),l=On(t.ethereumAddress);if(!l)throw Error(`[SigningEngine] threshold-ecdsa bootstrap did not provide a threshold owner address`);let u=t.thresholdEcdsaPublicKeyB64u,d=t.backendBinding.relayerKeyId,f=t.relayerVerifyingShareB64u,p=t.participantIds,m=Dn(e.chainTarget),h=hh(t.backendBinding),g={accountModel:`threshold-ecdsa`,accountAddress:l,ownerAddress:l,thresholdOwnerAddress:l,keyScope:`evm-family`,keyHandle:n,walletId:e.walletId,ecdsaThresholdKeyId:r,signingRootId:s,signingRootVersion:c,relayerKeyId:d,relayerVerifyingShareB64u:f,thresholdEcdsaPublicKeyB64u:u,participantIds:p,publicCapability:a.publicCapability,ecdsaRoleLocalPublicFacts:a,chainTarget:e.chainTarget,targetMembership:{targetKey:m,chainTarget:e.chainTarget},sharedEvmFamilyKey:{walletId:e.walletId,keyScope:`evm-family`,keyHandle:n,ecdsaThresholdKeyId:r,signingRootId:s,signingRootVersion:c,participantIds:p,thresholdOwnerAddress:l,thresholdEcdsaPublicKeyB64u:u},chainId:e.chainTarget.chainId};return h&&(g.roleLocalMaterialRef=h),{account:{profileId:e.walletId,chainIdKey:m,accountAddress:l,accountModel:`threshold-ecdsa`},signer:{signerId:l,signerType:`threshold`,signerKind:qt.thresholdEcdsa,signerAuthMethod:e.signerAuth.authMethod,signerSource:e.signerAuth.signerSource,metadata:g},activationPolicy:{mode:`allocate_next_free`},preferredSlot:1,selectAsActive:!1,mutation:{routeThroughOutbox:!1}}}async function _h(e){let t=V(e.walletId);await e.bootstrapStore.upsertProfile({profileId:t}),await e.bootstrapStore.activateAccountSigner(gh({walletId:t,chainTarget:e.chainTarget,bootstrap:e.bootstrap,signerAuth:e.signerAuth}))}function vh(e){let t=String(e.operationId||``).trim(),n=String(e.operationFingerprint||``).trim();if(!t)throw Error(`[SigningEngine] signingOperationId is required`);if(!n)throw Error(`[SigningEngine] operation fingerprint is required`);let r=e.state.callerProvidedOperationFingerprintsById,i=r.get(t);if(i&&i!==n)throw Error(`[SigningEngine] caller-provided signingOperationId reused for a different operation: ${t}`);r.set(t,n),bh(r)}var yh=class{state={callerProvidedOperationFingerprintsById:new Map};bindCallerProvidedOperationIdToFingerprint(e){vh({state:this.state,operationId:e.operationId,operationFingerprint:e.operationFingerprint})}};function bh(e){for(;e.size>1024;){let t=e.keys().next().value;if(!t)return;e.delete(t)}}function xh(e){let t=M(e);if(!t)return null;if(t.kind===`all`)return{kind:`all`};if(t.kind!==`session`)return null;let n=C(t.thresholdSessionId);return n.ok?{kind:`session`,thresholdSessionId:n.value}:null}function Sh(e){let t=M(e);if(!t||t.kind!==`clear_volatile_warm_material`||t.durableRecord!=null||t.resolvedIdentity!=null||t.deleteReason!=null)return null;let n=xh(t.scope);return n?{kind:`clear_volatile_warm_material`,scope:n}:null}function Ch(e){return{kind:`clear_volatile_warm_material`,scope:{kind:`session`,thresholdSessionId:e}}}function wh(){return{kind:`clear_volatile_warm_material`,scope:{kind:`all`}}}async function Th(e){let{authMethod:t,authority:n}=e.selected;if(n.state!==`active`)return{kind:`rejected`,reason:{kind:`authority_not_active`}};if(t.status!==`active`)return{kind:`rejected`,reason:{kind:`auth_method_not_active`}};if(n.walletId!==t.walletId)return{kind:`rejected`,reason:{kind:`wallet_id_mismatch`}};if(n.authorityId!==t.walletAuthorityId)return{kind:`rejected`,reason:{kind:`authority_id_mismatch`}};if(await Br(n.signerActivations)!==n.signerActivationSetDigestB64u)return{kind:`rejected`,reason:{kind:`authority_activation_set_digest_mismatch`}};if(await Kr(n)!==n.authorityDigestB64u)return{kind:`rejected`,reason:{kind:`authority_digest_mismatch`}};let r=Eh(e.operation);if(!n.permissions.includes(r))return{kind:`rejected`,reason:{kind:`permission_missing`}};switch(e.operation.kind){case`near_sign`:case`near_export`:return Dh(n,t);case`evm_sign`:case`evm_export`:return Oh(n,t);default:return jh(e.operation)}}function Eh(e){switch(e.kind){case`near_sign`:case`evm_sign`:return`sign`;case`near_export`:case`evm_export`:return`export_keys`;default:return jh(e)}}function Dh(e,t){let n=kh(e.signerActivations);return n===null?{kind:`rejected`,reason:{kind:`signer_family_unavailable`}}:n.signer.walletId===e.walletId?{kind:`resolved`,value:{kind:`resolved`,keyFamily:`ed25519`,walletId:e.walletId,authorityId:e.authorityId,authMethodId:t.walletAuthMethodId,materialActivation:n.materialActivation,registeredPublicKeyB64u:n.signer.registeredPublicKeyB64u}}:{kind:`rejected`,reason:{kind:`signer_wallet_id_mismatch`}}}function Oh(e,t){let n=Ah(e.signerActivations);return n===null?{kind:`rejected`,reason:{kind:`signer_family_unavailable`}}:n.signer.walletId===e.walletId?{kind:`resolved`,value:{kind:`resolved`,keyFamily:`ecdsa_secp256k1`,walletId:e.walletId,authorityId:e.authorityId,authMethodId:t.walletAuthMethodId,materialActivation:n.materialActivation,thresholdPublicKey33B64u:n.signer.thresholdPublicKey33B64u,evmAddress:n.signer.evmAddress}}:{kind:`rejected`,reason:{kind:`signer_wallet_id_mismatch`}}}function kh(e){return e.keyFamilies[0]!==`ed25519`||e.ed25519===void 0?null:e.ed25519}function Ah(e){return e.keyFamilies[0]!==`ecdsa_secp256k1`&&e.keyFamilies.length!==2||e.ecdsa===void 0?null:e.ecdsa}function jh(e){throw Error(`unsupported wallet authority operation: ${String(e)}`)}const Mh={listed:0,discovered:0,truncated:0};async function Nh(e,t){let n=V(t.walletId);switch(t.authMethod){case z.emailOtp:return await e.discovery.emailOtp({...t,walletId:n,authMethod:z.emailOtp});case z.passkey:return await e.discovery.passkey?.({...t,walletId:n,authMethod:z.passkey})??Mh;default:throw t.authMethod,Error(`Unsupported signer auth method`)}}async function Ph(e,t,n){return await nm(e.availableLanes,t,e.getConfiguredEcdsaChainTargets(),n)}async function Fh(e,t,n){return await rm(e.availableLanes,{walletId:t.walletId,ownerScope:t.ownerScope,ecdsaChainTargets:e.getConfiguredEcdsaChainTargets(),requiredEcdsaCapability:`sign`},n)}function Ih(e){let t=typeof e?.getWarmSessionStatus==`function`?t=>e.getWarmSessionStatus(t):null,n=typeof e?.getWarmSessionStatuses==`function`?t=>e.getWarmSessionStatuses(t):null;return t&&n?{statusPort:`single_and_batch`,getWarmSessionStatus:t,getWarmSessionStatuses:n}:t?{statusPort:`single`,getWarmSessionStatus:t}:n?{statusPort:`batch`,getWarmSessionStatuses:n}:null}function Lh(e){console.warn(`[WarmSessionStore] warm-session availability failure`,{operation:e.operation,thresholdSessionId:e.thresholdSessionId,code:String(e.code||`worker_error`).trim()||`worker_error`})}async function Rh(e,t){let n=String(t||``).trim();return!e||!n||e.statusPort===`batch`?null:zh({thresholdSessionId:n,status:await e.getWarmSessionStatus({thresholdSessionId:n}).catch(()=>({ok:!1,code:`worker_error`,message:`worker_error`}))})}function zh(e){let t=String(e.thresholdSessionId||``).trim();return e.status.ok?{state:`warm`,thresholdSessionId:t,expiresAtMs:e.status.expiresAtMs,remainingUses:e.status.remainingUses}:e.status.code===`expired`?{state:`expired`,thresholdSessionId:t}:e.status.code===`exhausted`?{state:`exhausted`,thresholdSessionId:t}:e.status.code===`not_found`?{state:`missing`,thresholdSessionId:t}:(Lh({operation:`status_read`,thresholdSessionId:t,code:e.status.code}),{state:`unavailable`,thresholdSessionId:t,code:String(e.status.code||`worker_error`).trim()||`worker_error`})}function Bh(e){if(!e.auth||String(e.auth.session.walletId)!==String(e.runtime.walletId)||e.auth.selectedAuthMethod.kind!==e.runtime.factor.kind||e.auth.status.remainingUses<=0||e.auth.status.quotaId!==e.auth.session.quotaId||!ol({session:e.auth.session,materialActivation:e.runtime.sealedRecord.ed25519Restore.materialActivation})||e.runtime.factor.kind===`passkey`&&(e.auth.selectedAuthMethod.kind!==`passkey`||String(e.auth.selectedAuthMethod.rpId)!==String(e.runtime.factor.rpId)||e.auth.selectedAuthMethod.credentialIdB64u!==e.runtime.factor.credentialIdB64u||e.auth.selectedFactorAuthority.factor.kind!==`passkey`||e.auth.selectedFactorAuthority.factor.credentialIdB64u!==e.runtime.factor.credentialIdB64u)||e.runtime.factor.kind===`email_otp`&&(e.auth.selectedAuthMethod.kind!==`email_otp`||e.auth.selectedFactorAuthority.factor.kind!==`email_otp`||e.auth.selectedFactorAuthority.factor.providerUserId!==e.runtime.factor.providerSubjectId||e.auth.selectedFactorAuthority.verifier.kind!==`email_otp_wallet_auth_method`||e.auth.selectedFactorAuthority.verifier.emailHashHex!==e.runtime.factor.emailHashHex))return`authorization_required`;let t=al({remainingUses:e.runtime.remainingUses,expiresAtMs:e.runtime.expiresAtMs});if(t===`expired`||t===`exhausted`)return`authorization_required`;if(!e.prfClaim)return`prf_missing`;switch(e.prfClaim.state){case`unavailable`:return`prf_unavailable`;case`warm`:return`ready`;case`missing`:case`expired`:case`exhausted`:return`prf_missing`}}function Vh(e){if(!e.auth)return`authorization_required`;let t=al({remainingUses:e.runtime.remainingUses,expiresAtMs:e.runtime.expiresAtMs});if(t===`expired`||t===`exhausted`)return`authorization_required`;let n=e.emailOtpAuthContext;return n&&_l(n)===`single_use`&&Number(ml(n))>0||!e.prfClaim?`prf_missing`:e.prfClaim.state===`unavailable`?`prf_unavailable`:e.prfClaim.state===`warm`?`ready`:`prf_missing`}function Hh(e){let t=String(e.sessionId||``).trim(),n=e.claim,r={...e.authMethod?{authMethod:e.authMethod}:{},...e.retention?{retention:e.retention}:{}};return n?n.state===`unavailable`?{sessionId:t,status:`unavailable`,statusCode:n.code,...r}:n.state===`warm`?{sessionId:t,status:`active`,...r,remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs}:{sessionId:t,...r,status:n.state===`expired`?`expired`:n.state===`exhausted`?`exhausted`:`not_found`}:{sessionId:t,status:`not_found`,...r}}function Uh(e){if(!e.auth?.operationCredential.token||!String(e.runtime.relayerUrl||``).trim())return null;let t=String(e.groupId||``).trim();return{curve:`ecdsa`,...e.signingSessionSealKeyVersion?{signingSessionSealKeyVersion:e.signingSessionSealKeyVersion}:{},...t?{groupId:t}:{}}}function Wh(e){return String(e||``).trim()}function Gh(e){let t=Wh(e.thresholdSessionId),n=Math.max(0,Math.floor(Number(e.remainingUses)||0)),r=Math.floor(Number(e.expiresAtMs)||0);return r<=Date.now()?{state:`expired`,thresholdSessionId:t}:n<=0?{state:`exhausted`,thresholdSessionId:t}:{state:`warm`,thresholdSessionId:t,remainingUses:n,expiresAtMs:r}}function Kh(e){switch(e.factor.kind){case`email_otp`:return z.emailOtp;case`passkey`:return z.passkey}}function qh(e){for(let t of e){let e=t.source;switch(e){case`voiceid`:return`voiceid`;case z.emailOtp:return z.emailOtp;case z.passkey:break;default:return Jh(e)}}return null}function Jh(e){throw Error(`Unsupported signing session lane auth method: ${String(e)}`)}function Yh(e){return fm(e.walletId)}function Xh(e,t){t&&(!t.thresholdSessionId||!t.walletSessionId||e.push(t))}function Zh(e,t,n){return{curve:`ed25519`,chain:`near`,source:Kh(e),thresholdSessionId:e.thresholdSessionId,walletSessionId:t,quotaId:n,materialActivation:e.sealedRecord.ed25519Restore.materialActivation,backing:`record_policy`,runtime:e}}async function Qh(e,t){return await tg(e,t,e.exactWalletSessionReadPorts)}function $h(e,t){return e.capabilitySubjects.some(e=>e.kind===`sign`&&e.keyFamily===`ed25519`&&g(e.materialActivation,t))}function eg(e){switch(e.runtime.factor.kind){case`passkey`:return e.authMethod.kind===`passkey`&&String(e.authMethod.rpId)===String(e.runtime.factor.rpId)&&String(e.authMethod.credentialIdB64u)===String(e.runtime.factor.credentialIdB64u);case`email_otp`:return e.authMethod.kind===`email_otp`&&e.authMethod.emailHashHex===e.runtime.factor.emailHashHex}}async function tg(e,t,n){let r=e.listExactSealedSessionsForWallet??hs,i=(await Promise.all([r({walletId:t,filter:{authMethod:z.passkey,curve:`ed25519`}}),r({walletId:t,filter:{authMethod:z.emailOtp,curve:`ed25519`}})])).flat(),a;try{a=await n.resolveSelectedWalletAuthority(String(t))}catch{return[]}if(a.kind!==`resolved`)return[];let{selection:o,authMethod:s,authority:c}=a;if(o.lockState!==`unlocked`||o.walletId!==t||o.walletAuthMethodId!==s.walletAuthMethodId||s.status!==`active`||s.walletId!==t||s.walletAuthorityId!==c.authorityId||c.state!==`active`||c.walletId!==t)return[];let l;try{l=await Th({selected:{authMethod:s,authority:c},operation:{kind:`near_sign`,operation:`sign`,keyFamily:`ed25519`}})}catch{return[]}if(l.kind!==`resolved`||l.value.walletId!==t||l.value.authorityId!==c.authorityId||l.value.authMethodId!==s.walletAuthMethodId)return[];let u;try{u=await n.readExactWithOperationCredential({walletId:t,authorityId:c.authorityId,authMethodId:s.walletAuthMethodId})}catch{return[]}if(u.kind!==`found`)return[];let d=u.record,f=u.operationCredential;if(d.walletId!==t||d.authorityId!==c.authorityId||d.authMethodId!==s.walletAuthMethodId||d.authorityDigestB64u!==c.authorityDigestB64u||d.authorityRevocationEpoch!==c.revocationEpoch||d.expiresAtMs<=Date.now()||f.walletSessionId.length===0||f.token.trim().length===0||!$h(d,l.value.materialActivation))return[];let p=[],m=new Set;for(let e of i){if(e.curve!==`ed25519`)continue;let n=fc(e);!n||n.walletId!==t||!eg({runtime:n,authMethod:s})||!g(n.sealedRecord.ed25519Restore.materialActivation,l.value.materialActivation)||m.has(n.thresholdSessionId)||(m.add(n.thresholdSessionId),Xh(p,Zh(n,f.walletSessionId,d.quotaId)))}return p}async function ng(e){let t=lm(e.walletSessionId,`walletSessionId`);return(await Qh(e.deps,e.walletId)).filter(n=>n.walletSessionId===t&&n.quotaId===e.quotaId)}function rg(e){let t=new Map;for(let n of e.lanes){let e=hm({walletSessionId:n.walletSessionId,quotaId:n.quotaId}),r=t.get(e)||[];r.push(n),t.set(e,r)}let n=new Map;for(let r of t.values()){let t=r[0];if(!t)continue;let i=t.walletSessionId,a=t.quotaId,o=ig({walletSessionId:i,quotaId:a,lanes:r,claimsByThresholdSessionId:e.claimsByThresholdSessionId,statusOverrides:e.statusOverrides}),s=r.map(t=>({lane:t,claim:e.claimsByThresholdSessionId.get(t.thresholdSessionId)||null})),c=e=>{if(!e.length)return;let t=e.find(e=>e.claim?.state===`expired`)?.claim||e.find(e=>e.claim?.state===`exhausted`)?.claim||null,r=e.map(e=>e.claim).filter(e=>e?.state===`warm`),i=r.length?Math.min(...r.map(e=>Math.floor(Number(e.remainingUses)||0))):void 0,a=r.length?Math.min(...r.map(e=>Math.floor(Number(e.expiresAtMs)||0))):void 0;for(let r of e){if(t){n.set(r.lane.thresholdSessionId,ug(t,r.lane.thresholdSessionId));continue}if(r.claim?.state===`warm`){n.set(r.lane.thresholdSessionId,{state:`warm`,thresholdSessionId:r.lane.thresholdSessionId,remainingUses:i??r.claim.remainingUses,expiresAtMs:a??r.claim.expiresAtMs});continue}n.set(r.lane.thresholdSessionId,r.claim)}};if(o){let e=cg(o),t=s.filter(e=>o.thresholdSessionIds.has(Wh(e.lane.thresholdSessionId))),r=s.filter(e=>!o.thresholdSessionIds.has(Wh(e.lane.thresholdSessionId)));if(t.length===s.length){for(let t of s)n.set(t.lane.thresholdSessionId,e?ug(e,t.lane.thresholdSessionId):null);continue}for(let r of t)n.set(r.lane.thresholdSessionId,e?ug(e,r.lane.thresholdSessionId):null);c(r);continue}c(s)}return n}function ig(e){let t=e.statusOverrides;if(!t)return null;for(let n of ag(e.lanes)){let r=t.get(og(n,e.walletSessionId,e.quotaId));if(!r)continue;let i=sg({override:r,lanes:e.lanes,claimsByThresholdSessionId:e.claimsByThresholdSessionId,statusOverrides:t});if(i)return i}return null}function ag(e){let t=new Map;for(let n of e){let e=Yh(n.runtime);t.set(mm(e),e)}return[...t.values()]}function og(e,t,n){return`${mm(e)}:${hm({walletSessionId:t,quotaId:n})}`}function sg(e){if(!e.lanes.length)return null;if(e.lanes.find(t=>{let n=Wh(t.thresholdSessionId);return e.override.thresholdSessionIds.has(n)||t.runtime.sealedRecord.updatedAtMs<=e.override.updatedAtMs?!1:(e.claimsByThresholdSessionId.get(n)||null)?.state===`warm`})){for(let t of e.lanes)e.statusOverrides?.delete(og(Yh(t.runtime),e.override.walletSessionId,e.override.quotaId));return null}return e.override}function cg(e){let t=e.status;if(t.status===`active`){if(typeof t.remainingUses!=`number`||typeof t.expiresAtMs!=`number`)return{state:`unavailable`,code:`invalid_wallet_budget_status`};let e=Math.max(0,Math.floor(Number(t.remainingUses)||0)),n=Math.floor(Number(t.expiresAtMs)||0);return n<=Date.now()?{state:`expired`}:e<=0?{state:`exhausted`}:{state:`warm`,remainingUses:e,expiresAtMs:n}}return t.status===`expired`?{state:`expired`}:t.status===`exhausted`?{state:`exhausted`}:t.status===`unavailable`?{state:`unavailable`,code:String(t.statusCode||`wallet_budget_status_override`)}:null}async function lg(e){let t=new Map;for(let n of e.lanes)t.set(n.thresholdSessionId,Gh({thresholdSessionId:n.thresholdSessionId,remainingUses:n.runtime.remainingUses,expiresAtMs:n.runtime.expiresAtMs}));return t}function ug(e,t){switch(e.state){case`warm`:return{state:`warm`,thresholdSessionId:t,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs};case`unavailable`:return{state:`unavailable`,thresholdSessionId:t,code:e.code};case`missing`:return{state:`missing`,thresholdSessionId:t};case`expired`:return{state:`expired`,thresholdSessionId:t};case`exhausted`:return{state:`exhausted`,thresholdSessionId:t}}}async function dg(e){let t=await Qh(e.deps,e.walletId);return fg({deps:e.deps,lanes:t,statusOverrides:e.statusOverrides})}async function fg(e){let t=await lg({deps:e.deps,lanes:e.lanes});return rg({lanes:e.lanes,claimsByThresholdSessionId:t,statusOverrides:e.statusOverrides})}async function pg(e){let t=e.walletSessionId,n=Array.from(new Set([...e.targetThresholdSessionIds||[]].map(Wh).filter(Boolean)));if(!n.length)return null;let r=Ih(e.deps.touchConfirm),i=await Promise.all(n.map(e=>Rh(r,e)));return Hh({sessionId:t,claim:i.find(e=>e?.state===`expired`)||i.find(e=>e?.state===`exhausted`)||i.find(e=>e?.state===`unavailable`)||i.find(e=>e?.state===`warm`)||null})}function mg(e){let t=e.lanes.some(e=>e.source===z.emailOtp);return Hh({sessionId:e.walletSessionId,claim:e.claim,authMethod:qh(e.lanes),retention:t?`session`:null})}async function hg(e){let t=await ng({deps:e.deps,walletId:e.walletId,walletSessionId:e.walletSessionId,quotaId:e.quotaId});e.statusOverrides.delete(og(fm(e.walletId),e.walletSessionId,e.quotaId));let r=new Set,i=new Set;for(let a of t){if(a.backing===`record_policy`)continue;let t=String(a.materialActivation.activationId);if(r.has(t))continue;if(r.add(t),a.backing===`email_otp_worker`){try{await e.deps.clearEmailOtpWarmSessionMaterial?.(a.thresholdSessionId)}catch{i.add(`email_otp_material`)}continue}let o=n(a.thresholdSessionId);if(o.ok)try{await e.deps.touchConfirm?.clearVolatileWarmSessionMaterial?.(Ch(o.value))}catch{i.add(`touch_confirm_material`)}}return i.size>0?{kind:`unavailable`,failures:[...i]}:{kind:`cleared`}}function gg(e){return`${String(e.walletId)}:wallet-session:${String(e.walletSessionId)}`}function _g(e){let t=e.state;return{kind:`wallet_session_expired`,walletId:t.walletId,walletSessionId:e.walletSessionId,authMethod:t.authMethod,expiresAtMs:t.expiresAtMs,detectedAtMs:t.detectedAtMs}}async function vg(e){let t=e.state.laneIdentity;if(!(`thresholdSessionId`in t))return{kind:`cleared`};try{return t.auth.kind===`email_otp`?await e.deps.readiness.clearEmailOtpWarmSessionMaterial(t.thresholdSessionId):await e.deps.readiness.touchConfirm.clearVolatileWarmSessionMaterial(Ch(t.thresholdSessionId)),{kind:`cleared`}}catch{return{kind:`unavailable`,failures:[t.auth.kind===`email_otp`?`email_otp_material`:`touch_confirm_material`]}}}var yg=class{#e;#t=new Map;#n=new Set;constructor(e){this.#e=e}async invalidate(e){let t=e.state,n=gg(t),r=this.#t.get(n);r||(r=vg({deps:this.#e,state:t}),this.#t.set(n,r));let i=await r;return i.kind===`unavailable`?(this.#t.delete(n),{kind:`unavailable`,failures:i.failures,event:null}):this.#n.has(n)?{kind:`already_invalidated`,event:null}:(this.#n.add(n),{kind:`invalidated`,event:_g(e)})}};function bg(e){return e.lane.curve===`ed25519`&&e.readiness.curve===`ed25519`}function xg(e){return e.lane.curve===`ecdsa`&&e.readiness.curve===`ecdsa`}var Sg=class{#e;#t;#n=!0;constructor(e){this.#e=e.listeners,this.#t=e.listener}unsubscribe(){this.#n&&(this.#n=!1,this.#e.delete(this.#t))}};function Cg(e){return Ji({walletId:e.event.walletId,walletSessionId:e.event.walletSessionId,authMethod:e.event.authMethod,expiresAtMs:e.event.expiresAtMs,detectedAtMs:e.event.detectedAtMs,source:e.source})}var wg=class{onPlannerTrace;walletSessionStatusReader;walletSessionDeps;walletSessionState;operationIdBindings;walletSessionExpiryInvalidator;lifecycleListeners=new Set;walletSessionQuotaAdmissionRefreshQueues=new Map;exactWalletSessionReadPorts;constructor(e){this.exactWalletSessionReadPorts=e.exactWalletSessionReadPorts,this.onPlannerTrace=e.onPlannerTrace,this.walletSessionDeps=e,this.walletSessionState={statusOverrides:new Map},this.walletSessionExpiryInvalidator=new yg({readiness:{touchConfirm:e.touchConfirm,clearEmailOtpWarmSessionMaterial:e.clearEmailOtpWarmSessionMaterial},statusOverrides:this.walletSessionState.statusOverrides}),this.operationIdBindings=new yh,this.walletSessionStatusReader=e.getStatus}async resolveActiveAuthorizedRouterAbEd25519WalletSessionState(e){return await Ws({state:e.state,nowMs:e.nowMs,ports:this.exactWalletSessionReadPorts})}subscribeLifecycle(e){return this.lifecycleListeners.add(e),new Sg({listeners:this.lifecycleListeners,listener:e})}async invalidateExpiredWalletSession(e){let t=await Jo({ports:this.exactWalletSessionReadPorts,input:{walletId:e.state.walletId,authMethod:e.state.authMethod,walletSessionId:e.state.walletSessionId,quotaId:e.state.quotaId,requiredSigningSubject:Ho(e.state.laneIdentity),expiry:{kind:`expired`,nowMs:e.state.detectedAtMs}}});if(t.kind!==`resolved`)return{kind:`unavailable`,failures:[`wallet_session_authorization`],event:null};let n=await this.walletSessionExpiryInvalidator.invalidate({state:e.state,walletSessionId:t.resolved.walletSessionId});if(n.kind!==`invalidated`)return n;let r=Cg({event:n.event,source:e.source});return this.emitLifecycleEvent(r),{kind:`invalidated`,event:r}}emitLifecycleEvent(e){for(let t of this.lifecycleListeners)try{t(e)}catch(e){console.error(`[SigningSessionCoordinator] lifecycle listener failed`,e)}}resolveAuthPlan(e,t){let n=mf(e),r=sf(e,n);return t?.(r),t||this.onPlannerTrace?.(r),n}async resolveAuthPlanFromReadiness(e,t){if(bg(e)){let n=e.readiness.status===`ready`||e.readiness.status===`exhausted`||e.readiness.status===`expired`?e.readiness.expiresAtMs:0,r=e.readiness.status===`ready`||e.readiness.status===`exhausted`?e.readiness.remainingUses:0;return{readiness:e.readiness,expiresAtMs:n,remainingUses:r,signingSessionPlan:this.resolveAuthPlan({lane:e.lane,readiness:e.readiness,forceFreshAuth:e.forceFreshAuth,sensitiveOperationPolicy:e.sensitiveOperationPolicy},t)}}if(xg(e)){let n=e.readiness.status===`ready`||e.readiness.status===`exhausted`||e.readiness.status===`expired`?e.readiness.expiresAtMs:Math.floor(Number(e.expiresAtMs)||0),r=e.readiness.status===`ready`||e.readiness.status===`exhausted`?e.readiness.remainingUses:0;return{readiness:e.readiness,expiresAtMs:n,remainingUses:r,signingSessionPlan:this.resolveAuthPlan({lane:e.lane,readiness:e.readiness,forceFreshAuth:e.forceFreshAuth,sensitiveOperationPolicy:e.sensitiveOperationPolicy},t)}}throw Error(`[SigningSessionCoordinator] lane and readiness curves do not match`)}async getStatus(e){let t=V(e.walletId),n=e.walletSessionId,r=new Set((e.targetThresholdSessionIds||[]).map(Wh).filter(Boolean)),i=r.size>0,a=async()=>i?await pg({deps:this.walletSessionDeps,walletSessionId:n,targetThresholdSessionIds:r}):null,o=(await Qh(this.walletSessionDeps,t)).filter(t=>t.walletSessionId===n&&t.quotaId===e.quotaId);if(!o.length)return await a();let s=i?o.filter(e=>r.has(e.thresholdSessionId)):o;if(i&&!s.length)return await a()||{sessionId:n,status:`not_found`};let c=rg({lanes:s,claimsByThresholdSessionId:await lg({deps:this.walletSessionDeps,lanes:s}),statusOverrides:this.walletSessionState.statusOverrides}),l=s.map(e=>c.get(e.thresholdSessionId)||null).filter(Boolean);return mg({walletSessionId:n,lanes:s,claim:l.find(e=>e?.state===`expired`)||l.find(e=>e?.state===`exhausted`)||l.find(e=>e?.state===`unavailable`)||l.find(e=>e?.state===`warm`)||null})}async getLaneClaimsForWallet(e){return await dg({deps:this.walletSessionDeps,walletId:V(e),statusOverrides:this.walletSessionState.statusOverrides})}async clear(e){await hg({deps:this.walletSessionDeps,statusOverrides:this.walletSessionState.statusOverrides,walletId:V(e.walletId),walletSessionId:e.walletSessionId,quotaId:e.quotaId})}async getAvailableStatus(e){return this.walletSessionStatusReader?await this.walletSessionStatusReader(e):null}bindCallerProvidedOperationIdToFingerprint(e){this.operationIdBindings.bindCallerProvidedOperationIdToFingerprint(e)}async runWalletSessionQuotaAdmissionRetry(e){let t=String(e.queueKey),n=this.walletSessionQuotaAdmissionRefreshQueues.get(t);if(n)return await n.catch(()=>void 0),await e.retryAfterRefresh();let r=e.refresh(),i=r.catch(()=>void 0).then(()=>{this.walletSessionQuotaAdmissionRefreshQueues.get(t)===i&&this.walletSessionQuotaAdmissionRefreshQueues.delete(t)});return this.walletSessionQuotaAdmissionRefreshQueues.set(t,i),await r}};const Tg={resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),readExactWithOperationCredential:q.readExactWithOperationCredential.bind(q)};function Eg(e){return e.getEmailOtpWarmSessionStatus||(async t=>await e.passkeyMpcSession.getWarmSessionStatus({thresholdSessionId:t.thresholdSessionId}))}function Dg(e){let{createArgs:t,getEmailOtpWarmSessionStatus:n}=e;return new wg({exactWalletSessionReadPorts:Tg,getStatus:t.getWalletSessionStatus,touchConfirm:t.passkeyMpcSession,getEmailOtpWarmSessionStatus:e=>n({kind:`ecdsa`,thresholdSessionId:e}),clearEmailOtpWarmSessionMaterial:t.clearEmailOtpWarmSessionMaterial})}async function Og(e){if(e.lane.auth.kind!==`email_otp`)return null;try{let t=await e.createArgs.resolveCanonicalEcdsaSigningCapability({walletId:e.lane.signer.walletId,chainTarget:e.lane.signer.chainTarget,materialActivation:e.lane.signer.materialActivation});if(!bi(t.authority)||t.authority.factor.providerUserId!==e.lane.auth.providerSubjectId)return null;let n=await e.createArgs.resolveActiveEcdsaWalletSessionAuthorization({walletId:e.lane.signer.walletId,chainTarget:e.lane.signer.chainTarget,materialActivation:e.lane.signer.materialActivation},new Ja);if(!n)return null;let r=Td({capability:t,authorization:n,nowMs:Date.now()}),i=r.authorization.runtime;return r.authorization.selectedAuthMethod.kind!==`email_otp`||i.authBinding.kind!==`email_otp`||!yi(t.authority,i.authBinding.emailOtpAuthority)||t.authority.factor.providerUserId!==e.lane.auth.providerSubjectId||i.walletId!==e.lane.signer.walletId||!wn(i.chainTarget,e.lane.signer.chainTarget)||!g(i.materialActivation,e.lane.signer.materialActivation)?null:r.authorization}catch{return null}}function kg(e){let{createArgs:t,signingSessionCoordinator:n,getEmailOtpWarmSessionStatus:r}=e;return{activeWalletAuthorityEcdsaRuntimeReadPorts:Tg,resolveOwnerLaneScope:t.resolveOwnerLaneScope,resolveCanonicalEcdsaSigningCapability:t.resolveCanonicalEcdsaSigningCapability,resolveAuthorizedEcdsaSigningCapability:t.resolveAuthorizedEcdsaSigningCapability,resolveActiveEcdsaWalletSessionAuthorization:t.resolveActiveEcdsaWalletSessionAuthorization,walletSignerStore:e.walletSignerStore,passkeyAuthenticatorStore:e.passkeyAuthenticatorStore,seamsWebConfigs:t.seamsWebConfigs,nonceCoordinator:t.nonceCoordinator,ensureSealedRefreshStartupParity:t.ensureSealedRefreshStartupParity,getSignerWorkerContext:()=>t.signerWorkerManager.getContext(),requestEmailOtpTransactionSigningChallenge:({walletSession:e,chain:n,authority:r,operationFingerprintDigest:i})=>t.requestEmailOtpTransactionSigningChallenge?.({walletSession:e,chain:n,authority:r,operationFingerprintDigest:i})||Promise.reject(Error(`Email OTP signing challenge is not configured`)),resolveDurableEmailOtpEcdsaSigningSessionAuthority:async({lane:e})=>await Og({lane:e,createArgs:t}),restorePersistedSessionForSigning:e=>t.restorePersistedSessionForSigning(e),readAvailableSigningLanesForSigning:e=>t.readAvailableSigningLanesForSigning(e),signingSessionCoordinator:n,getEmailOtpWarmSessionStatus:e=>r({kind:`ecdsa`,thresholdSessionId:e}),provisionThresholdEcdsaSession:e=>t.provisionThresholdEcdsaSession(e),withThresholdEcdsaSigningQueue:e=>t.withThresholdEcdsaSigningQueue(e),touchConfirm:t.touchConfirm}}function Ag(e){let{createArgs:t,nearRpcUrl:n,signingSessionCoordinator:r}=e;return{nearRpcUrl:n,touchConfirm:t.touchConfirm,resolveOwnerLaneScope:t.resolveOwnerLaneScope,prepareNearEd25519YaoMaterialBoundary:t.prepareNearEd25519YaoMaterialBoundary,createSigningSessionId:e=>Il(e),getSignerWorkerContext:()=>t.signerWorkerManager.getContext(),readAvailableSigningLanesForSigning:e=>t.readAvailableSigningLanesForSigning(e),...t.requestEmailOtpEd25519SigningChallenge?{requestEmailOtpEd25519SigningChallenge:e=>t.requestEmailOtpEd25519SigningChallenge(e)}:{},signingSessionCoordinator:r,withThresholdEd25519CommitQueue:e=>t.withThresholdEd25519CommitQueue(e)}}function jg(e){return{credentialStore:e.credentialStore,touchIdPrompt:e.createArgs.touchIdPrompt,getSignerWorkerContext:()=>e.createArgs.signerWorkerManager.getContext(),routerAbNormalSigning:e.createArgs.seamsWebConfigs.signing.routerAb.normalSigning,defaultRelayerUrl:e.createArgs.seamsWebConfigs.network.relayer?.url||``,persistThresholdEcdsaBootstrapForWalletTarget:e.createArgs.persistThresholdEcdsaBootstrapForWalletTarget}}function Mg(e){return{accountStore:e.accountStore,userPreferencesManager:e.createArgs.userPreferencesManager,nonceCoordinator:e.createArgs.nonceCoordinator}}var Ng=class{async upsert(e){}async remove(e){}async list(){return[]}async upsertLane(e){}async removeLane(e){}async listLanes(){return[]}};function Pg(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required`);return n}function Fg(e){let t=e.materialActivation;return JSON.stringify([Pg(e.walletId,`walletId`),Pg(e.nearAccountId,`nearAccountId`),Pg(t.activationId,`materialActivation.activationId`),Pg(t.capability,`materialActivation.capability`),Pg(t.materialOwner,`materialActivation.materialOwner`),Pg(t.keyBinding,`materialActivation.keyBinding`),Pg(t.lifecycleBinding,`materialActivation.lifecycleBinding`),Pg(t.signingWorker,`materialActivation.signingWorker`)])}function Ig(e){if(e.activeClient.status().kind!==`active`)throw Error(`Ed25519 Yao active Client registry rejects disposed state`);let t=e.activeClient.metadata(),n=e.facts,r=n.signer,i=r.account.wallet.walletId,a=r.account.nearAccountId,o=Pg(n.thresholdSessionId,`material.facts.thresholdSessionId`),s=fo(t);if(t.scope.threshold_session_id!==o||!ei(t.scope.material_activation,oi(s))||t.scope.account_id!==String(i)||t.applicationBinding.wallet_id!==String(i)||t.applicationBinding.near_ed25519_signing_key_id!==String(r.nearEd25519SigningKeyId)||t.applicationBinding.signing_root_id!==n.signingRootId||t.scope.root_share_epoch!==n.signingRootVersion||t.applicationBinding.key_creation_signer_slot!==r.signerSlot||t.scope.signing_worker_id!==n.routerAbNormalSigning.signingWorkerId)throw Error(`Ed25519 Yao active Client registry subject identity mismatch`);if(t.participantIds[0]!==de[0]||t.participantIds[1]!==de[1])throw Error(`Ed25519 Yao active Client registry participant identity mismatch`);return{walletId:i,nearAccountId:a,materialActivation:s}}function Lg(e,t){return String(e.walletId)===String(t.walletId)&&String(e.nearAccountId)===String(t.nearAccountId)&&g(e.materialActivation,t.materialActivation)}var Rg=class{entries=new Map;lifecycleGeneration=0;constructor(e=new Ng){this.publicReferences=e}async activate(e){let t=Ig(e),n=Fg(t),r=this.lifecycleGeneration;for(let n of this.entries.values())if(n.material.activeClient===e.activeClient&&!Lg(n.identity,t))throw Error(`Ed25519 Yao active Client state is already bound to another identity`);let i=this.entries.get(n);if(!i&&this.entries.size>=64)throw Error(`Ed25519 Yao active Client registry capacity is exhausted`);if(await this.publicReferences.upsert({walletId:t.walletId,nearAccountId:t.nearAccountId,thresholdSessionId:e.facts.thresholdSessionId,runtimePolicyScope:e.facts.runtimePolicyScope,materialActivation:t.materialActivation}),r!==this.lifecycleGeneration||e.activeClient.status().kind!==`active`)throw e.activeClient.dispose(),await this.publicReferences.remove(t),await this.publicReferences.removeLane(t),Error(`Ed25519 Yao active Client activation was interrupted`);return i&&i.material.activeClient!==e.activeClient&&i.material.activeClient.dispose(),this.entries.set(n,{identity:t,material:e}),t}resolve(e){let t=Fg(e),n=this.entries.get(t);return n?n.material.activeClient.status().kind===`disposed`?(this.entries.delete(t),null):n.material:null}resolveExact(e){return this.resolve(e)}resolveForWalletAccount(e){let t=null;for(let n of this.entries.values())if(!(String(n.identity.walletId)!==String(e.walletId)||String(n.identity.nearAccountId)!==String(e.nearAccountId))&&n.material.activeClient.status().kind!==`disposed`){if(t)throw Error(`Ed25519 Yao active Client lookup scope is ambiguous`);t=n.material}return t}async rollbackActivation(e){this.lifecycleGeneration+=1;let t=Fg(e),n=this.entries.get(t);return n&&(this.entries.delete(t),n.material.activeClient.dispose()),await this.publicReferences.remove(e),await this.publicReferences.removeLane(e),n!==void 0}disposeWallet(e){this.lifecycleGeneration+=1;let t=Pg(e,`walletId`),n=0;for(let[e,r]of this.entries)String(r.identity.walletId)===t&&(this.entries.delete(e),r.material.activeClient.dispose(),n+=1);return n}dispose(){this.lifecycleGeneration+=1;for(let e of this.entries.values())e.material.activeClient.dispose();this.entries.clear()}};function zg(e,t){t.wrapKeySalt&&(e.wrapKeySalt=t.wrapKeySalt),t.payload&&(e.payload=t.payload),typeof t.timestamp==`number`&&(e.timestamp=t.timestamp),typeof t.schemaVersion==`number`&&(e.schemaVersion=t.schemaVersion)}function Bg(e,t){typeof t.timestamp==`number`&&(e.timestamp=t.timestamp),typeof t.schemaVersion==`number`&&(e.schemaVersion=t.schemaVersion)}function Vg(e){let t=nn(d(e||``));return t.startsWith(`ed25519:`)?t:``}function Hg(e){let t=Vg(e.publicKey);if(t)return t;let n=nn(d(e.relayerKeyId||``));return n.startsWith(`ed25519:`)?n:``}function Ug(e,t){if(e.role!==`relayer`)return e;let n={id:e.id,role:`relayer`,relayerKeyId:t};return e.relayerUrl&&(n.relayerUrl=e.relayerUrl),e.shareDerivation&&(n.shareDerivation=e.shareDerivation),n}function Wg(e){let t=oe(e.participants),n=t?.some(e=>e.role===`relayer`)===!0;return!t||!n?ce({relayerKeyId:e.relayerKeyId,clientShareDerivation:`prf_first_v1`}):t.map(t=>Ug(t,e.relayerKeyId))}function Gg(e,t,n){if(!n)return null;let r=n.payload||{},i=Vg(n.publicKey),a=Hg({publicKey:i,relayerKeyId:r.relayerKeyId}),o=d(r.keyVersion||``);return!i||!a||!o?null:{nearAccountId:e,signerSlot:t,kind:`threshold_ed25519_v1`,publicKey:i,relayerKeyId:a,keyVersion:o,participants:Wg({participants:r.participants,relayerKeyId:a}),timestamp:n.timestamp}}async function Kg(e,t,n){return Gg(t,n,await Oo({deps:e,accountRefs:So(t),signerSlot:n,keyKind:`threshold_share_v1`}))}async function qg(e,t){let n=d(t.nearAccountId||``).toLowerCase();if(!n)throw Error(`IndexedDBManager: Missing nearAccountId for key write`);if(!Number.isSafeInteger(t.signerSlot)||t.signerSlot<1)throw Error(`IndexedDBManager: Invalid signerSlot for key write`);let r=d(t.keyKind||``);if(!r)throw Error(`IndexedDBManager: Missing keyKind for key write`);let i=String(t.algorithm||`ed25519`).trim().toLowerCase(),a=d(t.publicKey||``);if(!a)throw Error(`IndexedDBManager: Missing publicKey for key write`);let o=d(t.signerId||``);if(!o)throw Error(`IndexedDBManager: Missing signerId for key write`);let s=d(t.chainIdKey||``).toLowerCase(),c=d(t.profileId||``),l=So(n);if(c||s){if(!c||!s)throw Error(`IndexedDBManager: profileId and chainIdKey are required together for explicit NEAR key material writes`);let u={accountRefs:l,signerSlot:t.signerSlot,keyKind:r,algorithm:i,publicKey:a,signerId:o,explicitProfileId:c,explicitChainIdKey:s,explicitAccountAddress:n};zg(u,t),await To(e,u);return}let u={accountRefs:l,signerSlot:t.signerSlot,keyKind:r,algorithm:i,publicKey:a,signerId:o};zg(u,t),await To(e,u)}async function Jg(e,t){let n=Vg(t.publicKey);if(!n)throw Error(`IndexedDBManager: Missing Ed25519 publicKey for threshold key write`);let r=Hg({publicKey:n,relayerKeyId:t.relayerKeyId}),i=d(t.keyVersion||``);if(!r||!i)throw Error(`IndexedDBManager: Missing threshold Ed25519 relayer metadata for key write`);let a={relayerKeyId:r,keyVersion:i,participants:Wg({participants:t.participants,relayerKeyId:r})},o=d(t.profileId||``),s=d(t.chainIdKey||``).toLowerCase();if(o||s){if(!o||!s)throw Error(`IndexedDBManager: profileId and chainIdKey are required together for explicit NEAR threshold key writes`);let r={nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,keyKind:`threshold_share_v1`,publicKey:n,signerId:t.signerId,payload:a,profileId:o,chainIdKey:s};Bg(r,t),await qg(e,r);return}let c={nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,keyKind:`threshold_share_v1`,publicKey:n,signerId:t.signerId,payload:a};Bg(c,t),await qg(e,c)}function Yg(e){return Math.max(0,Math.round(performance.now()-e))}async function Xg(e){let t=performance.now();try{await e()}catch{}return Yg(t)}async function Zg(e,t){if(!e)return null;try{return await of(e,t)}catch{return null}}async function Qg(e,t={kind:`none`}){let n=t.kind===`near_account_bound`?t.account:null,r=n?B(n.nearAccountId):null,i=await Zg(r,e.store);return{kind:`worker_resource_warmup_diagnostics_v1`,authenticatedWalletStateMs:n&&r&&i?await Xg(()=>e.activateAuthenticatedWalletState({walletId:n.wallet.walletId,nearAccountId:r,signerSlot:i,nearClient:e.nearClient})):0,noncePrefetchMs:await Xg(()=>e.nonceCoordinator.prefetchNearContext({kind:`initialized_state`,nearClient:e.nearClient})),keyMaterialReadMs:r&&i?await Xg(async()=>{await Kg({clientDB:e.store,keyMaterialStore:e.store},r,i).catch(()=>null)}):0,uiConfirmPrewarmMs:e.shouldPrewarmUiConfirmUi(e.workerBaseOrigin)?await Xg(e.prewarmUiConfirmUi):0}}function $g(e){return Ke(e.seamsWebConfigs.network.chains)}function e_(e,t){return()=>({workerBaseOrigin:e.getWorkerBaseOrigin(),store:t.warmupStore,nearClient:e.nearClient,nonceCoordinator:e.nonceCoordinator,shouldPrewarmUiConfirmUi:e.shouldPrewarmUiConfirmUi,prewarmUiConfirmUi:async()=>{await Promise.all([e.touchConfirm.initialize(),e.passkeyMpcSession.prewarmShamir3Pass()])},activateAuthenticatedWalletState:e.activateAuthenticatedWalletState})}function t_(e){let{createArgs:t,getWorkerResourceWarmupDeps:n}=e;return()=>({signTempo:t.signTempo,warmCriticalResources:e=>Qg(n(),e)})}function n_(e){let t=new Rg(e.ed25519YaoPublicCapabilityReferences),n=$g(e),r=Eg(e),i=Dg({createArgs:e,getEmailOtpWarmSessionStatus:r}),a=e_(e,{warmupStore:e.stores.warmup.store});return{ed25519YaoActiveClients:t,nearSigningDeps:Ag({createArgs:e,nearRpcUrl:n,signingSessionCoordinator:i}),tempoSigningDeps:kg({createArgs:e,walletSignerStore:e.stores.walletProfileAndSignerRecords.walletSignerStore,passkeyAuthenticatorStore:e.stores.walletProfileAndSignerRecords.passkeyAuthenticatorStore,signingSessionCoordinator:i,getEmailOtpWarmSessionStatus:r}),registrationAccountLifecycleDeps:Mg({createArgs:e,accountStore:e.stores.walletProfileAndSignerRecords.accountStore}),registrationSessionDeps:{touchConfirm:e.touchConfirm,touchIdPrompt:e.touchIdPrompt},walletSessionActivationDeps:jg({createArgs:e,credentialStore:e.stores.recoveryAndDeviceLinking.credentialStore}),signingSessionCoordinator:i,getWorkerResourceWarmupDeps:a,getManagerConveniencePorts:t_({createArgs:e,getWorkerResourceWarmupDeps:a})}}const r_=[`kind`,`keyFamily`,`walletId`,`walletKeyId`,`walletKeyVersion`,`lifecycle`],i_=[...r_,`nearEd25519SigningKeyId`,`keyCreationSignerSlot`,`registeredPublicKeyB64u`],a_=[...r_,`evmFamilySigningKeySlotId`,`thresholdPublicKey33B64u`,`evmAddress`],o_=Array.from(new Set([...i_,...a_])),s_=[`state`,`activatedAtMs`,`retiredAtMs`,`compromisedAtMs`],c_=[...[`kind`,`walletId`,`walletKeyId`,`laneId`,`laneKind`,`laneShareEpoch`,`participantBindingDigestB64u`],`lifecycle`],l_=[...c_,`walletAuthMethodId`,`ownerParticipantContinuity`],u_=[...c_,`ownerParticipantContinuity`],d_=[...c_,`holderParticipant`,`serverParticipant`],f_=[...d_,`authorizationId`,`agentIdentityKeyId`,`custodyBindingId`,`authorizationBindingDigestB64u`],p_=[...d_,`linkedDeviceId`],m_=Array.from(new Set([...l_,...u_,...f_,...p_])),h_=[`state`,`revocationEpoch`,`startedAtMs`,`deliveryDigestB64u`,`activatedAtMs`,`activationReceiptDigestB64u`,`revokedAtMs`,`revokeReason`];function g_(e){switch(e){case`owner_passkey`:case`owner_voiceid`:case`owner_email_otp`:return l_;case`recovery`:case`break_glass`:return u_;case`linked_device`:return p_;case`delegated_execution`:return f_}}function __(e,t){if(e==null)throw Error(`${t} is required`);if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=e.trim();if(!n)throw Error(`${t} is required`);if(x(n))throw Error(`${t} must not contain whitespace or control characters`);return n}function v_(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=e.trim();if(!n)throw Error(`${t} is required`);if(x(n))throw Error(`${t} must not contain whitespace or control characters`);return n}function y_(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative safe integer`);return e}function b_(e,t=`walletKeyVersion`){return __(e,t)}function x_(e,t){return __(e,t)}function S_(e,t){return __(e,t)}function C_(e,t){return __(e,t)}function w_(e,t){switch(e){case`owner_passkey`:case`owner_voiceid`:case`owner_email_otp`:case`linked_device`:case`delegated_execution`:case`recovery`:case`break_glass`:return e;default:throw Error(`${t} must be a known signing lane kind`)}}function T_(e,t){let n=E(e,t);switch(ke(n,s_,t,s_),n.state){case`active`:if(n.retiredAtMs!==void 0||n.compromisedAtMs!==void 0)throw Error(`${t} cannot be active and carry a retired or compromised timestamp`);return M_({activatedAtMs:je(n.activatedAtMs,`${t}.activatedAtMs`)});case`retired`:if(n.activatedAtMs!==void 0||n.compromisedAtMs!==void 0)throw Error(`${t} cannot be retired and carry an active or compromised timestamp`);return N_({retiredAtMs:je(n.retiredAtMs,`${t}.retiredAtMs`)});case`compromised`:if(n.activatedAtMs!==void 0||n.retiredAtMs!==void 0)throw Error(`${t} cannot be compromised and carry an active or retired timestamp`);return P_({compromisedAtMs:je(n.compromisedAtMs,`${t}.compromisedAtMs`)});default:throw Error(`${t}.state must be active, retired, or compromised`)}}function E_(e,t){let n=E(e,t);ke(n,h_,t);let r=y_(n.revocationEpoch,`${t}.revocationEpoch`);switch(n.state){case`provisioning`:if(n.deliveryDigestB64u!==void 0||n.activatedAtMs!==void 0||n.activationReceiptDigestB64u!==void 0||n.revokedAtMs!==void 0||n.revokeReason!==void 0)throw Error(`${t} provisioning state carries fields from another lifecycle state`);return R_({revocationEpoch:r,startedAtMs:je(n.startedAtMs,`${t}.startedAtMs`)});case`pending_receipt`:if(n.activatedAtMs!==void 0||n.activationReceiptDigestB64u!==void 0||n.revokedAtMs!==void 0||n.revokeReason!==void 0)throw Error(`${t} pending_receipt state carries fields from another lifecycle state`);return z_({revocationEpoch:r,startedAtMs:je(n.startedAtMs,`${t}.startedAtMs`),deliveryDigestB64u:De(n.deliveryDigestB64u,`${t}.deliveryDigestB64u`)});case`active`:if(n.startedAtMs!==void 0||n.deliveryDigestB64u!==void 0||n.revokedAtMs!==void 0||n.revokeReason!==void 0)throw Error(`${t} active state carries fields from another lifecycle state`);return B_({revocationEpoch:r,activatedAtMs:je(n.activatedAtMs,`${t}.activatedAtMs`),activationReceiptDigestB64u:De(n.activationReceiptDigestB64u,`${t}.activationReceiptDigestB64u`)});case`revoked`:{if(n.startedAtMs!==void 0||n.deliveryDigestB64u!==void 0||n.activatedAtMs!==void 0||n.activationReceiptDigestB64u!==void 0)throw Error(`${t} revoked state carries fields from another lifecycle state`);let e=n.revokeReason;if(e!==`user_revoked`&&e!==`device_compromise`&&e!==`agent_compromise`&&e!==`rotation`)throw Error(`${t}.revokeReason is invalid`);return V_({revocationEpoch:r,revokedAtMs:je(n.revokedAtMs,`${t}.revokedAtMs`),revokeReason:e})}default:throw Error(`${t}.state must be provisioning, pending_receipt, active, or revoked`)}}function D_(e,n){if(e.kind!==`signing_lane_reference_v1`)throw Error(`${n}.kind must be signing_lane_reference_v1`);return L_({walletId:Ne(_(e.walletId),`${n}.walletId`),walletKeyId:Ne(t(e.walletKeyId),`${n}.walletKeyId`),laneId:Ne(w(e.laneId),`${n}.laneId`),laneShareEpoch:Ne(v(e.laneShareEpoch),`${n}.laneShareEpoch`),laneKind:w_(e.laneKind,`${n}.laneKind`),participantBindingDigestB64u:Ne(ba(e.participantBindingDigestB64u),`${n}.participantBindingDigestB64u`)})}function O_(e,t){let n=D_(e,t);return{walletId:n.walletId,walletKeyId:n.walletKeyId,laneId:n.laneId,laneShareEpoch:n.laneShareEpoch,participantBindingDigestB64u:n.participantBindingDigestB64u,lifecycle:E_(e.lifecycle,`${t}.lifecycle`)}}function k_(e,t){let n=O_(e,t),i=r(e.walletAuthMethodId);return{...n,walletAuthMethodId:Ne(i,`${t}.walletAuthMethodId`),ownerParticipantContinuity:Sa(e.ownerParticipantContinuity,`${t}.ownerParticipantContinuity`)}}function A_(e,t){return{...O_(e,t),ownerParticipantContinuity:Sa(e.ownerParticipantContinuity,`${t}.ownerParticipantContinuity`)}}function j_(e,t){return{...O_(e,t),holderParticipant:ja(e.holderParticipant,`${t}.holderParticipant`),serverParticipant:Aa(e.serverParticipant,`${t}.serverParticipant`)}}function M_(e){return{state:`active`,activatedAtMs:e.activatedAtMs}}function N_(e){return{state:`retired`,retiredAtMs:e.retiredAtMs}}function P_(e){return{state:`compromised`,compromisedAtMs:e.compromisedAtMs}}function F_(e){return{kind:`wallet_key_record_v1`,keyFamily:`ed25519`,walletId:e.walletId,walletKeyId:e.walletKeyId,walletKeyVersion:e.walletKeyVersion,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,keyCreationSignerSlot:e.keyCreationSignerSlot,registeredPublicKeyB64u:e.registeredPublicKeyB64u,lifecycle:e.lifecycle}}function I_(e){return{kind:`wallet_key_record_v1`,keyFamily:`ecdsa_secp256k1`,walletId:e.walletId,walletKeyId:e.walletKeyId,walletKeyVersion:e.walletKeyVersion,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,thresholdPublicKey33B64u:e.thresholdPublicKey33B64u,evmAddress:e.evmAddress,lifecycle:e.lifecycle}}function L_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:e.laneKind,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u}}function R_(e){return{state:`provisioning`,revocationEpoch:e.revocationEpoch,startedAtMs:e.startedAtMs}}function z_(e){return{state:`pending_receipt`,revocationEpoch:e.revocationEpoch,startedAtMs:e.startedAtMs,deliveryDigestB64u:e.deliveryDigestB64u}}function B_(e){return{state:`active`,revocationEpoch:e.revocationEpoch,activatedAtMs:e.activatedAtMs,activationReceiptDigestB64u:e.activationReceiptDigestB64u}}function V_(e){return{state:`revoked`,revocationEpoch:e.revocationEpoch,revokedAtMs:e.revokedAtMs,revokeReason:e.revokeReason}}function H_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`owner_passkey`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,walletAuthMethodId:e.walletAuthMethodId,ownerParticipantContinuity:e.ownerParticipantContinuity,lifecycle:e.lifecycle}}function U_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`owner_email_otp`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,walletAuthMethodId:e.walletAuthMethodId,ownerParticipantContinuity:e.ownerParticipantContinuity,lifecycle:e.lifecycle}}function W_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`owner_voiceid`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,walletAuthMethodId:e.walletAuthMethodId,ownerParticipantContinuity:e.ownerParticipantContinuity,lifecycle:e.lifecycle}}function G_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`linked_device`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,holderParticipant:e.holderParticipant,serverParticipant:e.serverParticipant,lifecycle:e.lifecycle,linkedDeviceId:e.linkedDeviceId}}function K_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`delegated_execution`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,holderParticipant:e.holderParticipant,serverParticipant:e.serverParticipant,lifecycle:e.lifecycle,authorizationId:e.authorizationId,agentIdentityKeyId:e.agentIdentityKeyId,custodyBindingId:e.custodyBindingId,authorizationBindingDigestB64u:e.authorizationBindingDigestB64u}}function q_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`recovery`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,ownerParticipantContinuity:e.ownerParticipantContinuity,lifecycle:e.lifecycle}}function J_(e){return{kind:`signing_lane_reference_v1`,walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneKind:`break_glass`,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,ownerParticipantContinuity:e.ownerParticipantContinuity,lifecycle:e.lifecycle}}function Y_(e,n=`walletKeyRecord`){let r=E(e,n);if(r.kind!==`wallet_key_record_v1`)throw Error(`${n}.kind must be wallet_key_record_v1`);if(r.keyFamily===`ed25519`)return ke(r,i_,n,o_),F_({walletId:Ne(_(r.walletId),`${n}.walletId`),walletKeyId:Ne(t(r.walletKeyId),`${n}.walletKeyId`),walletKeyVersion:b_(r.walletKeyVersion,`${n}.walletKeyVersion`),nearEd25519SigningKeyId:Di(r.nearEd25519SigningKeyId),keyCreationSignerSlot:Be(r.keyCreationSignerSlot,`${n}.keyCreationSignerSlot`),registeredPublicKeyB64u:Ee(r.registeredPublicKeyB64u,`${n}.registeredPublicKeyB64u`),lifecycle:T_(r.lifecycle,`${n}.lifecycle`)});if(r.keyFamily===`ecdsa_secp256k1`)return ke(r,a_,n,o_),I_({walletId:Ne(_(r.walletId),`${n}.walletId`),walletKeyId:Ne(t(r.walletKeyId),`${n}.walletKeyId`),walletKeyVersion:b_(r.walletKeyVersion,`${n}.walletKeyVersion`),evmFamilySigningKeySlotId:vi(r.evmFamilySigningKeySlotId,`${n}.evmFamilySigningKeySlotId`),thresholdPublicKey33B64u:Ae(r.thresholdPublicKey33B64u,`${n}.thresholdPublicKey33B64u`),evmAddress:v_(r.evmAddress,`${n}.evmAddress`),lifecycle:T_(r.lifecycle,`${n}.lifecycle`)});throw Error(`${n}.keyFamily must be ed25519 or ecdsa_secp256k1`)}function X_(e,t=`signingLaneRecord`){let n=E(e,t);if(n.kind!==`signing_lane_reference_v1`)throw Error(`${t}.kind must be signing_lane_reference_v1`);let r=w_(n.laneKind,`${t}.laneKind`);switch(ke(n,g_(r),t,m_),r){case`owner_passkey`:return H_(k_(n,t));case`owner_voiceid`:return W_(k_(n,t));case`owner_email_otp`:return U_(k_(n,t));case`linked_device`:{let e=j_(n,t);return G_({walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,holderParticipant:e.holderParticipant,serverParticipant:e.serverParticipant,lifecycle:e.lifecycle,linkedDeviceId:Ne(p(n.linkedDeviceId),`${t}.linkedDeviceId`)})}case`delegated_execution`:{let e=j_(n,t);return K_({walletId:e.walletId,walletKeyId:e.walletKeyId,laneId:e.laneId,laneShareEpoch:e.laneShareEpoch,participantBindingDigestB64u:e.participantBindingDigestB64u,holderParticipant:e.holderParticipant,serverParticipant:e.serverParticipant,lifecycle:e.lifecycle,authorizationId:C_(n.authorizationId,`${t}.authorizationId`),agentIdentityKeyId:x_(n.agentIdentityKeyId,`${t}.agentIdentityKeyId`),custodyBindingId:S_(n.custodyBindingId,`${t}.custodyBindingId`),authorizationBindingDigestB64u:De(n.authorizationBindingDigestB64u,`${t}.authorizationBindingDigestB64u`)})}case`recovery`:return q_(A_(n,t));case`break_glass`:return J_(A_(n,t))}}async function Z_(e){let t=await se(new Request(`${fe(e.relayerUrl)}/wallet/execution-lane/owner`,le({headers:ae(e.operationCredential),body:{curve:e.curve,expectedMaterialActivation:e.expectedMaterialActivation}}))),n=await t.json().catch(()=>null);if(!t.ok){let e=ev(n);throw Error(e||`Owner execution-lane preflight returned HTTP ${t.status}`)}return Q_(n,e.curve)}function Q_(e,t){let n=$_(e,[`ok`,`projection`],`owner execution-lane response`);if(n.get(`ok`)!==!0)throw Error(`owner execution-lane response is unsuccessful`);let r=$_(n.get(`projection`),[`kind`,`walletKey`,`lane`,`materialActivation`,`verifiedActivationReceiptDigestB64u`],`owner execution-lane projection`);if(r.get(`kind`)!==`active_owner_wallet_execution_lane_projection_v1`)throw Error(`owner execution-lane projection kind is invalid`);let i=Y_(r.get(`walletKey`)),a=X_(r.get(`lane`)),o=m(r.get(`materialActivation`));if(!o.ok)throw Error(o.error.message);if(i.keyFamily!==t||a.walletId!==i.walletId||a.walletKeyId!==i.walletKeyId||a.laneKind!==`owner_passkey`&&a.laneKind!==`owner_email_otp`)throw Error(`owner execution-lane projection identity is inconsistent`);return{kind:`active_owner_wallet_execution_lane_projection_v1`,walletKey:i,lane:a,materialActivation:o.value,verifiedActivationReceiptDigestB64u:Pt(r.get(`verifiedActivationReceiptDigestB64u`))}}function $_(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw Error(`${n} must be a JSON object`);let r=new Map(Object.entries(e)),i=new Set(t);if(r.size!==i.size||[...r.keys()].some(e=>!i.has(e)))throw Error(`${n} fields are invalid`);return r}function ev(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return null;let t=new Map(Object.entries(e));if(t.size===0||t.size>2||[...t.keys()].some(e=>e!==`code`&&e!==`message`))return null;let n=t.get(`message`);return typeof n==`string`&&n.trim()?n.trim():null}function tv(e){return Xo(e)}function nv(e){return`selector`in e?e.selector.capability:e.capability}function rv(e){switch(e.kind){case`retired`:return lo({capability:e.manifest.signer.capability,reason:`replaced`});case`missing`:return e.subject===`capability`?lo({capability:null,reason:`missing_capability`}):lo({capability:nv(e),reason:`missing_material`});case`exact_binding_mismatch`:return lo({capability:nv(e),reason:`binding_mismatch`});case`exact_record_conflict`:return lo({capability:nv(e),reason:`exact_record_conflict`});case`corrupt`:return lo({capability:nv(e),reason:`corrupt`});case`persistence_unavailable`:return lo({capability:nv(e),reason:`persistence_unavailable`})}}function iv(e){let t=e.lookup.manifest.activation.materialActivation;if(!g(t,e.lookup.material.binding.materialActivation)||e.lookup.manifest.signer.materialOwner!==t.materialOwner)return lo({capability:e.lookup.manifest.signer.capability,reason:`binding_mismatch`});switch(e.runtime.kind){case`live`:return g(t,e.runtime.materialActivation)?oo({authority:e.lookup.manifest.signer.authority,runtime:e.runtime.runtime,materialActivation:t}):lo({capability:e.lookup.manifest.signer.capability,reason:`binding_mismatch`});case`absent`:return go({authority:e.lookup.manifest.signer.authority,materialActivation:t,sealedMaterial:Xo(e.lookup.material.binding.durableMaterialRef)})}}function av(e){return e.lookup.kind===`active`?iv({lookup:e.lookup,runtime:e.runtime}):rv(e.lookup)}function ov(e){let t=v(e);if(!t.ok)throw Error(t.error.message);return t.value}function sv(e){return{walletKey:Y_(e.walletKey),lane:X_(e.lane)}}function cv(e,t){return{kind:`wallet_execution_lane_refused_v1`,reason:e,walletId:t.walletKey.walletId,walletKeyId:t.walletKey.walletKeyId,laneId:t.lane.laneId}}function lv(){return{kind:`wallet_execution_lane_refused_v1`,reason:`invalid_boundary_record`}}function uv(e){if(e.lane.lifecycle.state!==`active`)throw Error(`active lane reference requires an active lane`);return{kind:`signing_lane_reference_v1`,walletId:e.lane.walletId,walletKeyId:e.lane.walletKeyId,laneId:e.lane.laneId,laneKind:e.lane.laneKind,laneShareEpoch:e.lane.laneShareEpoch,participantBindingDigestB64u:e.lane.participantBindingDigestB64u,lifecycle:e.lane.lifecycle,materialActivation:e.materialActivation}}function dv(e){switch(e.laneKind){case`owner_passkey`:case`owner_voiceid`:case`owner_email_otp`:case`recovery`:case`break_glass`:return e.ownerParticipantContinuity;case`linked_device`:case`delegated_execution`:return null}}function fv(e,t){return t.length===e.participantIds.length&&t.every((t,n)=>t===e.participantIds[n])}function pv(e,t){let{walletKey:n,lane:r}=e;if(n.lifecycle.state!==`active`)return cv(`wallet_key_inactive`,e);if(r.lifecycle.state!==`active`)return cv(`lane_inactive`,e);if(String(n.walletId)!==String(r.walletId)||String(n.walletKeyId)!==String(r.walletKeyId))return cv(`wallet_key_mismatch`,e);if(n.keyFamily!==t.keyFamily)return cv(`key_family_mismatch`,e);if(r.laneKind===`linked_device`||r.laneKind===`delegated_execution`)return cv(`unsupported_lane_kind`,e);let i=dv(r);if(i===null)return lv();let a;try{a=ov(t.laneShareEpoch)}catch{return lv()}return String(a)===String(r.laneShareEpoch)?!String(r.participantBindingDigestB64u)||!String(i.signerId)||!String(i.signingWorkerId)||i.participantIds.length!==2?cv(`participant_binding_mismatch`,e):null:cv(`share_epoch_mismatch`,e)}function mv(e){return e.kind===`use_live_runtime`||e.kind===`rehydrate_material_activation`}function hv(e,t){let n=pv(e,t);if(n)return n;let r=e.walletKey,i=e.lane,a=dv(i);if(r.keyFamily!==`ecdsa_secp256k1`||i.lifecycle.state!==`active`)return cv(`key_family_mismatch`,e);if(a===null)return lv();let o=av({lookup:t.lookup,runtime:t.runtime});if(!mv(o)||t.lookup.kind!==`active`)return cv(`hydration_blocked`,e);let s=t.lookup.manifest,c=s.durableMaterial,l=c.roleLocalPublicFacts,u=s.signer.registeredPublicFacts,d=s.activation.serverActivation.serverActivationReceipt,f=d.protocolReceipt.ecdsa_activation.public_identity,p=ai({walletId:l.walletId,signingRootId:l.signingRootId,signingRootVersion:l.signingRootVersion});if(!g(o.materialActivation,s.activation.materialActivation)||!g(o.materialActivation,c.materialActivation)||String(o.authority.walletId)!==String(r.walletId)||String(s.signer.walletId)!==String(r.walletId)||String(l.walletId)!==String(r.walletId)||String(r.evmFamilySigningKeySlotId)!==String(p)||String(r.thresholdPublicKey33B64u)!==String(l.groupPublicKey33B64u)||String(r.thresholdPublicKey33B64u)!==String(u.publicKeyB64u)||r.evmAddress.toLowerCase()!==String(l.ethereumAddress).toLowerCase()||r.evmAddress.toLowerCase()!==String(u.thresholdOwnerAddress).toLowerCase()||String(f.context_binding_b64u)!==String(c.bindingDigest)||String(f.derivation_client_share_public_key33_b64u)!==String(l.derivationClientSharePublicKey33B64u)||String(f.threshold_public_key33_b64u)!==String(r.thresholdPublicKey33B64u)||String(d.activationDigest)!==String(i.lifecycle.activationReceiptDigestB64u))return cv(`activation_receipt_mismatch`,e);if(String(a.signingWorkerId)!==String(o.materialActivation.signingWorker)||!fv(a,l.participantIds))return cv(`participant_binding_mismatch`,e);let m=o.materialActivation;return{kind:`active_wallet_execution_lane_v1`,keyFamily:`ecdsa_secp256k1`,walletKey:r,lane:uv({lane:i,materialActivation:m}),ownerParticipantContinuity:a,materialActivation:m,laneShareEpoch:i.laneShareEpoch,activationReceiptDigestB64u:i.lifecycle.activationReceiptDigestB64u,publicIdentity:{keyFamily:`ecdsa_secp256k1`,thresholdPublicKey33B64u:r.thresholdPublicKey33B64u,evmAddress:r.evmAddress,evmFamilySigningKeySlotId:r.evmFamilySigningKeySlotId}}}function gv(e){let t;try{t=sv(e)}catch{return lv()}try{return hv(t,e.material)}catch{return lv()}}function _v(e){let t=Tn(e.seamsWebConfigs.network.chains),n=e=>{if(e.ecdsaChainTargets.length===0)return e;let n=new Map;for(let r of[...e.ecdsaChainTargets,...t])n.set(H(r),r);return{...e,ecdsaChainTargets:[...n.values()]}};return{sessionLifecycle:e.sessionLifecycle,laneSelection:{readPersistedAvailableSigningLanesForTargets:t=>cm({activeWalletAuthorityEcdsaRuntimeReadPorts:Tg,ed25519YaoPublicCapabilityLanes:e.ed25519YaoPublicCapabilityLanes,isEd25519YaoPublicCapabilityActive:e.isEd25519YaoPublicCapabilityActive,readActiveWalletSessionAuthorization:e.readActiveWalletSessionAuthorization,listEcdsaSigningCapabilitiesForWallet:e.listEcdsaSigningCapabilitiesForWallet},{...n(t),requiredEcdsaCapability:`export_keys`},new Ja,`all`),readOwnerScopedAvailableSigningLanesForTargets:async t=>await rm({activeWalletAuthorityEcdsaRuntimeReadPorts:Tg,ed25519YaoPublicCapabilityLanes:e.ed25519YaoPublicCapabilityLanes,isEd25519YaoPublicCapabilityActive:e.isEd25519YaoPublicCapabilityActive,readActiveWalletSessionAuthorization:e.readActiveWalletSessionAuthorization,listEcdsaSigningCapabilitiesForWallet:e.listEcdsaSigningCapabilitiesForWallet},{...n(t),requiredEcdsaCapability:`export_keys`,ownerScope:await e.resolveOwnerLaneScope(String(t.walletId))},new Ja)},ecdsa:{activeWalletAuthorityEcdsaRuntimeReadPorts:Tg,sessionStore:{...e.ecdsaSessions,resolveActiveEcdsaCapabilityRuntime:e.resolveActiveEcdsaCapabilityRuntime,relayerUrl:String(e.relayerUrl).trim().replace(/\/+$/g,``)},touchConfirm:e.touchConfirm,emailOtp:{requestExportChallenge:t=>e.emailOtpSessions.requestExportChallenge(t),exportEcdsaKeyWithDurableAuthorization:t=>e.emailOtpSessions.exportEcdsaKeyWithDurableAuthorization(t)},provisionPasskeyEcdsaExplicitExportSession:t=>e.provisionPasskeyEcdsaExplicitExportSession(t),getSignerWorkerContext:()=>e.signerWorkerManager.getContext(),withThresholdEcdsaSigningQueue:e.withThresholdEcdsaSigningQueue},ed25519Yao:{touchConfirm:e.touchConfirm,passkeyMpcExport:e.passkeyMpcExport,resolvePasskeyExportContext:e.resolvePasskeyEd25519YaoExportContext,withThresholdEd25519CommitQueue:e.withThresholdEd25519CommitQueue,emailOtp:{requestExportChallenge:t=>e.emailOtpSessions.requestExportChallenge(t),resolveExportContext:t=>e.resolveEmailOtpEd25519YaoExportContext(t),exportSeedWithFreshAuthorization:t=>e.emailOtpSessions.exportEd25519YaoSeedWithFreshEmailOtpLane(t)}},getTheme:e.getTheme}}async function vv(e,t){let n=t.laneIdentity,r={kind:`ed25519`,laneIdentity:n},i=pl(n),a;try{a=await e.resolveSelectedWalletAuthority(String(i))}catch{return $d({observation:{kind:`unavailable`,source:r},nowMs:t.nowMs})}if(a.kind!==`resolved`)return $d({observation:a.kind===`integrity_error`?{kind:`invalid`,source:r}:{kind:`missing`,source:r},nowMs:t.nowMs});if(!yv(a,n))return $d({observation:{kind:`invalid`,source:r},nowMs:t.nowMs});let o;try{o=await e.readExactActiveForWallet({walletId:i,authorityId:a.authority.authorityId,authMethodId:a.authMethod.walletAuthMethodId})}catch{return $d({observation:{kind:`unavailable`,source:r},nowMs:t.nowMs})}switch(o.kind){case`missing`:return $d({observation:{kind:`missing`,source:r},nowMs:t.nowMs});case`corrupt`:case`upgrade_required`:return $d({observation:{kind:`invalid`,source:r},nowMs:t.nowMs});case`persistence_unavailable`:return $d({observation:{kind:`unavailable`,source:r},nowMs:t.nowMs});case`found`:break}return o.record.walletId!==i||o.record.authorityId!==a.authority.authorityId||o.record.authMethodId!==a.authMethod.walletAuthMethodId||o.operationCredential.walletSessionId!==n.walletSessionId||o.record.quotaId!==n.quotaId||o.record.authorityDigestB64u!==a.authority.authorityDigestB64u||o.record.authorityRevocationEpoch!==a.authority.revocationEpoch?$d({observation:{kind:`invalid`,source:r},nowMs:t.nowMs}):$d({observation:{kind:`found`,source:r,expiresAtMs:o.record.expiresAtMs},nowMs:t.nowMs})}function yv(e,t){let n=pl(t);if(e.selection.lockState!==`unlocked`||e.selection.walletId!==n||e.selection.walletAuthMethodId!==e.authMethod.walletAuthMethodId||e.authMethod.walletId!==n||e.authMethod.walletAuthorityId!==e.authority.authorityId||e.authMethod.status!==`active`||e.authority.walletId!==n||e.authority.state!==`active`)return!1;switch(t.auth.kind){case`voiceid`:return e.authMethod.kind===`voiceid`&&e.authMethod.walletAuthMethodId===t.auth.walletAuthMethodId&&e.authMethod.deviceKeyId===t.auth.deviceKeyId;case`passkey`:return e.authMethod.kind===`passkey`&&String(e.authMethod.rpId)===String(t.auth.rpId)&&e.authMethod.credentialIdB64u===t.auth.credentialIdB64u;case`email_otp`:return e.authMethod.kind===`email_otp`}}function bv(e){return $d({observation:{kind:`found`,source:{kind:`ecdsa`,laneIdentity:e.laneIdentity,authorization:e.authorization},expiresAtMs:e.authorization.session.expiresAtMs},nowMs:e.nowMs})}async function xv(e,t){switch(t.kind){case`ed25519`:return await vv(e,t);case`ecdsa`:return bv(t)}}const Sv={resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),readExactActiveForWallet:q.readExactActiveForWallet.bind(q)};async function Cv(e){return await xv(Sv,e)}function wv(e,t){return e.selection.lockState===`unlocked`&&e.selection.walletId===t&&e.selection.walletAuthMethodId===e.authMethod.walletAuthMethodId&&e.authMethod.status===`active`&&e.authMethod.walletId===t&&e.authMethod.walletAuthorityId===e.authority.authorityId&&e.authority.state===`active`&&e.authority.walletId===t}async function Tv(e){let t;try{t=await K.resolveSelectedWalletAuthority(String(e))}catch{return{kind:`persistence_unavailable`}}if(t.kind!==`resolved`||!wv(t,e))return{kind:`missing`};try{return await q.readExactActiveForWallet({walletId:e,authorityId:t.authority.authorityId,authMethodId:t.authMethod.walletAuthMethodId})}catch{return{kind:`persistence_unavailable`}}}function Ev(e){let t=bm({relayerUrl:String(e.seamsWebConfigs.network.relayer?.url||``).trim(),readAuthorization:Tv});return _v({resolveActiveEcdsaCapabilityRuntime:dy,seamsWebConfigs:e.seamsWebConfigs,signerWorkerManager:e.signerWorkerManager,getTheme:e.getTheme,withThresholdEcdsaSigningQueue:t=>Hd({queueByKey:e.thresholdEcdsaSigningQueueByKey,...t}),withThresholdEd25519CommitQueue:t=>Pf({queueByKey:e.thresholdEd25519CommitQueueByKey,...t}),ecdsaSessions:e.warmSigning.ecdsaSessions,relayerUrl:String(e.seamsWebConfigs.network.relayer?.url||``).trim(),readActiveWalletSessionAuthorization:e.readActiveWalletSessionAuthorization,ed25519YaoPublicCapabilityLanes:e.ed25519YaoPublicCapabilityLanes,isEd25519YaoPublicCapabilityActive:e.isEd25519YaoPublicCapabilityActive,listEcdsaSigningCapabilitiesForWallet:e.listEcdsaSigningCapabilitiesForWallet,resolveOwnerLaneScope:e.resolveOwnerLaneScope,touchConfirm:e.touchConfirm,passkeyMpcSession:e.passkeyMpcSession,passkeyMpcExport:e.passkeyMpcExport,emailOtpSessions:{readWarmSessionStatusOnly:t=>e.emailOtpSessions.readWarmSessionStatusOnly(t),requestExportChallenge:t=>e.emailOtpSessions.requestExportChallenge(t),exportEcdsaKeyWithDurableAuthorization:t=>e.emailOtpSessions.exportEcdsaKeyWithDurableAuthorization(t),exportEd25519YaoSeedWithFreshEmailOtpLane:t=>e.emailOtpSessions.exportEd25519YaoSeedWithFreshEmailOtpLane(t)},provisionPasskeyEcdsaExplicitExportSession:t=>yu({queueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,activationDeps:e.getWalletSessionActivationDeps(),persistEcdsaRoleLocalReadyRecord:e.runtimePorts.storage.persistEcdsaRoleLocalReadyRecord},t),getWalletSessionStatus:e=>t(e),resolvePasskeyEd25519YaoExportContext:e.resolvePasskeyEd25519YaoExportContext,resolveEmailOtpEd25519YaoExportContext:e.resolveEmailOtpEd25519YaoExportContext,sessionLifecycle:{readAuthorization:Cv,invalidateExpiredAuthorization:async t=>{if((await e.getSigningSessionCoordinator().invalidateExpiredWalletSession({state:t.state,source:t.source})).kind===`unavailable`)throw Error(`[SigningEngine][key-export] expired Wallet Session cleanup failed`)}}})}const Dv=new ra;function Ov(e,t){return e.walletId===t.authority.walletId&&e.authorityId===t.authority.authorityId&&e.authMethodId===t.authMethod.walletAuthMethodId&&e.authorityDigestB64u===t.authority.authorityDigestB64u&&e.authorityRevocationEpoch===t.authority.revocationEpoch}function kv(e){if(e.authMethod!==`passkey`)throw Error(`Passkey restore adapter received a non-Passkey request`);let{authMethod:t,...n}=e;return n}const Av={getWalletAuthMethodV2:K.getWalletAuthMethodV2.bind(K),listWalletAuthMethodsForWallet:K.listWalletAuthMethodsForWallet.bind(K),readEmailOtpProviderSubjectForWallet:na.bind(null,K)};async function jv(){return null}async function Mv(e,t){let n=await t.getWalletAuthMethodV2(String(e.walletAuthMethodId));if(!n||n.status!==`active`||n.walletId!==e.walletId)throw Error(`Exact wallet authentication authority is unavailable`);let r;try{r=await Jp({authMethod:n,stores:{...t,getWalletPasskeyAuthenticator:jv}})}catch{throw Error(`Exact wallet authentication authority is unavailable`)}let i=await U({authority:r});if(i.walletId===e.walletId&&i.walletAuthMethodId===e.walletAuthMethodId&&i.authorityDigest===e.authorityDigest)return r;throw Error(`Exact wallet authentication authority is unavailable`)}function Nv(e){return bm({relayerUrl:String(e.seamsWebConfigs.network.relayer?.url||``).trim(),readAuthorization:Tv})}function Pv(e,t){return e.kind!==`resolved`||e.selection.lockState!==`unlocked`||e.selection.walletId!==t||e.selection.walletAuthMethodId!==e.authMethod.walletAuthMethodId||e.authMethod.status!==`active`||e.authMethod.walletId!==t||e.authMethod.walletAuthorityId!==e.authority.authorityId||e.authority.state!==`active`||e.authority.walletId!==t?null:{kind:e.kind,selection:e.selection,authMethod:e.authMethod,authority:e.authority,signerMaterials:e.signerMaterials,exportRoot:e.exportRoot}}async function Fv(e,t,n){let r=Pv(await K.resolveSelectedWalletAuthority(String(e)),e),i=await Tv(e);return!r||i.kind!==`found`||i.operationCredential.token!==n.token||!Ov(i.record,r)||!zl(t,i.record)||t.authorityRevocationEpoch!==i.record.authorityRevocationEpoch||t.capabilitySubjects.length>=i.record.capabilitySubjects.length||!Le(t,i.record)?null:{selected:r,session:i.record}}async function Iv(e){return await Jp({authMethod:e.authMethod,stores:{...Av,getWalletPasskeyAuthenticator:jv}})}async function Lv(e){let t;try{t=await K.resolveSelectedWalletAuthority(String(e.walletId))}catch{throw Error(`[SigningEngine][near] exact Passkey authority is unavailable`)}let n=Pv(t,e.walletId);if(!n||n.authMethod.kind!==R.passkey)throw Error(`[SigningEngine][near] exact Passkey authority is unavailable`);if(e.runtime.walletId!==e.walletId||e.runtime.factor.kind!==R.passkey||String(e.runtime.factor.rpId)!==String(n.authMethod.rpId)||e.runtime.factor.credentialIdB64u!==n.authMethod.credentialIdB64u)throw Error(`[SigningEngine][near] exact Passkey authority changed`);let r;try{r=await ks({runtime:e.runtime,walletAuthMethodId:n.authMethod.walletAuthMethodId})}catch{throw Error(`[SigningEngine][near] exact Passkey authority changed`)}let i;try{i=await Iv(n)}catch{throw Error(`[SigningEngine][near] exact Passkey authority changed`)}let a=await U({authority:i});if(a.walletId!==r.walletId||a.walletAuthMethodId!==r.walletAuthMethodId||a.authorityDigest!==r.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey authority changed`);return a}async function Rv(e){switch(e.authorizationRead.kind){case`expired`:case`exhausted`:return await Lv(e);case`found`:{let t=e.authorizationRead.authorization;if(t.selectedAuthMethod.kind!==R.passkey||e.runtime.factor.kind!==R.passkey||String(e.runtime.factor.rpId)!==String(t.selectedAuthMethod.rpId)||e.runtime.factor.credentialIdB64u!==t.selectedAuthMethod.credentialIdB64u)throw Error(`[SigningEngine][near] exact Passkey authority changed`);let n=await ks({runtime:e.runtime,walletAuthMethodId:t.selectedAuthMethod.walletAuthMethodId}),r=await U({authority:t.selectedFactorAuthority});if(n.walletId!==r.walletId||n.walletAuthMethodId!==r.walletAuthMethodId||n.authorityDigest!==r.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey authority changed`);return n}default:throw e.authorizationRead,Error(`[SigningEngine][near] unsupported exact Passkey authorization read`)}}function zv(e){switch(e.status){case`missing`:return{kind:`missing`};case`exhausted`:return{kind:`exhausted`};case`expired`:return{kind:`expired`};case`superseded`:return{kind:`superseded`};case`authority_unavailable`:return{kind:`authority_unavailable`};case`method_unavailable`:return{kind:`method_unavailable`};case`capability_unavailable`:return{kind:`capability_unavailable`};case`invalid`:return{kind:`unavailable`};case`active`:throw Error(`[SigningEngine][near] active status must be resolved as authorization`);default:throw Error(`[SigningEngine][near] unsupported Wallet Session status`)}}async function Bv(e,t,n){let r=await Tv(n);if(r.kind!==`found`)return r;let i=Pv(await K.resolveSelectedWalletAuthority(String(n)),n);if(!i)return{kind:`missing`};if(r.record.expiresAtMs<=Date.now())return{kind:`expired`};let a=Ja.observationForConfirmation({relayerUrl:e,operationCredential:r.operationCredential},{walletSessionId:r.operationCredential.walletSessionId,quotaId:r.record.quotaId});if(!a||a.status.status===`active`&&(!Ue(a.status.authorization,r.record)||!Ov(r.record,i)))return Vv(e,t,n);let o=a.status;if(o.status!==`active`)return zv(o);let s=await Iv(i);return{kind:`found`,authorization:bl({selectedAuthority:i.authority,selectedAuthMethod:i.authMethod,selectedFactorAuthority:s,session:r.record,operationCredential:r.operationCredential,status:o,nowMs:Date.now()})}}async function Vv(e,t,n){let r=V(n),i;try{i=await K.resolveSelectedWalletAuthority(String(r))}catch{return{kind:`persistence_unavailable`}}let a=Pv(i,r);if(!a)return{kind:`missing`};let o;try{o=await q.readExactActiveForWallet({walletId:r,authorityId:a.authority.authorityId,authMethodId:a.authMethod.walletAuthMethodId})}catch{return{kind:`persistence_unavailable`}}switch(o.kind){case`missing`:case`corrupt`:case`persistence_unavailable`:case`upgrade_required`:return o;case`found`:break;default:throw Error(`[SigningEngine][near] unsupported exact Wallet Session read result`)}let s=String(e||``).trim();if(!s)return{kind:`unavailable`};let c=Date.now();if(o.record.expiresAtMs<=c)return{kind:`expired`};let l;try{l=await t.read({relayerUrl:s,operationCredential:o.operationCredential},{walletSessionId:o.operationCredential.walletSessionId,quotaId:o.record.quotaId})}catch{return{kind:`unavailable`}}if(l.status!==`active`)return zv(l);let u;try{u=await K.resolveSelectedWalletAuthority(String(r))}catch{return{kind:`persistence_unavailable`}}let d=Pv(u,r);if(!d)return{kind:`missing`};let f=Date.now();if(l.authorization.expiresAtMs<=f)return{kind:`expired`};if(l.walletSessionId!==o.operationCredential.walletSessionId||l.quotaId!==o.record.quotaId||l.expiresAtMs!==l.authorization.expiresAtMs||!zl(l.authorization,o.record)||!Ov(l.authorization,d))return{kind:`corrupt`};let p;try{p=await K.replaceExactActiveWalletSessionFromStatus({active:l.authorization,operationCredential:o.operationCredential})}catch{return{kind:`persistence_unavailable`}}if(p.kind===`superseded`)return Rl(`near`,{event:`wallet_session_status_superseded`,walletSessionId:o.operationCredential.walletSessionId}),{kind:`unavailable`};let m;try{m=await Iv(d)}catch{return{kind:`unavailable`}}try{return{kind:`found`,authorization:bl({selectedAuthority:d.authority,selectedAuthMethod:d.authMethod,selectedFactorAuthority:m,session:l.authorization,operationCredential:o.operationCredential,status:l,nowMs:f})}}catch{return{kind:`corrupt`}}}async function Hv(e,t,n){let r=await Vv(t,n,e);return r.kind===`found`?r.authorization:null}function Uv(e){return e.curve===`ecdsa`}function Wv(e){let{manifest:t,selected:n,walletId:r,chainTarget:i,materialActivation:a}=e;return t.signer.walletId===r&&t.signer.authority.walletId===r&&t.signer.authority.walletAuthMethodId===n.authMethod.walletAuthMethodId&&g(t.activation.materialActivation,a)&&t.signer.scope.targetMemberships.some(e=>H(e)===H(i))}async function Gv(e){let t=(await ly(String(e.walletId))).filter(t=>Wv({manifest:t,selected:e.selected,walletId:e.walletId,chainTarget:e.chainTarget,materialActivation:e.materialActivation}));if(t.length!==1)return{kind:`inactive`,reason:`Expected one exact ECDSA capability manifest; found ${t.length}`};let[n]=t;if(!n)return{kind:`inactive`,reason:`Exact ECDSA capability manifest is missing`};let r=await ey(n),i=e.selected.authMethod.kind===`voiceid`?[]:await e.context.sealedSigningSessionStore.listExactSealedSessionsForWallet({walletId:String(e.walletId),filter:{authMethod:e.selected.authMethod.kind,curve:`ecdsa`,chainTarget:e.chainTarget}}),a=yd({manifest:n,walletId:e.walletId,chainTarget:e.chainTarget,sealedRecords:i.filter(Uv)}),o;if(a.kind===`resolved`){let t=a.runtime;o={kind:`exact_ecdsa_sealed_runtime_v1`,walletId:t.walletId,chainTarget:t.chainTarget,materialActivation:t.materialActivation,normalSigning:t.normalSigning,relayerUrl:t.relayerUrl,relayerKeyId:t.relayerKeyId,clientVerifyingPublicKey33B64u:t.clientVerifyingPublicKey33B64u,participantIds:t.participantIds,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,keyHandle:t.keyHandle,runtimePolicyScope:t.runtimePolicyScope,roleLocalMaterialRef:t.roleLocalMaterialRef,authBinding:t.authBinding,sealedRecord:t.sealedRecord,expiresAtMs:Math.min(t.expiresAtMs,e.status.expiresAtMs),remainingUses:e.status.remainingUses}}else{if(a.reason!==`missing_material`)return{kind:`inactive`,reason:`Exact sealed ECDSA runtime is ${a.reason}`};let t=await jd({manifest:n,chainTarget:e.chainTarget,relayerUrl:e.context.seamsWebConfigs.network.relayer?.url??``});if(t.kind!==`resolved`)return{kind:`inactive`,reason:`Exact durable ECDSA capability runtime is ${t.reason}`};try{o=hd({runtime:t.runtime,authority:r.authority,status:e.status})}catch{return{kind:`inactive`,reason:`Exact durable ECDSA quota facts are invalid`}}}try{return{kind:`resolved`,capability:xd({capability:r,selected:e.selected,session:e.session,operationCredential:e.operationCredential,runtime:o,nowMs:e.nowMs})}}catch(e){return{kind:`inactive`,reason:e instanceof Error?e.message:`Exact ECDSA Wallet Session authorization is invalid`}}}async function Kv(e,t,n){let r=V(t.walletId),i=Date.now(),a=Pv(await K.resolveSelectedWalletAuthority(String(r)),r);if(!a)return{kind:`inactive`,reason:`Selected wallet authentication authority is unavailable`};let o=String(e.seamsWebConfigs.network.relayer?.url||``).trim();if(!o)throw Error(`Exact Wallet Session status requires a relayer URL`);let s=await Tv(r);if(s.kind!==`found`)return{kind:`inactive`,reason:`Exact Wallet Session authorization is ${s.kind}`};if(s.record.expiresAtMs<=i)return{kind:`inactive`,reason:`Exact Wallet Session authorization is expired`};let c=await n.read({relayerUrl:o,operationCredential:s.operationCredential},{walletSessionId:s.operationCredential.walletSessionId,quotaId:s.record.quotaId});if(c.status!==`active`&&c.status!==`exhausted`)return{kind:`inactive`,reason:`Exact Wallet Session is ${c.status}`};if(zl(c.authorization,s.record)&&!Ov(c.authorization,a))try{await K.reconcilePendingNearRegistrationAuthority({walletSession:c.authorization,operationCredential:s.operationCredential})}catch{return{kind:`inactive`,reason:`NEAR authority reconciliation was superseded`}}let l=Pv(await K.resolveSelectedWalletAuthority(String(r)),r);if(!l||c.walletSessionId!==s.operationCredential.walletSessionId||c.quotaId!==s.record.quotaId||c.expiresAtMs!==c.authorization.expiresAtMs||!zl(c.authorization,s.record))return{kind:`inactive`,reason:`Exact Wallet Session status identity is inconsistent`};let u=Date.now();if(c.authorization.expiresAtMs<=u)return{kind:`inactive`,reason:`Exact Wallet Session authorization is expired`};let d=Ov(c.authorization,l),f=null;if(d){let e;try{e=await K.replaceExactActiveWalletSessionFromStatus({active:c.authorization,operationCredential:s.operationCredential})}catch{return{kind:`inactive`,reason:`Exact Wallet Session promotion reconciliation could not be persisted`}}e.kind===`replaced`?f={selected:l,session:c.authorization}:Rl(`evm-family`,{event:`wallet_session_status_superseded`,walletSessionId:s.operationCredential.walletSessionId})}if(f??=await Fv(r,c.authorization,s.operationCredential),!f)return{kind:`inactive`,reason:d?`Exact Wallet Session status was superseded by a newer wallet authority`:`Exact Wallet Session status identity is inconsistent`};let p=await Gv({context:e,walletId:r,selected:f.selected,session:f.session,operationCredential:s.operationCredential,status:c,chainTarget:t.chainTarget,materialActivation:t.materialActivation,nowMs:u});return p.kind===`resolved`?{kind:`active`,capability:p.capability}:p}async function qv(e,t,n){let r=await Kv(e,t,n);if(r.kind===`inactive`)return r;let i=Nd(r.capability,Date.now());return i?{kind:`active`,authorization:i}:{kind:`inactive`,reason:`Exact Wallet Session signing quota is exhausted`}}async function Jv(e,t,n){let r=await cy({walletId:V(t.walletId),chainTargets:t.chainTargets}),i=[];for(let a of r)for(let r of t.chainTargets){let t=await Kv(e,{walletId:a.manifest.signer.walletId,materialActivation:a.manifest.activation.materialActivation,chainTarget:r},n);if(t.kind===`active`){i.push(t.capability);break}}return i}function Yv(e){return Xv.bind(null,e)}async function Xv(e,t,n){let r=await qv(e,t,n);return r.kind===`active`?r.authorization:null}async function Zv(e){for(let t of e.subjects){let n=await Dv.lookup(t);if(n.kind===`persistence_unavailable`)throw Error(`ECDSA capability persistence is unavailable`);if(n.kind!==`active`)continue;let r=n.manifest;if(r.signer.walletId===e.walletId&&r.signer.scope.targetMemberships.some(t=>H(t)===H(e.chainTarget)))return r}return null}async function Qv(e){let t=await K.resolveSelectedWalletAuthority(String(e.walletId));if(t.kind!==`resolved`)throw Error(`ECDSA material activation is ambiguous and the wallet selection is ${t.kind}`);let n=e.authorities.find(e=>e.walletAuthMethodId===t.selection.walletAuthMethodId);if(!n)throw Error(`ECDSA material activation has no access projection for the selected wallet auth method`);return await Dv.lookupByMaterialActivation({walletId:e.walletId,materialActivation:e.materialActivation,authority:n})}async function $v(e,t){let n=V(t.walletId),r=await Dv.listActiveWalletCapabilitySubjects(n);if(r.kind!==`resolved`)throw Error(`ECDSA capability subjects are ${r.kind}`);let i=async e=>{let i=await Zv({walletId:n,subjects:r.subjects,chainTarget:t.chainTarget});if(i)throw new Df({kind:`superseded`,supersessionKind:`material_activation_replaced`,preparedMaterialActivation:t.materialActivation,currentMaterialActivation:i.activation.materialActivation});return e()},a=await Dv.lookupByMaterialActivation({walletId:n,materialActivation:t.materialActivation});if(a.kind===`ambiguous_authority`&&(a=await Qv({walletId:n,materialActivation:t.materialActivation,authorities:a.authorities})),a.kind===`persistence_unavailable`||a.kind===`exact_record_conflict`||a.kind===`corrupt`)throw Error(`ECDSA material activation is ${a.kind}`);if(a.kind!==`active`)return await i(()=>{throw Error(`ECDSA capability manifest is missing`)});let o=a.manifest;if(o.signer.walletId!==n||!o.signer.scope.targetMemberships.some(e=>H(e)===H(t.chainTarget)))throw Error(`ECDSA capability manifest does not match the requested signer`);return{capability:await ey(o),lookup:a}}async function ey(e){return await Sd({authority:await Mv(e.signer.authority,{getWalletAuthMethodV2:e=>K.getWalletAuthMethodV2(e),listWalletAuthMethodsForWallet:e=>K.listWalletAuthMethodsForWallet(e),readEmailOtpProviderSubjectForWallet:e=>na(K,e)}),manifest:e,material:Rd({authority:e.signer.authority,materialActivation:e.activation.materialActivation,publicFacts:e.durableMaterial.roleLocalPublicFacts})})}async function ty(e,t){return(await $v(e,t)).capability}async function ny(e,t){let n=await qv(e,t,new Ja);if(n.kind!==`active`)throw Error(n.reason);let r=n.authorization,i=await $v(e,t),a=await Z_({relayerUrl:String(e.seamsWebConfigs.network.relayer?.url||``).trim(),operationCredential:r.operationCredential,curve:`ecdsa_secp256k1`,expectedMaterialActivation:i.capability.manifest.activation.materialActivation}),o=gv({walletKey:a.walletKey,lane:a.lane,material:{keyFamily:`ecdsa_secp256k1`,laneShareEpoch:a.lane.laneShareEpoch,lookup:i.lookup,runtime:{kind:`absent`}}});if(o.kind!==`active_wallet_execution_lane_v1`)throw Error(`Owner ECDSA execution lane is ${o.reason}`);return Td({capability:i.capability,authorization:r,nowMs:Date.now()})}async function ry(e,t,n){let r=await cy({walletId:V(t.walletId),chainTargets:t.chainTargets,...t.authMethod?{authMethod:t.authMethod}:{}});return await Promise.all(r.map(iy.bind(null,e,t.chainTargets,n)))}async function iy(e,t,n,r){let i=r.manifest,a=t.find(e=>i.signer.scope.targetMemberships.some(t=>H(e)===H(t)));if(!a)return{kind:`authorization_required`,capability:r};let o=await qv(e,{walletId:i.signer.walletId,chainTarget:a,materialActivation:i.activation.materialActivation},n);return o.kind===`active`?ay(r,o.authorization):{kind:`authorization_required`,capability:r}}function ay(e,t){try{return Td({capability:e,authorization:t,nowMs:Date.now()})}catch{return{kind:`authorization_required`,capability:e}}}async function oy(e,t,n,r){let i=r.manifest,a=i.signer.walletId,o=t.find(e=>i.signer.scope.targetMemberships.some(t=>H(e)===H(t)));if(!o)return{kind:`authorization_required`,capability:r};let s=Pv(await K.resolveSelectedWalletAuthority(String(a)),a),c=await Tv(a);if(!s||c.kind!==`found`||!Ov(c.record,s))return{kind:`authorization_required`,capability:r};let l=Ja.observationForConfirmation({relayerUrl:e.seamsWebConfigs.network.relayer.url,operationCredential:c.operationCredential},{walletSessionId:c.operationCredential.walletSessionId,quotaId:c.record.quotaId});if(!l)return iy(e,t,n,r);let u=l.status;if(u.status!==`active`)return{kind:`authorization_required`,capability:r};if(!zl(u.authorization,c.record)||!Ov(u.authorization,s))return iy(e,t,n,r);let d=await Gv({context:e,walletId:a,selected:s,session:c.record,operationCredential:c.operationCredential,status:u,chainTarget:o,materialActivation:i.activation.materialActivation,nowMs:Date.now()});if(d.kind!==`resolved`)return{kind:`authorization_required`,capability:r};let f=Nd(d.capability,Date.now());return f?ay(r,f):{kind:`authorization_required`,capability:r}}async function sy(e,t,n){let r=await cy({walletId:V(t.walletId),chainTargets:t.chainTargets,...t.authMethod?{authMethod:t.authMethod}:{}});return Promise.all(r.map(oy.bind(null,e,t.chainTargets,n)))}async function cy(e){let t=await Dv.listActiveWalletCapabilitySubjects(e.walletId);if(t.kind!==`resolved`)return[];let n=[];for(let r of t.subjects){let t=await Dv.lookup(r);if(t.kind!==`active`)continue;let i=t.manifest;if(!i.signer.scope.targetMemberships.some(t=>e.chainTargets.some(e=>H(e)===H(t))))continue;let a;try{a=await ey(i)}catch{continue}let o=a.authority.factor.kind;e.authMethod&&o!==e.authMethod||n.push(a)}return n}async function ly(e){let t=V(e),n=await Dv.listActiveWalletCapabilitySubjects(t);if(n.kind!==`resolved`)return[];let r=[];for(let e of n.subjects){let t=await Dv.lookup(e);t.kind===`active`&&r.push(t.manifest)}return r}const uy={listActiveEcdsaCapabilityManifestsForWallet:ly,listExactSealedSessionsForWallet:hs,resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K)},dy=wd(uy),fy=vd(uy);async function py(e){let t=await Tv(e);if(t.kind!==`found`||t.record.expiresAtMs<=Date.now())throw Error(`Email OTP step-up requires the exact unexpired Wallet Session`);return t.operationCredential}async function my(e){switch(e.authority.kind){case`live_session`:return await e.coordinator.requestTransactionSigningChallenge({kind:`wallet_session_challenge`,walletSession:e.walletSession,chain:e.chain,authLane:e.authority.authLane,operationFingerprintDigest:e.operationFingerprintDigest});case`capability_step_up`:return await e.coordinator.requestTransactionSigningChallenge({kind:`wallet_operation_challenge`,operationCredential:await py(e.walletSession.walletId),walletSession:e.walletSession,chain:e.chain,operationFingerprintDigest:e.operationFingerprintDigest})}}function hy(e){let t=Nv(e);return n_({runtimePorts:e.runtimePorts,stores:e.stores,ed25519YaoPublicCapabilityReferences:e.ed25519YaoPublicCapabilityReferences,seamsWebConfigs:e.seamsWebConfigs,nearClient:e.nearClient,touchIdPrompt:e.touchIdPrompt,userPreferencesManager:e.userPreferencesManager,nonceCoordinator:e.nonceCoordinator,ensureSealedRefreshStartupParity:e.ensureSealedRefreshStartupParity,touchConfirm:e.touchConfirm,passkeyMpcSession:e.passkeyMpcSession,passkeyMpcExport:e.passkeyMpcExport,getEmailOtpWarmSessionStatus:t=>e.emailOtpSessions.readWarmSessionStatusOnly(t),consumeEmailOtpWarmSessionUses:t=>e.emailOtpSessions.consumeWarmSessionUses(t),clearEmailOtpWarmSessionMaterial:t=>e.emailOtpSessions.clearVolatileWarmSessionMaterial({kind:`ecdsa`,thresholdSessionId:t}),getWalletSessionStatus:e=>t(e),resolveCanonicalEcdsaSigningCapability:t=>ty(e,t),resolveAuthorizedEcdsaSigningCapability:t=>ny(e,t),resolveActiveEcdsaWalletSessionAuthorization:Yv(e),resolveOwnerLaneScope:e.resolveOwnerLaneScope,signerWorkerManager:e.signerWorkerManager,getWorkerBaseOrigin:e.getWorkerBaseOrigin,shouldPrewarmUiConfirmUi:e.shouldPrewarmUiConfirmUi,getTheme:e.getTheme,signTempo:t=>Dd(e.getEnginePorts().tempoSigningDeps,t),activateAuthenticatedWalletState:t=>Jc(e.getEnginePorts().registrationAccountLifecycleDeps,{walletId:t.walletId,nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,nearClient:t.nearClient}),persistThresholdEcdsaBootstrapForWalletTarget:t=>_h({bootstrapStore:e.ecdsaBootstrapStore,walletId:t.walletId,chainTarget:t.chainTarget,bootstrap:t.bootstrap,signerAuth:t.signerAuth}),requestEmailOtpTransactionSigningChallenge:t=>my({coordinator:e.emailOtpSessions,walletSession:t.walletSession,chain:t.chain,authority:t.authority,operationFingerprintDigest:t.operationFingerprintDigest}),requestEmailOtpEd25519SigningChallenge:async({walletSession:t,operationFingerprintDigest:n})=>e.emailOtpSessions.requestTransactionSigningChallenge({kind:`wallet_operation_challenge`,operationCredential:await py(t.walletId),walletSession:t,chain:`near`,operationFingerprintDigest:n}),prepareNearEd25519YaoMaterialBoundary:e.prepareNearEd25519YaoMaterialBoundary,provisionThresholdEd25519Session:t=>mh({credentialStore:e.stores.recoveryAndDeviceLinking.credentialStore,touchIdPrompt:e.touchIdPrompt,touchConfirm:e.passkeyMpcSession,defaultRelayerUrl:e.seamsWebConfigs.network.relayer?.url||``,getSignerWorkerContext:()=>e.getEnginePorts().walletSessionActivationDeps.getSignerWorkerContext()},t),restorePersistedSessionForSigning:t=>t.authMethod===`passkey`?e.passkeyMpcSession.restorePersistedSessionForSigning(kv(t)):e.emailOtpSessions.restorePersistedSessionForSigning(t),readAvailableSigningLanesForSigning:async t=>im({activeWalletAuthorityEcdsaRuntimeReadPorts:{resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),readExactWithOperationCredential:q.readExactWithOperationCredential.bind(q)},ed25519YaoPublicCapabilityLanes:e.ed25519YaoPublicCapabilityReferences,isEd25519YaoPublicCapabilityActive:t=>{switch(t.auth.kind){case`email_otp`:return!0;case`passkey`:case`voiceid`:return e.getEnginePorts().ed25519YaoActiveClients.resolve({walletId:t.walletId,nearAccountId:t.nearAccountId,materialActivation:t.materialActivation})!==null}},readActiveWalletSessionAuthorization:Bv.bind(null,e.seamsWebConfigs.network.relayer.url),listEcdsaSigningCapabilitiesForWallet:(t.curve===`ecdsa`?sy:ry).bind(null,e)},t,Tn(e.seamsWebConfigs.network.chains)),provisionThresholdEcdsaSession:t=>cu({queueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,activationDeps:e.getEnginePorts().walletSessionActivationDeps,persistEcdsaRoleLocalReadyRecord:e.runtimePorts.storage.persistEcdsaRoleLocalReadyRecord},t),withThresholdEcdsaSigningQueue:t=>Hd({queueByKey:e.thresholdEcdsaSigningQueueByKey,...t,walletId:V(t.walletId)}),withThresholdEd25519CommitQueue:t=>Pf({queueByKey:e.thresholdEd25519CommitQueueByKey,...t})})}function gy(e){throw Error(`Unexpected Router A/B normal-signing config branch: ${String(e)}`)}function _y(e){let t=e.signing.routerAb.normalSigning;switch(t.mode){case`disabled`:throw Error(`[threshold-warm-session] Router A/B normal signing must be enabled for Ed25519 sessions`);case`enabled`:return{kind:Xe,signingWorkerId:t.signingWorkerId};default:return gy(t)}}var vy=class extends Error{code;details;constructor(e){super(`[WalletRuntimePostcondition] ${e.code} ${JSON.stringify(e.details)}`),this.name=`WalletRuntimePostconditionError`,this.code=e.code,this.details=e.details}};function yy(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function by(e,t){let n=Math.floor(Number(e));return Number.isFinite(n)&&n>t?n:null}function xy(e){return yy(e.remainingUses??e.policyHint?.remainingUses)}function Sy(e,t){return by(e.expiresAtMs??e.policyHint?.expiresAtMs,t)}function Cy(e){if(e.state===`missing`)return null;switch(e.source){case`durable_sealed_record`:case`public_capability_reference`:return{kind:e.source};default:return null}}function wy(e){let t=e.lanes.lanes.ed25519.near;if(t.state===`missing`)return`ed25519_lane_missing`;if(Gd(t)!==e.authMethod)return`auth_method_route_mismatch`;if(t.state!==`ready`&&t.state!==`restorable`)return`ed25519_lane_missing`;let n=xy(t),r=Sy(t,e.nowMs);if(t.authorizationState!==`authorized`||!t.authorization.operationCredential.walletSessionId||!t.authorization.session.quotaId||!t.thresholdSessionId||!n||!r)return`lane_inventory_mismatch`;let i=Cy(t);if(!i)return`lane_material_missing`;let a={authMethod:e.authMethod,target:{curve:`ed25519`},walletSessionId:t.authorization.operationCredential.walletSessionId,quotaId:t.authorization.session.quotaId,thresholdSessionId:t.thresholdSessionId,remainingSignatureUses:n,expiresAtMs:r,material:i};return t.state===`restorable`?{...a,state:`restorable`}:{...a,state:`ready`}}function Ty(e){let t=H(e.chainTarget),n=e.lanes.ecdsa.lanesByTarget[t];if(!n||n.state===`missing`)return`ecdsa_lane_missing`;let r=Qd(n);if(r!==e.authMethod)return`auth_method_route_mismatch`;if(n.state!==`ready`)return`ecdsa_lane_missing`;let i=xy(n),a=Sy(n,e.nowMs);return!n.authorization||!i||!a?`lane_inventory_mismatch`:{state:n.state,authMethod:r,target:{curve:`ecdsa`,chainTarget:e.chainTarget},authorizationId:n.authorization.session.authorizationId,materialActivationId:String(n.materialActivation.activationId),remainingSignatureUses:i,expiresAtMs:a,material:{kind:`canonical_capability`}}}async function Ey(e){let t=String(e.walletId||``).trim();if(!t)return{ok:!1,code:`wallet_missing`,details:{source:e.source}};let n=Xt(e.ownerScope.auth),r=await e.readOwnerScopedSigningLanes({walletId:t,ownerScope:e.ownerScope}),i=e.nowMs??Date.now(),a,o=new Map;for(let s of e.requiredTargets){if(s.curve===`ed25519`){let o=wy({lanes:r,authMethod:n,nowMs:i});if(typeof o==`string`)return{ok:!1,code:o,details:{source:e.source,walletId:t,authMethod:n,curve:`ed25519`,state:r.lanes.ed25519.near.state,candidateCount:r.candidates.ed25519.near.length}};a=o;continue}let c=Ty({lanes:r,chainTarget:s.chainTarget,authMethod:n,nowMs:i});if(typeof c==`string`){let i=H(s.chainTarget);return{ok:!1,code:c,details:{source:e.source,walletId:t,authMethod:n,curve:`ecdsa`,targetKey:i,state:r.ecdsa.lanesByTarget[i]?.state||`missing`,candidateCount:r.ecdsa.candidatesByTarget[i]?.length||0}}}o.set(H(s.chainTarget),c)}return{ok:!0,inventory:{...a?{ed25519:a}:{},ecdsaByTarget:o}}}async function Dy(e){let t=await Ey(e);if(!t.ok)throw new vy(t);return t.inventory}function Oy(e){let{record:t,operationCredential:n,scope:r}=e;return t.walletId===r.walletId&&t.authorityId===r.authorityId&&t.authMethodId===r.authMethodId&&t.authorityDigestB64u===r.authorityDigestB64u&&t.authorityRevocationEpoch===r.authorityRevocationEpoch&&n.kind===`opaque_wallet_session_operation_credential_v1`&&n.token.trim().length>0}async function ky(e){let{walletId:t,ports:n}=e,r=await n.resolveSelectedWalletAuthority(String(t));if(r.kind!==`resolved`)return{kind:`missing`};let{selection:i,authMethod:a,authority:o}=r;if(i.walletId!==t||i.walletAuthMethodId!==a.walletAuthMethodId||i.lockState!==`unlocked`||a.walletId!==t||a.walletAuthorityId!==o.authorityId||a.status!==`active`||o.walletId!==t||o.state!==`active`)return{kind:`missing`};let s=await n.readExactWithOperationCredential({walletId:t,authorityId:o.authorityId,authMethodId:a.walletAuthMethodId});switch(s.kind){case`found`:break;case`missing`:return{kind:`missing`};case`upgrade_required`:return{kind:`upgrade_required`}}return!Oy({record:s.record,operationCredential:s.operationCredential,scope:{walletId:t,authorityId:o.authorityId,authMethodId:a.walletAuthMethodId,authorityDigestB64u:o.authorityDigestB64u,authorityRevocationEpoch:o.revocationEpoch}})||s.record.expiresAtMs<=Date.now()?{kind:`missing`}:{kind:`authenticated`,state:{kind:`authenticated`,walletId:t,authMethod:a.kind},walletAuthMethodId:a.walletAuthMethodId}}function Ay(e,t){switch(e.kind){case`found`:return e;case`missing`:return null;case`upgrade_required`:throw new Ra(t)}}function jy(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required`);return n}function My(e){return{kind:e.kind,scope:{lifecycle_id:e.scope.lifecycle_id,root_share_epoch:e.scope.root_share_epoch,account_id:e.scope.account_id,threshold_session_id:e.scope.threshold_session_id,signer_set_id:e.scope.signer_set_id,signing_worker_id:e.scope.signing_worker_id,material_activation:e.scope.material_activation},applicationBinding:{wallet_id:e.applicationBinding.wallet_id,near_ed25519_signing_key_id:e.applicationBinding.near_ed25519_signing_key_id,signing_root_id:e.applicationBinding.signing_root_id,key_creation_signer_slot:e.applicationBinding.key_creation_signer_slot},participantIds:[e.participantIds[0],e.participantIds[1]],registeredPublicKey:e.registeredPublicKey.slice(),signingWorkerVerifyingShare:e.signingWorkerVerifyingShare.slice(),stateEpoch:e.stateEpoch,transcript:e.transcript.slice(),activeCapabilityBinding:[...e.activeCapabilityBinding],materialActivation:e.materialActivation}}function Ny(e){if(e.kind===`active`)return e.handle;throw Error(`Wallet custody Ed25519 active client is disposed`)}function Py(e){e.workerContext.requestWorkerOperation({kind:`emailOtp`,request:{type:`disposeEmailOtpEd25519YaoActiveClient`,payload:{activeClientHandle:e.handle}}}).catch(()=>void 0)}async function Fy(e){return(await e.workerContext.requestWorkerOperation({kind:`emailOtp`,request:{type:`disposeEmailOtpEd25519YaoActiveClient`,payload:{activeClientHandle:jy(e.activeClientHandle,`activeClientHandle`)}}})).removed}var Iy=class{lifecycle;activeMetadata;constructor(e,t,n){this.workerContext=e,this.lifecycle={kind:`active`,handle:jy(t,`activeClientHandle`)},this.activeMetadata=My(n)}async createSigningShare(e){return await this.workerContext.requestWorkerOperation({kind:`emailOtp`,request:{type:`createEmailOtpEd25519YaoSigningShare`,payload:{activeClientHandle:Ny(this.lifecycle),input:e}}})}metadata(){return My(this.activeMetadata)}status(){return this.lifecycle.kind===`active`?{kind:`active`}:{kind:`disposed`}}dispose(){if(this.lifecycle.kind!==`active`)return;let e=this.lifecycle.handle;this.lifecycle={kind:`disposed`},Py({workerContext:this.workerContext,handle:e})}};function Ly(e){switch(e.mode){case`ed25519_only`:return!1;case`ecdsa_only`:case`ed25519_and_ecdsa`:return!0}return!1}function Ry(e){switch(e.reason){case`missing_chain_target`:case`missing_key_handle`:case`invalid_key_handle`:case`duplicate_key_handles`:return e.reason;case`invalid_chain_target`:return`invalid_signer_record`}return e.reason,`invalid_signer_record`}function zy(e){let t=e.signer,n=xo({walletId:e.walletId,configuredTargets:e.configuredTargets,signer:e.signer}),r=typeof t.signerId==`string`&&t.signerId.trim()?t.signerId.trim():void 0;switch(n.kind){case`active_wallet_key`:return{kind:`active_ecdsa_signer_record`,targetKey:n.targetKey,chainTarget:n.chainTarget,walletKey:n.walletKey,publicCapability:n.publicCapability,source:`profile_continuity`,...r?{signerId:r}:{}};case`key_facts_inventory_required`:return{kind:`key_facts_inventory_required`,targetKey:n.targetKey,chainTarget:n.chainTarget,keyHandle:n.keyHandle,reason:n.reason,...r?{signerId:r}:{}};case`blocked`:return{kind:`blocked`,targetKey:n.targetKey,reason:Ry(n),...r?{signerId:r}:{}};case`skipped`:return{kind:`skipped`}}return{kind:`skipped`}}function By(e){let t=new Map;for(let n of e){let e=t.get(n.targetKey);if(!e){t.set(n.targetKey,n);continue}if(e.kind!==`active_ecdsa_signer_record`)continue;let r=ka(Ia(e.walletKey)),i=ka(Ia(n.walletKey));(String(e.walletKey.keyHandle)!==String(n.walletKey.keyHandle)||r!==i)&&t.set(n.targetKey,{kind:`blocked`,targetKey:n.targetKey,reason:`duplicate_key_handles`,...n.signerId?{signerId:n.signerId}:{}})}return t}function Vy(e){let t=String(e.keyHandle||``).trim();if(!t)throw Error(`[login] configured-target ECDSA warm key requires keyHandle`);let n=String(e.passkeyCredentialIdB64u||``).trim();if(e.key&&e.publicCapability&&String(e.publicCapability.client_id)!==String(e.key.walletId))throw Error(`[login] configured-target ECDSA public capability wallet mismatch`);return{chainTarget:e.chainTarget,targetKey:H(e.chainTarget),keyHandle:t,...e.key?{key:e.key}:{},...n?{passkeyCredentialIdB64u:n}:{},...e.existingRoleLocalMaterial?{existingRoleLocalMaterial:e.existingRoleLocalMaterial}:{},publicCapability:e.publicCapability?{kind:`persisted_public_capability`,value:e.publicCapability}:{kind:`missing_public_capability`}}}function Hy(e){let t=new Map;for(let n of e.keys){let r=H(n.chainTarget),i=String(n.keyHandle||``).trim();if(!i)continue;let a=t.get(r),o=String(a?.keyHandle||``).trim();if(o&&i&&o!==i)throw Error(`[login] threshold ECDSA warm-up received ambiguous ${e.source} key handles for ${r}`);if(a?.key&&n.key&&ka(a.key)!==ka(n.key))throw Error(`[login] threshold ECDSA warm-up received ambiguous ${e.source} key fingerprints for ${r}`);let s=a?.publicCapability.kind===`persisted_public_capability`?a.publicCapability.value:null,c=n.publicCapability.kind===`persisted_public_capability`?n.publicCapability.value:null;if(s&&c&&!ti(s,c))throw Error(`[login] threshold ECDSA warm-up received ambiguous ${e.source} public capabilities for ${r}`);let l=c||s,u=String(n.passkeyCredentialIdB64u||a?.passkeyCredentialIdB64u||``).trim(),d=n.existingRoleLocalMaterial||a?.existingRoleLocalMaterial;if(n.existingRoleLocalMaterial&&a?.existingRoleLocalMaterial&&!g(n.existingRoleLocalMaterial.materialActivation,a.existingRoleLocalMaterial.materialActivation))throw Error(`[login] threshold ECDSA warm-up received ambiguous ${e.source} role-local material for ${r}`);t.set(r,{chainTarget:n.chainTarget,targetKey:r,keyHandle:i||o,...n.key||a?.key?{key:n.key||a?.key}:{},...u?{passkeyCredentialIdB64u:u}:{},...d?{existingRoleLocalMaterial:d}:{},publicCapability:l?{kind:`persisted_public_capability`,value:l}:{kind:`missing_public_capability`}})}return[...t.values()]}function Uy(e,t){return{ecdsaKeys:Hy({source:`stored/relay`,keys:[...e.ecdsaKeys,...t?.ecdsaKeys||[]]}),...t?.runtimePolicyScope?{runtimePolicyScope:t.runtimePolicyScope}:e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{}}}function Wy(e){if(!e.configuredTargets.length)return{kind:`complete_configured_target_keys`,context:e.context};let t=new Map;for(let n of e.context.ecdsaKeys)t.set(n.targetKey,n);let n=e.configuredTargets.map(e=>H(e.chainTarget)).filter(e=>!t.has(e));if(n.length)return{kind:`missing_configured_target_keys`,missingTargets:n};let r={ecdsaKeys:Hy({source:`configured ECDSA target completion`,keys:[...t.values()]}),...e.context.runtimePolicyScope?{runtimePolicyScope:e.context.runtimePolicyScope}:{}},i=e.configuredTargets.filter(e=>!r.ecdsaKeys.some(t=>t.targetKey===H(e.chainTarget)));return i.length?{kind:`missing_configured_target_keys`,missingTargets:i.map(e=>H(e.chainTarget))}:{kind:`complete_configured_target_keys`,context:r}}function Gy(e){switch(e.completion.kind){case`complete_configured_target_keys`:return e.completion.context;case`missing_configured_target_keys`:throw Error(`[login] threshold ECDSA warm-up could not resolve configured target key facts from ${e.source} for ${e.completion.missingTargets.join(`, `)}`)}throw e.completion,Error(`[login] unsupported ECDSA warm-up key completion state`)}function Ky(e){let t=new Map;for(let n of e){let e=`${n.targetKey}:${n.keyHandle}`;t.set(e,{keyHandle:n.keyHandle,chainTarget:n.chainTarget})}return[...t.values()]}function qy(e){if(!Ly(e.selection)||e.configuredTargets.length===0)return{kind:`no_configured_ecdsa_targets`};let t=[...e.blockedRecords||[]],n=By(e.activeSignerRecords);for(let e of n.values())e.kind===`blocked`&&t.push(e);if(t.length)return{kind:`blocked`,blockedRecords:t};let r=new Map;for(let t of e.keyFactsInventoryRequiredRecords||[])r.set(t.targetKey,t);let i=[],a=[];for(let t of e.configuredTargets){let e=H(t),o=n.get(e);if(o?.kind===`active_ecdsa_signer_record`){a.push({targetKey:e,chainTarget:t,walletKey:o.walletKey,publicCapability:o.publicCapability});continue}let s=r.get(e);if(s){i.push(s);continue}i.push({kind:`key_facts_inventory_required`,targetKey:e,chainTarget:t,keyHandle:``,reason:`missing_key_facts`})}if(i.length===0)return{kind:`ready`,readyTargets:a};let o=i.filter(e=>String(e.keyHandle||``).trim()),s=e.runtimeConfig?.explicitKeyFactsInventoryMode??e.explicitKeyFactsInventoryMode,c=e.runtimeConfig?.allowAuthenticatedKeyFactsInventory??e.allowAuthenticatedKeyFactsInventory;return s===!0&&c===!0&&o.length===i.length?{kind:`awaiting_authenticated_key_facts_inventory`,keyFactsInventoryRequiredRecords:o,keyTargets:Ky(o)}:{kind:`key_facts_inventory_required`,keyFactsInventoryRequiredRecords:i}}async function Jy(e){let t=e.authenticators.map(e=>{let t=String(e.credentialId||``).trim();return t?{id:t,type:`public-key`,transports:Array.isArray(e.transports)?e.transports:[]}:null}).filter(e=>!!e);e.onPromptStarted();let n=await e.signingEngine.getAuthenticationCredentialsSerialized({subjectId:e.subjectId,challengeB64u:e.challengeB64u,allowCredentials:t,includeSecondPrfOutput:!1});return e.onPromptSucceeded(),n}function Yy(){if(typeof crypto>`u`||typeof crypto.getRandomValues!=`function`)throw Error(`Secure random is unavailable for passkey wallet unlock`);let e=new Uint8Array(32);return crypto.getRandomValues(e),P(e)}async function Xy(e){if(!e.currentCredential)return await e.collectCredentialForChallenge(Yy())}const Zy=new ra;async function Qy(e){let t=await Zy.listActiveWalletCapabilitySubjects(e);if(t.kind===`persistence_unavailable`)return{kind:`failed`,reason:`capability_subject_lookup_failed`};if(t.kind===`invalid_current_state`)return{kind:`failed`,reason:`invalid_capability_subject`};let n=[];for(let r of t.subjects)n.push({kind:`evm_family_ecdsa_wallet`,walletId:e,capability:r.capability,authority:r.authority,ecdsaThresholdKeyId:r.ecdsaThresholdKeyId});return{kind:`resolved`,subjects:n}}async function $y(e){return await Zy.listWalletActivationJournalSelectors(e)}function eb(e,t){let n=e?.[t];if(typeof n!=`string`||!n.trim())throw Error(`wallet unlock signer metadata requires ${t}`);return n.trim()}function tb(e,t){try{let n=String(t.metadata?.walletId||``).trim();if(n&&n!==String(e))return{kind:`invalid`};let r=Ai(t.signerSlot);return r?{kind:`valid`,subject:{kind:`near_ed25519_wallet`,walletId:e,nearAccountId:B(eb(t.metadata,`nearAccountId`)),nearEd25519SigningKeyId:Di(eb(t.metadata,`nearEd25519SigningKeyId`)),signerSlot:r}}:{kind:`invalid`}}catch{return{kind:`invalid`}}}async function nb(e){let t=[],n;try{n=await K.listActiveWalletSigners({walletId:e,signerFamily:`ed25519`})}catch{return{kind:`failed`,reason:`capability_subject_lookup_failed`}}for(let r of n){let n=tb(e,r);if(n.kind!==`valid`)return{kind:`failed`,reason:`invalid_capability_subject`};t.push(n.subject)}return{kind:`resolved`,subjects:t}}function rb(e){switch(e.kind){case`near_ed25519_wallet`:return[e.kind,e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot].join(`\0`);case`evm_family_ecdsa_wallet`:return[e.kind,e.walletId,e.capability,e.authority.authorityDigest,e.ecdsaThresholdKeyId].join(`\0`)}return``}function ib(e,t){for(let n of e)if(rb(n)===t)return!0;return!1}function ab(e,t){ib(e,rb(t))||e.push(t)}function ob(e){return e.kind===`near_ed25519_wallet`}function sb(e){let t=String(e||``).trim();if(!t)return null;try{return V(t)}catch{return null}}function cb(e){return String(e||``).trim()||null}function lb(e){let t=cb(e?.profileId);return t?{kind:`last_used_profile`,profileId:t}:{kind:`none`}}async function ub(){return lb(await K.getLastProfileState().catch(()=>null))}async function db(e){let t=sb(e);return t?{kind:`explicit_wallet`,walletId:t}:e?{kind:`none`}:await ub()}function fb(e){let t=String(e.metadata?.walletId||``).trim();if(!t)return null;try{return V(t)}catch{return null}}function pb(e){let t=[],n=new Set;for(let r of e){let e=fb(r);if(!e)return{kind:`invalid`};let i=String(e);n.has(i)||(n.add(i),t.push(e))}return{kind:`resolved`,walletIds:t}}async function mb(e){let t;try{t=await K.getProfile(e)}catch{return{kind:`unresolvable_profile`,reason:`capability_subject_lookup_failed`}}if(!t)return{kind:`unresolvable_profile`,reason:`missing_wallet_profile`};let n;try{n=await K.listAccountSignersByProfile({profileId:e,status:`active`})}catch{return{kind:`unresolvable_profile`,reason:`capability_subject_lookup_failed`}}if(n.length===0)return{kind:`unresolvable_profile`,reason:`missing_requested_capability_subject`};let r=pb(n);if(r.kind===`invalid`)return{kind:`unresolvable_profile`,reason:`invalid_wallet_profile`};let i=r.walletIds;return i.length===0?{kind:`unresolvable_profile`,reason:`invalid_wallet_profile`}:i.length>1?{kind:`unresolvable_profile`,reason:`ambiguous_wallet_profile`}:{kind:`resolved_wallet`,walletId:i[0]}}function hb(e,t){let n=t[0];return n?{kind:`resolved`,subjectSet:{kind:`wallet_unlock_subject_set`,walletId:e,subjects:[n,...t.slice(1)]}}:{kind:`missing_requested_capability_subject`}}function gb(e){return e.subjects.filter(ob).length>1?`ambiguous_wallet_profile`:null}async function _b(e){let t=V(e.walletId),n=[];switch(e.requestedCapabilityFamilies.kind){case`near_ed25519_only`:case`all_registered_mpc`:{let r=await nb(t);if(r.kind===`failed`)return{kind:`capability_subject_resolution_failed`,reason:r.reason};for(let e of r.subjects)ab(n,e);if(e.requestedCapabilityFamilies.kind===`near_ed25519_only`)return hb(t,n);break}case`evm_family_ecdsa_only`:break;default:e.requestedCapabilityFamilies}let r=await Qy(t);if(r.kind===`failed`)return{kind:`capability_subject_resolution_failed`,reason:r.reason};for(let e of r.subjects)ab(n,e);return hb(t,n)}async function vb(e){let t=await db(e);if(t.kind===`none`)return{kind:`no_session_request`};let n,r;if(t.kind===`last_used_profile`){let e=await mb(t.profileId);if(e.kind===`unresolvable_profile`)return{kind:`unresolvable_profile`,profileId:t.profileId,reason:e.reason};n=e.walletId,r=`host_last_used_profile`}else n=t.walletId,r=`profile_projection`;let i=await _b({walletId:String(n),requestedCapabilityFamilies:{kind:`all_registered_mpc`}});if(i.kind===`missing_requested_capability_subject`)return{kind:`no_session_for_wallet`,walletId:n,reason:`missing_requested_capability_subject`};if(i.kind===`capability_subject_resolution_failed`)return{kind:`unresolvable`,walletId:n,reason:i.reason};let a=i.subjectSet,o=gb(a);return o?{kind:`unresolvable`,walletId:n,reason:o}:{kind:`resolved`,walletId:n,subjectSet:a,source:r}}function yb(e,t){return globalThis.fetch(e,t)}function bb(e){switch(e?.mode){case`ed25519_only`:return{mode:`ed25519_only`,ed25519:!0};case`ecdsa_only`:return{mode:`ecdsa_only`,ecdsa:!0};case`ed25519_and_ecdsa`:case void 0:return{mode:`ed25519_and_ecdsa`,ed25519:!0,ecdsa:!0}}return Q(e)}function xb(e){if(e.selection)return bb(e.selection);let t=!1,n=!1;for(let r of e.subjectSet.subjects)switch(r.kind){case`near_ed25519_wallet`:t=!0;break;case`evm_family_ecdsa_wallet`:n=!0;break;default:return Q(r)}if(t&&n)return{mode:`ed25519_and_ecdsa`,ed25519:!0,ecdsa:!0};if(t)return{mode:`ed25519_only`,ed25519:!0};if(n)return{mode:`ecdsa_only`,ecdsa:!0};throw Error(`[login] wallet unlock subject set has no supported capability`)}function Sb(e){return e.kind===`near_ed25519_wallet`}function Cb(e){return e.kind===`evm_family_ecdsa_wallet`}function wb(e){let t=e.subjects.filter(Sb);if(t.length===0)return null;if(t.length>1)throw Error(`[WalletSession] multiple NEAR Ed25519 subjects found for wallet session`);return t[0]||null}function Tb(e){let t=wb(e.subjectSet),n=e.subjectSet.subjects.filter(Cb);for(let t of e.subjectSet.subjects)if(String(t.walletId)!==String(e.subjectSet.walletId))throw Error(`[login] wallet unlock subject belongs to a different wallet`);switch(e.selection.mode){case`ed25519_only`:if(!t||n.length!==0)throw Error(`[login] NEAR Ed25519 unlock requires one exact NEAR subject set`);return{kind:`near_ed25519_capable_wallet`,walletId:e.subjectSet.walletId,subjectSet:e.subjectSet,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot};case`ecdsa_only`:{let[r,...i]=n;if(t||!r)throw Error(`[login] ECDSA-only unlock requires exact ECDSA subjects`);return{kind:`evm_family_ecdsa_only_wallet`,walletId:e.subjectSet.walletId,subjectSet:e.subjectSet,ecdsaSubjects:[r,...i]}}case`ed25519_and_ecdsa`:if(!t||n.length===0)throw Error(`[login] combined unlock requires exact NEAR and ECDSA subjects`);return{kind:`near_ed25519_capable_wallet`,walletId:e.subjectSet.walletId,subjectSet:e.subjectSet,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot}}return Q(e.selection)}function Eb(e){if(e.kind===`near_ed25519_capable_wallet`)return e;throw Error(`[login] NEAR Ed25519 warm-up requires an exact NEAR subject`)}function Db(e){let t=new Set;for(let n of e.identity.subjectSet.subjects)n.kind===`evm_family_ecdsa_wallet`&&t.add(String(n.ecdsaThresholdKeyId));if(t.size===0)throw Error(`[login] ECDSA warm-up requires an exact ECDSA unlock subject`);for(let n of e.context.ecdsaKeys){let e=String(n.key?.ecdsaThresholdKeyId||``).trim();if(e&&!t.has(e))throw Error(`[login] ECDSA warm-up key does not match the unlock subject set`)}}function Ob(e){let t=[];for(let n of e.subjects)n.kind===`evm_family_ecdsa_wallet`&&t.push({capability:n.capability,authority:n.authority});return t}async function kb(e){let t=!1,n=!1;for(let r of e.selectors){let i=await Uu({workerCtx:e.workerCtx,command:{kind:`reconcile_canonical_ecdsa_activation_v1`,capability:r.capability,authority:r.authority}});switch(i.kind){case`canonical_ecdsa_activation_reconciliation_absent_v1`:break;case`canonical_ecdsa_activation_reconciliation_finalized_v1`:t=!0;break;case`canonical_ecdsa_activation_reconciliation_pending_v1`:n=!0;break;case`canonical_ecdsa_activation_reconciliation_failed_v1`:return{kind:`failed`,didFinalize:t,code:i.code};default:Q(i)}}return n?{kind:`pending`,didFinalize:t}:{kind:`settled`,didFinalize:t}}function Ab(e){switch(e.kind){case`settled`:return;case`pending`:console.warn(`[login] ECDSA activation remains prepared and requires confirmation`);return;case`failed`:console.warn(`[login] ECDSA activation reconciliation failed without changing active state`,{code:e.code});return}Q(e)}function jb(e){let t=pa({walletId:e.walletId});switch(e.kind){case`passkey`:{let n=_a(e.rpId);return n.ok?ma({walletAuthMethodId:e.walletAuthMethodId,scope:fa({wallet:t,rpId:n.value}),credentialIdB64u:e.credentialIdB64u}):null}case`email_otp`:return ga({walletAuthMethodId:e.walletAuthMethodId,wallet:t,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId});case`voiceid`:return ha({walletAuthMethodId:e.walletAuthMethodId,wallet:t,deviceKeyId:e.deviceKeyId});default:return null}}function Mb(e){return{walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.walletAuthMethodId}}async function Nb(e){return await U({authority:Mb(e)})}async function Pb(e){let t=hi({walletId:e.authMethod.walletId,factor:{kind:`email_otp`,provider:e.provider,providerUserId:e.providerSubjectId},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:e.authMethod.emailHashHex},bindingId:e.authMethod.walletAuthMethodId});if(!t)throw Error(`[login] linked Email OTP provider identity does not match selected authority`);return t}async function Fb(e){if(e.selection.authMethod.kind===`passkey`)return Mb(e.selection.authMethod);if(e.selection.authMethod.kind===`voiceid`)throw Error(`[login] VoiceID linked-device authority requires its own unlock path`);let t=e.providerIdentity;if(!t)throw Error(`[login] linked Email OTP authority provider identity is missing`);return await Pb({authMethod:e.selection.authMethod,provider:t.provider,providerSubjectId:t.providerSubjectId})}async function Ib(e){return await U({authority:await Fb(e)})}function Lb(e,t,n,r){let i=null;for(let a of e)if(!(a.authorityId!==t||a.walletAuthMethodId!==n||a.activationId!==r.activationId)){if(i)return null;i=a}return i}function Rb(e){let t=[];return e.selection.walletId!==e.walletId&&t.push(`selection_wallet_id`),!e.allowUnselectedSibling&&e.selection.walletAuthMethodId!==e.authMethod.walletAuthMethodId&&t.push(`selection_auth_method_id`),e.authMethod.walletId!==e.walletId&&t.push(`auth_method_wallet_id`),e.authMethod.status!==`active`&&t.push(`auth_method_inactive`),e.expectedKind&&e.authMethod.kind!==e.expectedKind&&t.push(`auth_method_not_${e.expectedKind}`),e.authority.walletId!==e.walletId&&t.push(`authority_wallet_id`),e.authority.state!==`active`&&t.push(`authority_inactive`),e.authority.authorityId!==e.authMethod.walletAuthorityId&&t.push(`authority_auth_method_id`),t}async function zb(e){let t=_(e);if(!t.ok)return null;let n=t.value;try{let e=await K.resolveSelectedWalletAuthority(String(n));if(e.kind!==`resolved`)return null;let{selection:t,authMethod:r,authority:i}=e;return Rb({walletId:n,selection:t,authMethod:r,authority:i,expectedKind:`passkey`}).length>0||r.status!==`active`||r.kind!==`passkey`||i.state!==`active`||i.provenance.kind!==`device_link`?null:{kind:`linked_device_passkey_authority_selection_v1`,walletId:n,selection:t,authMethod:r,authority:i,signerMaterials:e.signerMaterials,exportRoot:e.exportRoot}}catch{return null}}async function Bb(e){let t=_(e.walletIdInput),n=String(e.emailHashHex||``).trim().toLowerCase(),r=String(e.providerSubjectId||``).trim();if(!t.ok||!n||!r)return{kind:`none`};let i=t.value,a;try{a=e.walletAuthMethodId?await K.resolveWalletAuthorityForMethod(String(i),e.walletAuthMethodId):await K.resolveSelectedWalletAuthority(String(i))}catch(e){return{kind:`rejected`,message:e instanceof Error?e.message:`Selected Email OTP authority is unavailable`}}if(a.kind===`missing_selection`)return{kind:`none`};if(a.kind!==`resolved`)return{kind:`rejected`,message:`Selected Email OTP authority is unavailable`};let{selection:o,authMethod:s,authority:c}=a;if(s.kind!==`email_otp`)return{kind:`none`};if(Rb({walletId:i,selection:o,authMethod:s,authority:c,expectedKind:`email_otp`,allowUnselectedSibling:!!e.walletAuthMethodId}).length>0||s.emailHashHex.toLowerCase()!==n)return{kind:`rejected`,message:`Selected Email OTP authority is inactive or does not match the verified email`};if(s.status!==`active`||c.state!==`active`)return{kind:`rejected`,message:`Selected Email OTP authority is inactive`};try{await Pb({authMethod:s,provider:e.provider,providerSubjectId:r})}catch(e){return{kind:`rejected`,message:e instanceof Error?e.message:`Selected Email OTP provider identity does not match the local authority`}}return c.provenance.kind===`device_link`&&a.signerMaterials.length===0?{kind:`rejected`,message:`Selected linked Email OTP authority has no signer material`}:a.signerMaterials.some(e=>e.kind!==`wallet_authority_linked_signer_material_v1`)?{kind:`rejected`,message:`Selected Email OTP authority has an invalid linked signer material set`}:{kind:`selected`,selection:{kind:`linked_device_email_otp_authority_selection_v1`,walletId:i,selection:o,authMethod:s,authority:c,signerMaterials:a.signerMaterials,exportRoot:a.exportRoot}}}function Vb(e,t){let n=t.keyFamily===`ed25519`?e.signerActivations.ed25519:e.signerActivations.ecdsa;if(!n)throw Error(`[login] linked Wallet Session requested unavailable ${t.keyFamily} material`);if(!g(n.materialActivation,t.materialActivation))throw Error(`[login] linked Wallet Session material activation does not match authority`);return n.materialActivation}function Hb(e,t){if(t.walletId!==e.walletId||t.authorityId!==e.authority.authorityId||t.authMethodId!==e.authMethod.walletAuthMethodId||t.authorityDigestB64u!==e.authority.authorityDigestB64u||t.authorityRevocationEpoch!==e.authority.revocationEpoch)throw Error(`[login] linked Wallet Session identity does not match selected authority`);for(let n of t.capabilitySubjects)switch(n.kind){case`sign`:case`export_keys`:{let t=Vb(e.authority,n),r=Lb(e.signerMaterials,e.authority.authorityId,e.authMethod.walletAuthMethodId,t);if(!r||r.keyFamily!==n.keyFamily)throw Error(`[login] linked Wallet Session signer material is unavailable`);if(!g(r.materialActivation,n.materialActivation))throw Error(`[login] linked Wallet Session signer material activation is invalid`);break}case`link_devices`:case`revoke_devices`:break;default:return Q(n)}}function Ub(e,t){let n=e.targetFactor;if(n.kind!==`passkey`||n.walletAuthMethodId!==t.authMethod.walletAuthMethodId||n.rpId!==t.authMethod.rpId||n.credentialIdB64u!==t.authMethod.credentialIdB64u)throw Error(`[login] linked passkey signer material target factor does not match V2 auth`)}async function Wb(e){let t=wl(e.credential);if(!t)throw Error(`[login] linked passkey unlock requires WebAuthn PRF.first output`);let n;try{n=F(t)}catch{throw Error(`[login] linked passkey unlock returned an invalid PRF.first output`)}try{if(n.byteLength!==32)throw Error(`[login] linked passkey unlock requires a 32-byte PRF.first output`);return await Gb({selection:e.selection,factorSecret32:n})}finally{n.fill(0)}}async function Gb(e){if(e.factorSecret32.byteLength!==32)throw Error(`[login] linked signer material requires a 32-byte factor secret`);let t=e.factorSecret32.slice();try{let n=[];for(let r of e.selection.signerMaterials){if(r.kind!==`wallet_authority_linked_signer_material_v1`)throw Error(`[login] linked signer material is not a linked sealed record`);e.selection.kind===`linked_device_passkey_authority_selection_v1`?Ub(r,e.selection):Kb(r,e.selection);let i=await ea({record:r,factorSecret:t,expected:{authorityId:e.selection.authority.authorityId,walletId:e.selection.walletId,walletAuthMethodId:e.selection.authMethod.walletAuthMethodId,packageSetDigestB64u:r.packageSetDigestB64u,targetFactor:r.targetFactor,materialActivation:r.materialActivation,keyFamily:r.keyFamily}});if(i.kind!==`opened_wallet_authority_linked_signer_material_v1`)throw Error(`[login] linked signer material open failed: ${i.reason}`);n.push(i)}let[r,...i]=n;if(!r)throw Error(`[login] linked signer material set is empty`);return[r,...i]}finally{t.fill(0)}}function Kb(e,t){let n=e.targetFactor;if(n.kind!==`email_otp`||n.walletAuthMethodId!==t.authMethod.walletAuthMethodId||n.emailHashHex.toLowerCase()!==t.authMethod.emailHashHex.toLowerCase()||n.registrationAuthorityId!==t.authMethod.registrationAuthorityId)throw Error(`[login] linked Email OTP signer material target factor does not match V2 auth`)}async function qb(e){if(e.factorSecret32.byteLength!==32)throw Error(`[login] linked Email OTP unlock requires a 32-byte factor secret`);return await Gb({selection:e.selection,factorSecret32:e.factorSecret32})}function Jb(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`[login] recent unlock account is missing walletId`);let n=String(e.loginDisplayName||``).trim()||t;return{walletId:t,nearAccountId:e.nearAccountId,displayName:n,signerSlot:e.signerSlot,...typeof e.lastLogin==`number`?{lastLogin:e.lastLogin}:{},authMethod:e.authMethod||null}}async function Yb(e){let t=await K.resolveSelectedWalletAuthority(String(e.walletId)).catch(()=>null);if(!t||t.kind!==`resolved`||t.selection.walletAuthMethodId!==e.walletAuthMethodId||t.authMethod.status!==`active`||t.authority.state!==`active`||t.authority.provenance.kind!==`device_link`)return null;let n=await Nx({walletId:e.walletId,authMethod:t.authMethod,authority:t.authority,signerMaterials:t.signerMaterials});if(n.kind!==`resolved`)return null;let r;switch(t.authMethod.kind){case z.passkey:r=z.passkey;break;case z.emailOtp:r=z.emailOtp;break;case`voiceid`:return null;default:return Q(t.authMethod)}return{walletId:String(e.walletId),nearAccountId:n.subject.nearAccountId,displayName:String(e.walletId),signerSlot:n.subject.signerSlot,lastLogin:e.updatedAtMs,authMethod:r}}function Xb(e){return`${e.walletId}:${e.authMethod??``}`}function Zb(e){let t=null;for(let n of e)(!t||(n.lastLogin??0)>(t.lastLogin??0))&&(t=n);return t}async function Qb(e){return e?(await K.listWalletAuthMethodsV2ForWallet(String(e)).catch(()=>[])).filter(e=>e.status===`active`).map(jb).filter(e=>!!e):[]}function $b(e){if(e.authMethod===z.passkey)return null;if(e.authMethod!==z.emailOtp)throw Error(`[login] unsupported wallet auth method for warm-up: ${e.authMethod}`);let t=e.authMethods.filter(e=>e.kind===`email_otp`);if(t.length!==1)throw Error(`[login] Email OTP warm-up requires one active wallet auth-method binding`);let n=t[0];if(String(n.wallet.walletId)!==String(e.walletId))throw Error(`[login] Email OTP warm-up auth-method binding wallet mismatch`);return n}async function ex(e){return $b({authMethods:await Qb(e.walletId),authMethod:e.authMethod,walletId:e.walletId})}async function tx(e){let[t,n]=await Promise.all([K.listWalletPasskeyAuthenticators(String(e)),K.listWalletAuthMethodsV2ForWallet(String(e)).catch(()=>[])]),r=new Set;for(let e of n)e.kind===`passkey`&&e.status===`active`&&r.add(e.credentialIdB64u);return t.filter(e=>r.has(e.credentialId))}function nx(e){return e?.status===`active`}function rx(e){if(!e.request)return null;switch(e.request.mode){case`wallet_session_operation_credential_v1`:try{return{kind:`wallet_session_operation_credential_v1`,operationCredential:ix(e.request.operationCredential)}}catch{return null}case`webauthn`:return{kind:`webauthn`}}return null}function ix(e){if(e.kind===`opaque_wallet_session_operation_credential_v1`)return ze(e);if(e.kind!==`opaque_hosted_wallet_session_operation_credential_v1`||!/^wsh_[A-Za-z0-9_-]{43}$/.test(e.token))throw Error(`Hosted Wallet Session operation credential is invalid`);let t=Tt(e.walletSessionId);if(!t.ok)throw Error(`Hosted Wallet Session ID is invalid: ${t.error.message}`);return{kind:e.kind,home:He(e.home),token:e.token,walletSessionId:t.value}}function ax(){return{kind:`none`}}function ox(e){return String(e.authenticators.find(t=>t.signerSlot===e.signerSlot)?.credentialId||e.authenticators[0]?.credentialId||``).trim()}function sx(e){return pi({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})}function cx(e){if(!e.wantsEd25519Warmup)return{kind:`not_requested`};if(e.authMethod===z.passkey)return{kind:`passkey`,authority:{kind:`wallet_auth_authority`,authority:sx({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.passkeyCredentialIdB64u})},source:`login`};throw e.authMethod===z.emailOtp?Error(`[login] Email OTP warm-up requires its proof-bound unlock flow`):Error(`[login] unsupported wallet auth method for Ed25519 warm-up: ${e.authMethod}`)}function lx(e){if(e.kind===`not_requested`)throw Error(`[login] threshold Ed25519 warm-up authority is missing`);return e}function ux(e){return e.authority.kind===`email_otp`?e.authority:{kind:`passkey`,authority:{kind:`wallet_auth_authority`,authority:sx({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})},source:`login`}}function dx(e){switch(e.kind){case`passkey`:return{kind:`passkey`,rpId:wa(e.authority.authority.verifier.rpId),credentialIdB64u:String(e.authority.authority.factor.credentialIdB64u||``).trim()};case`email_otp`:return{kind:`email_otp`,providerSubjectId:String(e.authority.authority.factor.providerUserId||``).trim()}}throw Error(`[login] unsupported Ed25519 exact provision authority`)}function fx(e){return Cl({signer:fl({walletId:e.walletBinding.walletId,nearAccountId:e.walletBinding.nearAccountId,nearEd25519SigningKeyId:e.walletBinding.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:dx(e.authority),walletSessionId:e.walletSessionId,quotaId:e.quotaId,thresholdSessionId:e.thresholdSessionId})}function px(e){switch(e.mintPlan.kind){case`not_requested`:throw Error(`[login] threshold Ed25519 mint plan is missing`);case`wallet_custody`:return e.ecdsaMint?{kind:`exact_ed25519_provisioning`,operationCredential:e.ecdsaMint.operationCredential,laneIdentity:fx({walletBinding:e.walletBinding,signerSlot:e.signerSlot,thresholdSessionId:e.mintPlan.thresholdSessionId,walletSessionId:e.ecdsaMint.operationCredential.walletSessionId,quotaId:e.ecdsaMint.quotaId,authority:e.authority})}:{kind:`fresh_ed25519_provisioning`,materialActivation:e.mintPlan.custody.ed25519.capability.materialActivation};case`fresh`:throw Error(`[login] fresh Ed25519 passkey provisioning requires canonical material activation`);case`ecdsa_authorized`:if(!e.ecdsaMint)throw Error(`[login] threshold Ed25519 warm-up requires the ECDSA bootstrap session minted during unlock`);return{kind:`exact_ed25519_provisioning`,operationCredential:e.ecdsaMint.operationCredential,laneIdentity:fx({walletBinding:e.walletBinding,signerSlot:e.signerSlot,thresholdSessionId:e.mintPlan.thresholdSessionId,walletSessionId:e.ecdsaMint.operationCredential.walletSessionId,quotaId:e.ecdsaMint.quotaId,authority:e.authority})}}return Q(e.mintPlan)}function mx(e,t){if(e.kind===`fresh_ed25519_provisioning`&&e.materialActivation)return e.materialActivation;if(t.kind===`wallet_custody`)return t.custody.ed25519.capability.materialActivation;throw Error(`[login] passkey Ed25519 warm-up requires a canonical material activation`)}function hx(e){return e.mintPlan.kind===`wallet_custody`?{relayerKeyId:e.mintPlan.custody.ed25519.relayerKeyId,participantIds:e.mintPlan.custody.ed25519.participantIds,runtimePolicyScope:e.mintPlan.custody.ed25519.capability.runtimePolicyScope,routerAbNormalSigning:e.fallback.routerAbNormalSigning}:e.fallback}function gx(e){let t=e.session,n=e.custody.ed25519,r=e.credential?wl(e.credential):``;if(t.walletId!==String(e.walletBinding.walletId)||t.nearAccountId!==String(e.walletBinding.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.walletBinding.nearEd25519SigningKeyId)||n.signerSlot!==e.signerSlot||t.relayerKeyId!==e.provisionScope.relayerKeyId||t.thresholdSessionId!==n.capability.lifecycle.thresholdSessionId||t.remainingUses!==e.remainingUses||!DS(t.participantIds,e.provisionScope.participantIds)||!e.provisionScope.runtimePolicyScope||!kS(t.runtimePolicyScope,e.provisionScope.runtimePolicyScope)||!OS(t.routerAbNormalSigning,e.provisionScope.routerAbNormalSigning)||!r)throw Error(`[login] verified unlock returned an invalid Ed25519 Wallet Session`);switch(t.sessionKind){case`issued_exact_wallet_session`:if(t.operationCredential.walletSessionId!==t.walletSessionId)throw Error(`[login] verified unlock returned a mismatched Ed25519 credential`);return{ok:!0,...t,passkeyPrfFirstB64u:r};case`already_committed_exact_wallet_session`:{let n=e.unlockAuthorization;if(!n)throw Error(`[login] verified unlock reused an Ed25519 Wallet Session without its authorization`);if(n.operationCredential.walletSessionId!==t.walletSessionId||n.record.walletId!==t.walletId||n.record.authorizationId!==t.authorizationId||n.record.quotaId!==t.quotaId||n.record.expiresAtMs!==t.expiresAtMs)throw Error(`[login] verified unlock reused a mismatched Ed25519 Wallet Session`);return{ok:!0,...t,operationCredential:n.operationCredential,passkeyPrfFirstB64u:r}}default:return Q(t)}}function _x(e){return e.hasLoginCredential?{kind:`passkey_credential_already_collected`}:e.requiresLocalPasskeyUnlock?e.requireThresholdWarmup?{kind:`wallet_unlock_owns_passkey_credential`}:{kind:`local_unlock_passkey_assertion`}:{kind:`no_local_passkey_required`}}function vx(e){if(e.warmupPlan.signersToWarm.includes(`ed25519`)&&e.requiresLocalPasskeyUnlock)return{kind:`wallet_custody`};if(e.hasLoginCredential)return{kind:`existing_passkey_credential`};if(e.routeAuthorization.kind,e.requiresLocalPasskeyUnlock)throw Error(`[login] passkey warm-up requires the verified wallet-unlock credential`);return{kind:`no_passkey_credential_required`}}function yx(e){if(!e.credentialIds)return e.authenticators;let t=new Set;for(let n of e.credentialIds)t.add(n.trim());let n=[];for(let r of e.authenticators)t.has(String(r.credentialId||``).trim())&&n.push(r);if(!n.length)throw Error(`[login] no local authenticator matches the required credential`);return n}function bx(e){let t=[],n=new Set;for(let r of e){let e=String(r.credentialId||``).trim();!e||n.has(e)||(n.add(e),t.push(e))}return t}function xx(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let e=typeof r==`string`?r.trim():``;!e||n.has(e)||(n.add(e),t.push(e))}return t}function Sx(e){let t=[];for(let n of e.authenticators)n.signerSlot===e.signerSlot&&t.push(n);let n=bx(t.length>0?t:e.authenticators);if(n.length===0)throw Error(`[login] selected wallet has no local passkey credential ID`);if(e.serverCredentialIds.length===0)return n;let r=new Set(e.serverCredentialIds),i=[];for(let e of n)r.has(e)&&i.push(e);if(i.length===0)throw Error(`[login] server passkey allow-list does not match local wallet credentials`);return i}function Cx(e){let t=Tb({subjectSet:e.subjectSet,selection:e.selection});switch(e.selection.mode){case`ed25519_only`:return{kind:`near_ed25519_only`,wantsEd25519Warmup:!0,wantsEcdsaWarmup:!1};case`ecdsa_only`:if(t.kind!==`evm_family_ecdsa_only_wallet`)throw Error(`[login] ECDSA-only warm-up requires exact ECDSA subjects`);return{kind:`evm_family_ecdsa_only`,wantsEd25519Warmup:!1,wantsEcdsaWarmup:e.hasConfiguredEcdsaTargets};case`ed25519_and_ecdsa`:return{kind:`near_ed25519_and_evm_family_ecdsa`,wantsEd25519Warmup:!0,wantsEcdsaWarmup:e.hasConfiguredEcdsaTargets}}return Q(e.selection)}function wx(e){let t=String(e.context.configs?.network.relayer?.url||``).trim();if(!t)throw Error(`[login] threshold warm session requires relayer.url to be configured`);let n=jo(e.context.configs.network.chains),r=Cx({subjectSet:e.subjectSet,selection:e.selection,hasConfiguredEcdsaTargets:n.length>0}),i=r.wantsEcdsaWarmup,a=r.wantsEd25519Warmup,o=String(e.context.signingEngine.getRpId()||``).trim();return{kind:`threshold_login_warmup_phase_input`,signerSlot:e.signerSlot,selection:e.selection,relayerUrl:t,rpId:o,configuredEcdsaTargets:n,selectedEcdsaTargets:i?n:[],wantsEd25519Warmup:a,wantsEcdsaWarmup:i,ed25519SessionAuthority:cx({wantsEd25519Warmup:a,authMethod:e.authMethod,walletId:e.subjectSet.walletId,rpId:o,passkeyCredentialIdB64u:ox({authenticators:e.authenticators,signerSlot:e.signerSlot}),routeAuthorization:e.routeAuthorization}),keyFactsInventoryAuthority:e.keyFactsInventoryAuthority,routeAuthorization:e.routeAuthorization}}async function Tx(e){let t=[...e.signersWarmed.includes(`ed25519`)?[{curve:`ed25519`}]:[],...e.signersWarmed.includes(`ecdsa`)?jo(e.context.configs.network.chains).map(e=>({curve:`ecdsa`,chainTarget:e.chainTarget})):[]],n=Tl(e.credential);if(!n)throw Error(`[login] runtime lane selection requires the authenticated credential`);let r=String(e.walletIdentity.walletId),i=await K.getWalletPasskeyAuthenticator({walletId:r,credentialId:n}),a=Ai(i?.signerSlot,{min:1});if(!i||a===null)throw Error(`[login] authenticated credential resolves no exact local authenticator for its signer slot`);let o={auth:{kind:`passkey`,rpId:wa(e.context.signingEngine.getRpId()),credentialIdB64u:n},signerSlot:a};t.length!==0&&await Dy({source:`wallet_unlock`,walletId:String(e.walletIdentity.walletId),ownerScope:o,requiredTargets:t,readOwnerScopedSigningLanes:async t=>await e.context.signingEngine.readOwnerScopedSigningLanes(t,e.statusReads)})}async function Ex(e){let t=Tl(e.credential);if(!t)throw Error(`[login] successful Passkey unlock omitted its credential identity`);let n=await Us({walletId:e.walletIdentity.walletId,rpId:e.context.signingEngine.getRpId(),credentialIdB64u:t});await e.context.signingEngine.markWalletSelectionUnlocked({walletId:e.walletIdentity.walletId,walletAuthMethodId:n.walletAuthMethodId})}function Dx(e){if(e.userData&&String(e.userData.walletId)!==String(e.walletId))throw Error(`[login] NEAR account projection belongs to a different wallet`);let t=typeof e.userData?.operationalPublicKey==`string`?e.userData.operationalPublicKey.trim():``;return{kind:`near_wallet`,walletId:e.walletId,operationalPublicKey:t||null}}async function Ox(e){js(e.onEvent,String(e.identity.nearAccountId),{phase:G.STEP_02_ACCOUNT_LOOKUP_STARTED,status:`running`,authMethod:`passkey`});let t=e.signerSlotHint===null?Promise.resolve(null):e.signingEngine.getUserBySignerSlot(e.identity.nearAccountId,e.signerSlotHint).catch(()=>null),[n,r,i,a]=await Promise.all([t,e.signingEngine.getLastUser().catch(()=>null),Ac(K,e.identity.nearAccountId).catch(()=>null),tx(e.identity.walletId)]);if(a.length===0)throw Error(`No authenticators found for account ${e.identity.nearAccountId}. Please register an account.`);let o=null;o=n&&n.nearAccountId===e.identity.nearAccountId?n:i&&i.nearAccountId===e.identity.nearAccountId?i:r&&r.nearAccountId===e.identity.nearAccountId?r:await e.signingEngine.getUserBySignerSlot(e.identity.nearAccountId,Number(e.identity.signerSlot)).catch(()=>null);let s=Dx({userData:o,walletId:e.identity.walletId});return js(e.onEvent,String(e.identity.nearAccountId),{phase:G.STEP_02_ACCOUNT_LOOKUP_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,data:{signerSlot:Number(e.identity.signerSlot),...s.operationalPublicKey?{operationalPublicKey:s.operationalPublicKey}:{walletKind:s.kind}}}),{kind:`login_unlock_account_phase_ready`,accountSubject:s,authenticators:a,baseSignerSlot:e.signerSlotHint??Number(e.identity.signerSlot),localUnlockAuthMethod:z.passkey,requiresLocalPasskeyUnlock:!0}}async function kx(e){let t=String(e.identity.walletId);js(e.onEvent,t,{phase:G.STEP_02_ACCOUNT_LOOKUP_STARTED,status:`running`,authMethod:`passkey`});let[n,r]=await Promise.all([K.getProfile(t),tx(e.identity.walletId)]);if(!n||r.length===0)throw Error(`[login] ECDSA wallet ${t} has no local passkey profile`);let i=Ai(n.defaultSignerSlot,{min:1}),a=e.signerSlotHint??i;if(a===null)throw Error(`[login] ECDSA wallet profile is missing its exact signerSlot`);return js(e.onEvent,t,{phase:G.STEP_02_ACCOUNT_LOOKUP_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,data:{signerSlot:a,walletKind:`ecdsa_wallet_only`}}),{kind:`login_unlock_account_phase_ready`,accountSubject:{kind:`ecdsa_wallet_only`,walletId:e.identity.walletId,operationalPublicKey:null},authenticators:r,baseSignerSlot:a,localUnlockAuthMethod:z.passkey,requiresLocalPasskeyUnlock:!0}}async function Ax(e){switch(e.identity.kind){case`near_ed25519_capable_wallet`:return await Ox({signingEngine:e.signingEngine,identity:e.identity,signerSlotHint:e.signerSlotHint,onEvent:e.onEvent});case`evm_family_ecdsa_only_wallet`:return await kx({identity:e.identity,signerSlotHint:e.signerSlotHint,onEvent:e.onEvent})}return Q(e.identity)}function jx(e){switch(e.identity.kind){case`near_ed25519_capable_wallet`:if(e.accountSubject.kind!==`near_wallet`)throw Error(`[login] NEAR unlock returned an ECDSA-only account subject`);return{success:!0,kind:`near_wallet_unlocked`,walletId:e.identity.walletId,loggedInNearAccountId:String(e.identity.nearAccountId),operationalPublicKey:e.accountSubject.operationalPublicKey,nearAccountId:e.identity.nearAccountId};case`evm_family_ecdsa_only_wallet`:if(e.accountSubject.kind!==`ecdsa_wallet_only`)throw Error(`[login] ECDSA-only unlock returned a NEAR account subject`);return{success:!0,kind:`ecdsa_wallet_unlocked`,walletId:e.identity.walletId}}return Q(e.identity)}async function Mx(e,t,n){return await aS(e,t,n,{kind:`wallet_only`})}async function Nx(e){let t=e.authority.signerActivations.ed25519;if(!t)return{kind:`absent`};let n=Lb(e.signerMaterials,e.authority.authorityId,e.authMethod.walletAuthMethodId,t.materialActivation);if(!n||n.kind!==`wallet_authority_linked_signer_material_v1`||n.keyFamily!==`ed25519`||!g(n.materialActivation,t.materialActivation))return{kind:`invalid`};let r=n.publicFacts.applicationBinding;if(r.wallet_id!==String(e.walletId))return{kind:`invalid`};let i=null,a=await new ia(K).listLanes();for(let o of a){let a;switch(e.authMethod.kind){case z.passkey:a=o.auth.kind===z.passkey&&String(o.auth.rpId)===String(e.authMethod.rpId)&&String(o.auth.credentialIdB64u)===String(e.authMethod.credentialIdB64u);break;case z.emailOtp:a=o.auth.kind===z.emailOtp;break;case`voiceid`:return{kind:`invalid`};default:return Q(e.authMethod)}if(!(!a||String(o.walletId)!==String(e.walletId)||o.signerSlot!==r.key_creation_signer_slot||String(o.nearEd25519SigningKeyId)!==r.near_ed25519_signing_key_id||String(o.thresholdSessionId)!==n.publicFacts.targetBinding.lifecycle.session_id||!g(o.materialActivation,t.materialActivation))){if(i)return{kind:`invalid`};i=o}}if(!i)return{kind:`invalid`};let o=Ai(i.signerSlot,{min:1});return o?{kind:`resolved`,subject:{kind:`near_ed25519_wallet`,walletId:e.walletId,nearAccountId:i.nearAccountId,nearEd25519SigningKeyId:i.nearEd25519SigningKeyId,signerSlot:o}}:{kind:`invalid`}}function Px(e){let t=gi({kind:`wallet_auth_authority_ref`,walletId:e.authority.walletId,authorityDigest:e.authority.authorityDigestB64u,walletAuthMethodId:e.authMethod.walletAuthMethodId});if(!t)throw Error(`[login] linked device wallet authority reference is invalid`);return t}async function Fx(e){let t=_(e);if(!t.ok)return null;let n=t.value;try{let e=await K.resolveSelectedWalletAuthority(String(n));if(e.kind!==`resolved`)return null;let{selection:t,authMethod:r,authority:i}=e;if(Rb({walletId:n,selection:t,authMethod:r,authority:i}).length>0||r.status!==`active`||i.state!==`active`)return null;let a=[],o=await Nx({walletId:n,authMethod:r,authority:i,signerMaterials:e.signerMaterials});if(o.kind===`invalid`)return null;o.kind===`resolved`&&a.push(o.subject);let s=i.signerActivations.ecdsa;if(s){let t=Lb(e.signerMaterials,i.authorityId,r.walletAuthMethodId,s.materialActivation);if(!t||t.keyFamily!==`ecdsa_secp256k1`||!g(t.materialActivation,s.materialActivation))return null;let o;try{o=r.kind===z.passkey?await Nb(r):Px({authority:i,authMethod:r})}catch{return null}a.push({kind:`evm_family_ecdsa_wallet`,walletId:n,capability:s.materialActivation.capability,authority:o,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId})}let c=a[0];return c?{kind:`wallet_unlock_subject_set`,walletId:n,subjects:[c,...a.slice(1)]}:null}catch{return null}}async function Ix(e){let t=await yb(c(e.relayUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:String(e.walletId),rpId:e.rpId})}),n=await t.json().catch(()=>({})),r=A(n)?n:{};if(!t.ok||r.ok!==!0)throw Error(typeof r.message==`string`?r.message:`wallet/unlock/challenge failed (HTTP ${t.status})`);let i=String(r.challengeId||``).trim(),a=String(r.challengeB64u||``).trim();if(!i||!a)throw Error(`[login] linked passkey challenge is incomplete`);return{challengeId:i,challengeB64u:a}}function Lx(e){return{id:e,type:`public-key`,transports:[]}}function Rx(e,t){return e.capabilitySubjects.some(e=>(e.kind===`sign`||e.kind===`export_keys`)&&e.keyFamily===(t===`ed25519`?`ed25519`:`ecdsa_secp256k1`))}function zx(e){let t=e.filter(e=>e.keyFamily===`ed25519`);if(t.length>1)throw Error(`[login] linked passkey has multiple active Ed25519 materials`);return t[0]??null}function Bx(e){let t=e.filter(e=>e.keyFamily===`ecdsa_secp256k1`);if(t.length>1)throw Error(`[login] linked passkey has multiple active ECDSA materials`);return t[0]??null}async function Vx(e){let t=Ld({walletId:e.selection.walletId,materialActivation:e.material.materialActivation});if(t){let[n,r]=await Promise.all([U({authority:t.factorAuthority}),U({authority:e.factorAuthority})]);if(t.authorityId!==e.selection.authority.authorityId||t.walletAuthMethodId!==e.selection.authMethod.walletAuthMethodId||t.ecdsaThresholdKeyId!==e.material.publicFacts.ecdsaThresholdKeyId||n.authorityDigest!==r.authorityDigest)throw Error(`[login] linked ECDSA holder runtime conflicts with the selected authority`);return{runtime:t,installed:!1}}let n=ve(`linked-ecdsa-holder`);try{let t=await Wu({holderHandleId:n,ownedSigningShare32:e.material.material.slice(),activationReceiptJson:JSON.stringify(e.material.publicFacts.activationReceipt),workerCtx:e.context.signingEngine.getSignerWorkerContext()}),r={kind:`linked_ecdsa_holder_runtime_v1`,walletId:e.selection.walletId,authorityId:e.selection.authority.authorityId,walletAuthMethodId:e.selection.authMethod.walletAuthMethodId,factorAuthority:e.factorAuthority,materialActivation:e.material.materialActivation,holderHandleId:t.holderHandleId,ecdsaThresholdKeyId:e.material.publicFacts.ecdsaThresholdKeyId,activationReceipt:e.material.publicFacts.activationReceipt};return zd(r),{runtime:r,installed:!0}}catch(t){throw await nd({holderHandleId:n,workerCtx:e.context.signingEngine.getSignerWorkerContext()}).catch(()=>void 0),t}}async function Hx(e){if(e.kind===`passkey`){let t=await zb(String(e.walletId));if(!t)throw Error(`[login] linked Passkey authority is unavailable after link`);return t}let t=await Bb({walletIdInput:String(e.walletId),walletAuthMethodId:String(e.walletAuthMethodId),emailHashHex:e.emailHashHex,provider:e.providerIdentity.provider,providerSubjectId:e.providerIdentity.providerSubjectId});if(t.kind!==`selected`)throw Error(t.kind===`rejected`?t.message:`[login] linked Email OTP authority is unavailable after link`);return t.selection}async function Ux(e){let t=Gx(e.material),r=rn(`ed25519:${tn(t.registeredPublicKey)}`),i=Lr({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:String(e.selection.walletId),nearAccountId:r,nearEd25519SigningKeyId:t.applicationBinding.near_ed25519_signing_key_id,signerSlot:t.applicationBinding.key_creation_signer_slot,thresholdSessionId:t.scope.threshold_session_id,signingWorkerId:t.scope.signing_worker_id,participantIds:t.participantIds});if(!i.ok)throw Error(i.message);let a=await fetch(`${new URL(e.relayerUrl).origin}${Mr}`,{method:`POST`,headers:{Authorization:`Bearer ${e.operationCredential.token}`,"Content-Type":`application/json`},body:JSON.stringify(i.value)}),o=await a.json().catch(()=>null);if(!a.ok||!A(o)){let e=A(o)?String(o.message||``).trim():``;throw Error(`[login] linked Ed25519 post-link bootstrap failed (HTTP ${a.status}): ${e||`invalid response`}`)}let s=n(o.thresholdSessionId),c=Tt(o.walletSessionId),l=Ct(o.quotaId),u=Fe(o.runtimePolicyScope),d=Qe(o.routerAbNormalSigning),f=Array.isArray(o.participantIds)?o.participantIds:[];if(o.kind!==`router_ab_ed25519_yao_warm_recovery_bootstrap_v1`&&o.kind!==`router_ab_ed25519_yao_v2_session_bootstrap_v1`||String(o.walletId)!==String(e.selection.walletId)||String(o.nearAccountId)!==i.value.nearAccountId||String(o.nearEd25519SigningKeyId)!==i.value.nearEd25519SigningKeyId||String(o.signingWorkerId)!==i.value.signingWorkerId||!s.ok||!c.ok||!l.ok||!u||!d||f.length!==2||!Number.isSafeInteger(f[0])||!Number.isSafeInteger(f[1])||String(c.value)!==String(e.operationCredential.walletSessionId)||String(s.value)!==i.value.thresholdSessionId)throw Error(`[login] linked Ed25519 post-link bootstrap identity is invalid`);let p=Number(o.thresholdExpiresAtMs);if(!Number.isSafeInteger(p)||p<=Date.now())throw Error(`[login] linked Ed25519 post-link bootstrap is expired`);return{walletId:String(e.selection.walletId),nearAccountId:i.value.nearAccountId,nearEd25519SigningKeyId:i.value.nearEd25519SigningKeyId,relayerKeyId:i.value.signingWorkerId,participantIds:[f[0],f[1]],thresholdSessionId:s.value,authorizationId:e.walletSession.authorizationId,walletSessionId:c.value,quotaId:l.value,expiresAtMs:p,remainingUses:xe,runtimePolicyScope:u,routerAbNormalSigning:d,operationCredential:e.operationCredential}}async function Wx(e){let t=await Hx(e.factor);Hb(t,e.walletSession);let n=String(e.context.configs.network.relayer?.url||``).trim();if(!n)throw Error(`[login] linked post-link activation requires relayer.url`);await q.writeExactWithOperationCredential({record:e.walletSession,operationCredential:e.operationCredential});let r=await Gb({selection:t,factorSecret32:e.factorSecret32});try{let i=e.factor.kind===`email_otp`?e.factor.providerIdentity:void 0,a=await Fb({selection:t,...i?{providerIdentity:i}:{}}),o=Bx(r);if(o){let{runtime:r}=await Vx({context:e.context,selection:t,factorAuthority:a,material:o});Vp({runtime:r,operationCredential:e.operationCredential,expiresAtMs:e.walletSession.expiresAtMs,relayerUrl:n,workerCtx:e.context.signingEngine.getSignerWorkerContext()})}let s=zx(r);if(s){let r=await Ux({relayerUrl:n,selection:t,walletSession:e.walletSession,operationCredential:e.operationCredential,material:s});await Xx({context:e.context,selection:t,session:r,material:s,relayerUrl:n,...i?{providerIdentity:i}:{}})}t.exportRoot&&(e.factor.kind===`passkey`?await e.context.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:t.exportRoot.envelope,passkeyPrfFirstB64u:P(e.factorSecret32),walletId:String(t.walletId),walletAuthMethodId:String(t.authMethod.walletAuthMethodId),walletSessionId:String(e.operationCredential.walletSessionId),expiresAtMs:e.walletSession.expiresAtMs}):(ln(t.exportRoot.envelope.binding)||t.exportRoot.envelope.binding.kind===`ed25519_yao_client_root_v1`)&&await no(ro(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:t.exportRoot.envelope,existingFactorSecret:e.factorSecret32,walletId:String(t.walletId),walletAuthMethodId:String(t.authMethod.walletAuthMethodId),walletSessionId:String(e.operationCredential.walletSessionId),expiresAtMs:e.walletSession.expiresAtMs})),await e.context.signingEngine.markWalletSelectionUnlocked({walletId:t.walletId,walletAuthMethodId:t.authMethod.walletAuthMethodId})}finally{for(let e of r)e.material.fill(0)}}function Gx(e){let t=e.publicFacts.targetBinding,n=e.publicFacts.activationReceipt;return{kind:Ts,scope:{lifecycle_id:t.lifecycle.lifecycle_id,root_share_epoch:t.lifecycle.root_share_epoch,account_id:t.lifecycle.account_id,threshold_session_id:t.lifecycle.session_id,signer_set_id:t.lifecycle.signer_set_id,signing_worker_id:t.lifecycle.selected_server_id,material_activation:t.material_activation},applicationBinding:e.publicFacts.applicationBinding,participantIds:e.publicFacts.participantIds,registeredPublicKey:Uint8Array.from(n.registered_public_key),signingWorkerVerifyingShare:Uint8Array.from(n.signing_worker_verifying_share),stateEpoch:BigInt(n.state_epoch),transcript:Uint8Array.from(n.transcript),activeCapabilityBinding:t.session_id,materialActivation:e.materialActivation}}function Kx(e){let t=String(e?.providerSubjectId||``).trim();if(!t)throw Error(`[login] linked Email OTP lane provider identity is missing`);return t}function qx(e){let t=e.session;if(t.walletSessionId!==e.operationCredential.walletSessionId||t.sessionKind===`issued_exact_wallet_session`&&t.operationCredential.walletSessionId!==e.operationCredential.walletSessionId)throw Error(`[login] linked Passkey Ed25519 credentials identify different sessions`);return{walletId:t.walletId,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,relayerKeyId:t.relayerKeyId,participantIds:t.participantIds,thresholdSessionId:t.thresholdSessionId,authorizationId:t.authorizationId,walletSessionId:t.walletSessionId,quotaId:t.quotaId,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses,runtimePolicyScope:t.runtimePolicyScope,routerAbNormalSigning:t.routerAbNormalSigning,operationCredential:e.operationCredential}}function Jx(e){let t=e.session;if(t.authorityScope.kind!==`email_otp`||String(t.authorityScope.providerUserId)!==String(e.providerIdentity.providerSubjectId)){let n=[...t.authorityScope.kind===`email_otp`?[]:[`scope.kind`],...t.authorityScope.kind===`email_otp`&&String(t.authorityScope.providerUserId)!==String(e.providerIdentity.providerSubjectId)?[`scope.providerUserId`]:[]];throw Error(`[login] linked Email OTP Ed25519 session authority mismatch: ${n.join(`, `)}`)}let r=n(t.thresholdSessionId),i=Ot(t.authorizationId),a=Tt(t.walletSessionId),o=Ct(t.quotaId);if(!r.ok||!i.ok||!a.ok||!o.ok)throw Error(`[login] linked Email OTP Ed25519 session identity is invalid`);if(e.operationCredential.walletSessionId!==a.value)throw Error(`[login] linked Email OTP Ed25519 credential identifies another session`);return{walletId:String(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,relayerKeyId:t.routerAbNormalSigning.signingWorkerId,participantIds:t.participantIds,thresholdSessionId:r.value,authorizationId:i.value,walletSessionId:a.value,quotaId:o.value,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses,runtimePolicyScope:t.runtimePolicyScope,routerAbNormalSigning:t.routerAbNormalSigning,operationCredential:e.operationCredential}}function Yx(e){let t=B(e.session.nearAccountId),n={walletId:e.selection.walletId,nearAccountId:t,thresholdSessionId:e.session.thresholdSessionId,runtimePolicyScope:e.session.runtimePolicyScope,materialActivation:e.material.materialActivation,nearEd25519SigningKeyId:Oi(e.session.nearEd25519SigningKeyId),signerSlot:e.material.publicFacts.applicationBinding.key_creation_signer_slot};return e.selection.authMethod.kind===`passkey`?{...n,auth:{kind:`passkey`,rpId:wa(e.selection.authMethod.rpId),credentialIdB64u:e.selection.authMethod.credentialIdB64u}}:{...n,auth:{kind:`email_otp`,providerSubjectId:Kx(e.providerIdentity)},remainingUses:e.session.remainingUses,expiresAtMs:e.session.expiresAtMs}}async function Xx(e){let t=Gx(e.material),n=t.applicationBinding,r=[];if(e.session.walletId!==String(e.selection.walletId)&&r.push(`walletId`),n.wallet_id!==String(e.selection.walletId)&&r.push(`application.walletId`),t.scope.account_id!==String(e.selection.walletId)&&r.push(`material.walletId`),e.session.nearEd25519SigningKeyId!==n.near_ed25519_signing_key_id&&r.push(`nearEd25519SigningKeyId`),e.session.thresholdSessionId!==t.scope.threshold_session_id&&r.push(`thresholdSessionId`),e.session.relayerKeyId!==t.scope.signing_worker_id&&r.push(`signingWorkerId`),r.length>0)throw Error(`[login] linked Ed25519 Wallet Session does not match local material: ${r.join(`, `)}`);let i=(await Cs.initializeBundled()).importLinkedMaterial({ownedClientScalarShare:e.material.material,publicReceipt:e.material.publicFacts.activationReceipt,metadata:t}),a=!1;try{let r=await e.context.signingEngine.activateVerifiedNearEd25519YaoMaterial({activeClient:i,facts:{thresholdSessionId:e.session.thresholdSessionId,signer:fl({walletId:e.selection.walletId,nearAccountId:B(e.session.nearAccountId),nearEd25519SigningKeyId:Oi(e.session.nearEd25519SigningKeyId),signerSlot:n.key_creation_signer_slot}),signingRootId:n.signing_root_id,signingRootVersion:t.scope.root_share_epoch,routerAbNormalSigning:e.session.routerAbNormalSigning,runtimePolicyScope:e.session.runtimePolicyScope,relayerUrl:e.relayerUrl}}),o=B(e.session.nearAccountId);if(String(r.walletId)!==String(e.selection.walletId)||String(r.nearAccountId)!==String(o)||!g(r.materialActivation,e.material.materialActivation))throw Error(`[login] linked Ed25519 activation identity does not match the V2 session`);await sa(new ia(K),Yx({selection:e.selection,session:e.session,material:e.material,...e.providerIdentity?{providerIdentity:e.providerIdentity}:{}})),a=!0}finally{a||i.dispose()}let o=B(e.session.nearAccountId);return{success:!0,kind:`near_wallet_unlocked`,walletId:e.selection.walletId,loggedInNearAccountId:String(o),operationalPublicKey:`ed25519:${tn(t.registeredPublicKey)}`,nearAccountId:o}}function Zx(e){let[t,...n]=e.signerMaterials;if(e.authority.provenance.kind===`device_link`){if(!t)throw Error(`[login] linked Email OTP authority has no signer material`);return{kind:`linked_device`,selection:e,signerMaterials:[t,...n]}}if(t)throw Error(`[login] owner Email OTP authority must not carry linked signer material`);return{kind:`owner_authority`,selection:e}}async function Qx(e){let{source:t}=e;if(t.kind===`linked_device`){let e=t.signerMaterials.find(e=>e.kind===`wallet_authority_linked_signer_material_v1`&&e.keyFamily===`ed25519`);return e?{kind:`linked_device`,signerSlot:e.publicFacts.applicationBinding.key_creation_signer_slot,remainingUses:xe}:{kind:`no_ed25519`}}return!t.selection.authority.signerActivations.ed25519||await $x(t.selection)?{kind:`no_ed25519`}:await e.context.signingEngine.resolveOwnerAuthorityEd25519UnlockRequestInternal({walletSession:{walletId:t.selection.walletId,walletSessionUserId:String(t.selection.walletId)},providerSubjectId:e.providerIdentity.providerSubjectId,walletAuthMethodId:String(t.selection.authMethod.walletAuthMethodId),remainingUses:xe})??{kind:`no_ed25519`}}async function $x(e){let t=e.authority.signerActivations.ed25519?.materialActivation;return t?(await K.listPendingWalletRegistrationCommits()).some(eS.bind(void 0,e,t)):!1}function eS(e,t,n){return n.operation===`near_provisioning`&&n.phase===`joined`&&n.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&n.walletId===e.walletId&&n.walletAuthMethodId===e.authMethod.walletAuthMethodId&&g(n.localMaterial.ed25519.metadata.materialActivation,t)}async function tS(e){let{selection:t,unlocked:n}=e,r=n.walletSession;if(r.walletId!==t.walletId||r.authorityId!==t.authority.authorityId||r.authMethodId!==t.authMethod.walletAuthMethodId||r.authorityDigestB64u!==t.authority.authorityDigestB64u||r.authorityRevocationEpoch!==t.authority.revocationEpoch)throw Error(`[login] owner Email OTP Wallet Session does not match the selected authority`);let i=t.authority.signerActivations.ed25519?.materialActivation;if(!i)return;if(n.ed25519Activation.kind!==`ed25519_activation_ready`){if(await $x(t))return;throw Error(`[login] owner Email OTP unlock built no Ed25519 runtime to install`)}let a=n.ed25519Activation;if(!g(a.bootstrap.capability.materialActivation,i))throw Error(`[login] owner Email OTP Ed25519 capability names another activation`);if(!g(a.metadata.materialActivation,i))throw Error(`[login] owner Email OTP Ed25519 runtime names another activation`);if(a.bootstrap.session.walletSessionId!==n.operationCredential.walletSessionId)throw Error(`[login] owner Email OTP Ed25519 session credential mismatch`);let o=await Ib({selection:t,providerIdentity:e.providerIdentity});await e.context.signingEngine.activateOwnerAuthorityEd25519RuntimeInternal({walletSession:{walletId:t.walletId,walletSessionUserId:String(t.walletId)},providerSubjectId:e.providerIdentity.providerSubjectId,walletAuthMethodId:String(t.authMethod.walletAuthMethodId),emailHashHex:e.emailHashHex,authority:o,activeClientHandle:a.activeClientHandle,metadata:a.metadata,bootstrap:a.bootstrap})}function nS(e){switch(e.walletCustodySeed.kind){case`owner_authority_seed_envelope`:return e.walletCustodySeed.existingEnvelope;case`linked_device_seed_unavailable`:throw Error(`[login] owner Email OTP unlock returned linked-device custody state`);default:return Q(e.walletCustodySeed)}}async function rS(e){let t={provider:e.providerSubjectId.startsWith(`google:`)?`google`:`email`,providerSubjectId:e.providerSubjectId},n=await Bb({walletIdInput:e.walletIdInput,emailHashHex:e.emailHashHex,provider:t.provider,providerSubjectId:t.providerSubjectId,walletAuthMethodId:e.walletAuthMethodId});if(n.kind===`none`)throw Error(`[login] linked Email OTP authority is unavailable`);if(n.kind===`rejected`)throw Error(n.message);let r=n.selection;if(String(r.authMethod.walletAuthMethodId)!==String(e.walletAuthMethodId))throw Error(`[login] linked Email OTP selected auth method changed during unlock`);let i=String(e.relayUrl||``).trim();if(!i)throw Error(`[login] linked Email OTP unlock requires relayer.url`);let a=Zx(r),o=await Qx({context:e.context,source:a,providerIdentity:t}),s=await vs({relayUrl:i,walletId:String(r.walletId),walletAuthMethodId:String(r.authMethod.walletAuthMethodId),challengeId:e.challengeId,otpCode:e.otpCode,ed25519:o,workerCtx:e.context.signingEngine.getSignerWorkerContext()}),c=s.factorSecret32,l=t,u=null,d=null,f=s.ed25519Activation.kind===`ed25519_activation_ready`?s.ed25519Activation.activeClientHandle:null;try{if(a.kind===`owner_authority`){if(await q.writeExactWithOperationCredential({record:s.walletSession,operationCredential:s.operationCredential}),await tS({context:e.context,selection:r,unlocked:s,providerIdentity:l,emailHashHex:e.emailHashHex}),f=null,!c)throw Error(`[login] owner Email OTP factor secret ownership was lost`);await no(ro(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:nS(s),existingFactorSecret:c,walletId:String(r.walletId),walletAuthMethodId:String(r.authMethod.walletAuthMethodId),walletSessionId:String(s.operationCredential.walletSessionId),expiresAtMs:s.walletSession.expiresAtMs}),await e.context.signingEngine.markWalletSelectionUnlocked({walletId:r.walletId,walletAuthMethodId:r.authMethod.walletAuthMethodId}),e.context.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:r.walletId,authMethod:z.emailOtp}),JC({context:e.context,sessionAuthority:{record:s.walletSession,operationCredential:s.operationCredential},factor:{kind:`email_otp`,provider:t.provider,providerSubject:t.providerSubjectId,emailHashHex:e.emailHashHex},ownedFactorSecret:c.slice().buffer,custodyEnvelope:nS(s)});return}if(Hb(r,s.walletSession),!c)throw Error(`[login] linked Email OTP factor secret ownership was lost`);u=await qb({selection:r,factorSecret32:c});let n=zx(u),o=Bx(u);if(Rx(s.walletSession,`ed25519`)){if(!n||!s.ed25519Activation.bootstrap)throw Error(`[login] linked Email OTP Ed25519 runtime material or capability is missing`);if(!g(s.ed25519Activation.bootstrap.capability.materialActivation,n.materialActivation))throw Error(`[login] linked Email OTP Ed25519 capability activation is invalid`)}if(Rx(s.walletSession,`ecdsa`)){if(!o)throw Error(`[login] linked Email OTP ECDSA runtime material is missing`);let t=await Vx({context:e.context,selection:r,factorAuthority:await Fb({selection:r,providerIdentity:l}),material:o});t.installed&&(d=t.runtime)}let p;if(n&&s.ed25519Activation.bootstrap){let t=Jx({session:s.ed25519Activation.bootstrap.session,operationCredential:s.operationCredential,providerIdentity:l});if(t.walletSessionId!==s.operationCredential.walletSessionId)throw Error(`[login] linked Email OTP Ed25519 session credential mismatch`);p=await Xx({context:e.context,selection:r,session:t,material:n,relayerUrl:i,providerIdentity:l})}else if(o)p={success:!0,kind:`ecdsa_wallet_unlocked`,walletId:r.walletId};else throw Error(`[login] linked Email OTP has no unlockable signing runtime`);await q.writeExactWithOperationCredential({record:s.walletSession,operationCredential:s.operationCredential}),r.exportRoot&&ln(r.exportRoot.envelope.binding)&&await no(ro(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:r.exportRoot.envelope,existingFactorSecret:c,walletId:String(r.walletId),walletAuthMethodId:String(r.authMethod.walletAuthMethodId),walletSessionId:String(s.operationCredential.walletSessionId),expiresAtMs:s.walletSession.expiresAtMs}),await e.context.signingEngine.markWalletSelectionUnlocked({walletId:r.walletId,walletAuthMethodId:r.authMethod.walletAuthMethodId}),e.context.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:p.walletId,authMethod:z.emailOtp})}catch(t){d&&(Id({walletId:d.walletId,materialActivation:d.materialActivation,holderHandleId:d.holderHandleId}),await nd({holderHandleId:d.holderHandleId,workerCtx:e.context.signingEngine.getSignerWorkerContext()}).catch(()=>void 0));let n=e.context.signingEngine.getSignerWorkerContext();throw n&&await io(ro(n),{kind:`wallet_session`,walletSessionId:String(s.operationCredential.walletSessionId)}),await Promise.allSettled([e.context.signingEngine.clearVolatileWarmSigningMaterial(r.walletId),q.clearWallet(r.walletId)]),t}finally{if(f){let t=e.context.signingEngine.getSignerWorkerContext();t&&await Fy({workerContext:t,activeClientHandle:f}).catch(()=>void 0),f=null}for(let e of u||[])e.material.fill(0);c?.fill(0)}}async function iS(e,t,n){let r=String(t).trim()||`linked-passkey`,{onEvent:i,onError:a,afterCall:o}=n||{};js(i,r,{phase:G.STEP_01_STARTED,status:`started`,authMethod:`passkey`});try{let n=await zb(t);if(!n)throw Error(`[login] linked passkey authority is unavailable`);let a=String(e.configs.network.relayer?.url||``).trim();if(!a)throw Error(`[login] linked passkey unlock requires relayer.url`);js(i,r,{phase:G.STEP_03_PASSKEY_CHALLENGE_STARTED,status:`running`,authMethod:`passkey`});let s=await Ix({relayUrl:a,walletId:n.walletId,rpId:n.authMethod.rpId});js(i,r,{phase:G.STEP_03_PASSKEY_PROMPT_STARTED,status:`running`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`}});let c=await e.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(n.walletId),challengeB64u:s.challengeB64u,allowCredentials:[Lx(n.authMethod.credentialIdB64u)],includeSecondPrfOutput:!0});js(i,r,{phase:G.STEP_03_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let l=String(typeof window<`u`?window.location.origin:``).trim(),u={challengeId:s.challengeId,webauthn_authentication:c,ed25519SessionRequest:n.signerMaterials.some(e=>e.keyFamily===`ed25519`)?{kind:`requested`,remainingUses:xe}:{kind:`not_requested`},...l?{expected_origin:l}:{}};js(i,r,{phase:G.STEP_04_WALLET_UNLOCK_EXCHANGE_STARTED,status:`running`,authMethod:`passkey`});let d=await Vo(a,u);if(!d.success)throw Error(d.error);Hb(n,d.walletSession);let f=await Wb({selection:n,credential:c}),p;try{let t=zx(f),r=Bx(f);if(Rx(d.walletSession,`ed25519`)&&(!t||!d.ed25519Session))throw Error(`[login] linked Ed25519 runtime material or Wallet Session is missing`);if(Rx(d.walletSession,`ecdsa`)){if(!r)throw Error(`[login] linked ECDSA runtime material is missing`);await Vx({context:e,selection:n,factorAuthority:await Fb({selection:n}),material:r})}if(t&&d.ed25519Session)p=await Xx({context:e,selection:n,session:qx({session:d.ed25519Session,operationCredential:d.operationCredential}),material:t,relayerUrl:a});else if(r)p={success:!0,kind:`ecdsa_wallet_unlocked`,walletId:n.walletId};else throw Error(`[login] linked passkey has no unlockable signing runtime`);if(await q.writeExactWithOperationCredential({record:d.walletSession,operationCredential:d.operationCredential}),n.exportRoot){let t=wl(c);if(!t)throw Error(`[login] linked export-root unlock requires WebAuthn PRF.first output`);await e.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:n.exportRoot.envelope,passkeyPrfFirstB64u:t,walletId:String(n.walletId),walletAuthMethodId:String(n.authMethod.walletAuthMethodId),walletSessionId:String(d.operationCredential.walletSessionId),expiresAtMs:d.walletSession.expiresAtMs})}await e.signingEngine.markWalletSelectionUnlocked({walletId:n.walletId,walletAuthMethodId:n.authMethod.walletAuthMethodId})}catch(t){throw await Promise.allSettled([e.signingEngine.clearVolatileWarmSigningMaterial(n.walletId),q.clearWallet(n.walletId)]),t}finally{for(let e of f)e.material.fill(0)}return js(i,r,{phase:G.STEP_04_WALLET_UNLOCK_EXCHANGE_SUCCEEDED,status:`succeeded`,authMethod:`passkey`}),await oc({context:e,authMethod:z.passkey,unlockSubjectId:r,loginResult:p,onEvent:i,afterCall:o})}catch(e){let t=I(e);return await ec({unlockSubjectId:r,message:t.message,error:t,onEvent:i,onError:a,afterCall:o,cancelled:Ft(t)})}}async function aS(e,t,n,r){let{onEvent:i,onError:a,afterCall:o}=n||{},{signingEngine:s}=e,c=xb({selection:n?.unlockSelection,subjectSet:t}),l=Tb({subjectSet:t,selection:c}),u=l.kind===`near_ed25519_capable_wallet`?String(l.nearAccountId):String(l.walletId),d;js(i,u,{phase:G.STEP_01_STARTED,status:`started`,authMethod:`passkey`});try{if(s.assertSealedRefreshStartupParity().catch(e=>{console.warn(`[login] sealed refresh startup parity check failed during unlock; continuing to local passkey prompt`,e instanceof Error?e.message:String(e||`unknown error`))}),typeof window<`u`&&!window.isSecureContext){let e=`Passkey operations require a secure context (HTTPS or localhost).`;return await ec({unlockSubjectId:u,message:e,error:Error(e),onEvent:i,onError:a,afterCall:o,callAfterCall:!1})}let{accountSubject:t,authenticators:r,baseSignerSlot:f,localUnlockAuthMethod:p,requiresLocalPasskeyUnlock:m}=await Ax({signingEngine:s,identity:l,signerSlotHint:Ai(n?.signerSlot,{min:1}),onEvent:i}),h=async e=>{let t=yx({authenticators:r,credentialIds:e.credentialIds}),n=await Jy({signingEngine:s,subjectId:u,challengeB64u:e.challengeB64u,authenticators:t,onPromptStarted:()=>{js(i,u,{phase:G.STEP_03_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`}})},onPromptSucceeded:()=>{js(i,u,{phase:G.STEP_03_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`}})}});return e.saveAsLoginCredential&&(d=n),n},g=async()=>{let e=await Xy({currentCredential:d,collectCredentialForChallenge:async e=>await h({challengeB64u:e,saveAsLoginCredential:!0,credentialIds:Sx({authenticators:r,signerSlot:f,serverCredentialIds:[]})})});e&&(d=e)},_=Bp({defaults:e.configs.signing.sessionDefaults,override:n?.signingSession}),v=_.kind===`enabled`,y=v&&l.kind===`near_ed25519_capable_wallet`?Kg({clientDB:K,keyMaterialStore:K},l.nearAccountId,f).catch(()=>null):Promise.resolve(null),b=null,x=null,S=null,C=null,w=ax(),T=null,E=(e,t)=>{if(nx(t))return t;let n=String(t?.status||`not_found`);throw Error(`[login] ${e} did not produce an active warm signing session (status=${n})`)},D=async t=>{js(i,u,{phase:G.STEP_05_SIGNING_SESSION_WARMUP_STARTED,status:`running`,authMethod:d?`passkey`:`warm_session`});let a=t.wantsEd25519Warmup?Eb(l):null,o=hc(e.configs),c=!1,h=async()=>{c||(c=!0,await s.clearVolatileWarmSigningMaterial(l.walletId))};t.wantsEcdsaWarmup&&Ab(await kb({workerCtx:s.getSignerWorkerContext(),selectors:Ob(l.subjectSet)}));let g=t.wantsEcdsaWarmup?await yC(e,l.walletId,{keyFactsInventoryAuthority:t.keyFactsInventoryAuthority,keyFactsInventoryRequested:!!n?.ecdsaKeyFactsInventory,relayerUrl:t.relayerUrl,rpId:t.rpId},p):{ecdsaKeys:[]},v=await y,w=v?.participants.map(e=>e.id)||[];t.wantsEcdsaWarmup&&Db({identity:l,context:g});let T=rC({selection:t.selection,selectedEcdsaTargets:t.selectedEcdsaTargets,storedCanonicalEcdsaContext:g,wantsEd25519Warmup:t.wantsEd25519Warmup}),D=b,O=!!(D&&T.signersToWarm.includes(`ecdsa`)),k=O?T.signersToWarm.includes(`ed25519`):T.ed25519DependsOnEcdsa,A=O?!1:T.ecdsaDependsOnEd25519,M=vx({requiresLocalPasskeyUnlock:m,hasLoginCredential:!!d,routeAuthorization:t.routeAuthorization,warmupPlan:T});await h();let ee=iC(`threshold-login`),te=T.signersToWarm.includes(`ed25519`)?k?{kind:`ecdsa_authorized`,thresholdSessionId:ee}:{kind:`fresh`}:{kind:`not_requested`};switch(M.kind){case`existing_passkey_credential`:case`no_passkey_credential_required`:break;case`wallet_custody`:if(t.ed25519SessionAuthority.kind!==`passkey`)throw Error(`[login] wallet custody requires passkey wallet authority`);if(!C||C.ed25519.kind!==`active`)throw lC();te={kind:`wallet_custody`,thresholdSessionId:ee,custody:{...C,ed25519:C.ed25519}};break;default:return Q(M)}if(a&&!v&&te.kind!==`wallet_custody`)throw Error(`[login] threshold warm-up requires threshold key material for ${a.nearAccountId} signer slot ${t.signerSlot}`);let ne=d?Tl(d):``,re=String(ne||r.find(e=>e.signerSlot===f)?.credentialId||r[0]?.credentialId||``).trim(),N=d?{kind:`available`,credential:d,localPasskeyCredentialIdB64u:re}:re?{kind:`credential_id_only`,localPasskeyCredentialIdB64u:re}:{kind:`unavailable`,localPasskeyCredentialIdB64u:``},ie=o?{kind:`available`,runtimeScopeBootstrap:o}:{kind:`unavailable`},ae=await KS({statusReads:j,context:e,signingEngine:s,walletIdentity:l,signerSlot:t.signerSlot,thresholdKeyMaterial:v,relayerUrl:t.relayerUrl,relayerKeyId:v?.relayerKeyId||``,participantIds:w,ttlMs:_.ttlMs,unlockRemainingUses:sC(_.unlockRemainingUses),ecdsaContext:T.ecdsaContext,credentialState:N,runtimeScopeBootstrapState:ie,signersToWarm:T.signersToWarm,ed25519DependsOnEcdsa:k,ecdsaDependency:A?{kind:`ed25519_wallet_session_authority`}:{kind:`none`},ed25519MintPlan:te,ed25519SessionAuthority:t.ed25519SessionAuthority,routeAuthorization:t.routeAuthorization,passkeyExchangeEcdsaActivation:D,passkeyUnlockEd25519Session:x,passkeyUnlockWalletSessionAuthorization:S});if(T.signersToWarm.includes(`ed25519`)){let e=ae.ed25519Session;if(!e)throw Error(`[login] threshold warm-up omitted the Ed25519 session result`);let t=E(`threshold warm-up`,SS({session:e,authMethod:p}));return js(i,u,{phase:G.STEP_05_ED25519_SIGNING_SESSION_READY,status:`succeeded`,authMethod:`warm_session`}),T.signersToWarm.includes(`ecdsa`)&&js(i,u,{phase:G.STEP_05_ECDSA_SIGNING_SESSION_READY,status:`succeeded`,authMethod:`warm_session`}),{kind:`threshold_login_warmup_ready`,signingSession:t,signersWarmed:T.signersToWarm}}if(T.signersToWarm.length!==1||T.signersToWarm[0]!==`ecdsa`)throw Error(`[login] threshold warm-up signer selection is invalid`);return js(i,u,{phase:G.STEP_05_ECDSA_SIGNING_SESSION_READY,status:`succeeded`,authMethod:`warm_session`}),{kind:`threshold_login_ecdsa_only_warmup_ready`,signersWarmed:[`ecdsa`]}},O=async n=>{await s.setLastUser(l.walletId,n),l.kind===`near_ed25519_capable_wallet`&&(t.kind===`near_wallet`&&t.operationalPublicKey===null||await s.activateAuthenticatedWalletState({walletId:l.walletId,nearAccountId:B(l.nearAccountId),signerSlot:n,nearClient:e.nearClient}))},k=async()=>{await s.getNonceCoordinator().recoverDurableLeases({walletId:l.walletId}).catch(e=>{console.warn(`[login] nonce lane durable recovery after unlock failed`,e)})},A=_x({requiresLocalPasskeyUnlock:m,requireThresholdWarmup:v,hasLoginCredential:!!d});switch(A.kind){case`wallet_unlock_owns_passkey_credential`:case`passkey_credential_already_collected`:case`no_local_passkey_required`:break;case`local_unlock_passkey_assertion`:await g();break;default:return Q(A)}let j=new Ja;if(v&&p===z.passkey){let t=await pS({context:e,walletIdentity:l,selection:c,ttlMs:_.ttlMs,remainingUses:sC(_.unlockRemainingUses)}),n=String(e.configs.network.relayer.url||``).trim(),a=String(s.getRpId()||``).trim();if(!n||!a)throw Error(`[login] passkey wallet unlock requires relayer URL and rpId`);let o=await vS({context:e,walletIdentity:l,unlockSubjectId:u,onEvent:i,authenticators:r,signerSlot:f,remainingUses:sC(_.unlockRemainingUses),relayUrl:n,rpId:a,expectedOrigin:void 0,activation:t,collectCredentialForChallenge:async e=>await h({challengeB64u:e.challengeB64u,saveAsLoginCredential:!0,credentialIds:e.credentialIds})},j);d=o.credential,b=o.activation,x=o.result.ed25519Session,S=o.result.walletSessionAuthorization??(o.activation?cS(o.activation.sessionActivation):null),C=o.custody,await fS({walletId:String(l.walletId),unlock:o}),w=ax()}if(!d)throw Error(`[login] successful Passkey unlock omitted its credential`);if(await Ex({context:e,walletIdentity:l,credential:d}),v){let t=await ex({walletId:l.walletId,authMethod:p}),i=lS({completedActivation:b,request:n?.ecdsaKeyFactsInventory,routeAuthorization:w,wantsEcdsaWarmup:Cx({subjectSet:l.subjectSet,selection:c,hasConfiguredEcdsaTargets:jo(e.configs.network.chains).length>0}).wantsEcdsaWarmup});if(T=await D(wx({context:e,signerSlot:f,authenticators:r,selection:c,subjectSet:l.subjectSet,authMethod:p,authMethodBinding:t,keyFactsInventoryAuthority:i,routeAuthorization:w})),p===z.passkey){let t=d;if(!t)throw Error(`[login] passkey threshold warm-up completed without a credential`);await Tx({context:e,statusReads:j,walletIdentity:l,signersWarmed:T.signersWarmed,credential:t})}}if(await O(f),k(),S&&d&&C){let t=wl(d);t&&JC({context:e,sessionAuthority:S,factor:{kind:`passkey`,rpId:s.getRpId(),credentialIdB64u:Tl(d),prfFirstB64u:t},ownedFactorSecret:F(t).slice().buffer,custodyEnvelope:C.envelope})}let M=jx({identity:l,accountSubject:t}),ee=T?{...M,...T.kind===`threshold_login_warmup_ready`?{signingSession:T.signingSession}:{}}:M;return js(i,u,{phase:G.STEP_06_SESSION_READY,status:`succeeded`,authMethod:d?`passkey`:void 0}),await oc({context:e,authMethod:p,unlockSubjectId:u,loginResult:ee,onEvent:i,afterCall:o})}catch(t){return console.warn(`[login] unlock failed before active session commit`,{unlockSubjectId:u,message:t&&typeof t==`object`&&`message`in t?String(t.message||``):String(t||``)}),await oS({context:e,walletId:l.walletId}),await ec({unlockSubjectId:u,message:It(t,`login`)||`Login failed`,error:t,cancelled:Ft(t),onEvent:i,onError:a,afterCall:o})}}async function oS(e){await K.clearLastProfileSelection().catch(()=>void 0);try{e.context.signingEngine.getNonceCoordinator().clearAll()}catch{}try{await e.context.signingEngine.clearVolatileWarmSigningMaterial(e.walletId)}catch{}}function sS(e){return au(e)?e.activation.session.threshold_session_id:e.session.threshold_session_id}function cS(e){return au(e)?e.authorization:{record:e.session.wallet_session,operationCredential:e.session.operation_credential}}function lS(e){if(!e.wantsEcdsaWarmup)return null;if(e.completedActivation){let t;try{let n=e.completedActivation.sessionActivation;if(au(n))t=ze(n.authorization.operationCredential);else{let n=e.completedActivation.response;if(n.kind!==`router_ab_ecdsa_post_registration_session_activated_v1`)throw Error(`completed ECDSA unlock activation branch is invalid`);t=ze(n.session.operation_credential)}}catch{throw Error(`[login] completed ECDSA unlock omitted a valid Wallet Session operation credential`)}return{kind:`wallet_session_operation_credential_v1`,operationCredential:t}}let t=rx({request:e.request??null,routeAuthorization:e.routeAuthorization});if(t?.kind===`webauthn`)throw Error(`[login] ECDSA warm-up requires the Wallet Session minted by the unlock assertion`);return t}function uS(e){let t=e.continuity.signers.find(t=>H(t.chainTarget)===e.prepared.targetKey);if(!t)throw Error(`Passkey ECDSA custody continuity omitted the requested chain target`);let n=t.walletKey.publicCapability,r=t.activationReceipt,i=r.ecdsa_activation,a=e.response.normal_signing.scope;if(t.walletKey.walletId!==e.walletId||t.walletKey.keyHandle!==e.prepared.policy.key_handle||e.response.session.threshold_session_id!==e.prepared.policy.session_policy.threshold_session_id||!kS(t.runtimePolicyScope,e.prepared.policy.session_policy.runtime_policy_scope)||!ti(e.response.public_capability,n)||!xi(e.activationReceipt,r)||n.context.application_binding_digest_b64u!==i.context.application_binding_digest_b64u||!ri(n.public_identity,i.public_identity)||!ei(n.material_activation,i.material_activation)||!fi(n.signer_set.selected_server,i.signing_worker)||n.activation_epoch!==i.activation_epoch||a.context.application_binding_digest_b64u!==i.context.application_binding_digest_b64u||!ri(a.public_identity,i.public_identity)||!ei(a.material_activation,i.material_activation)||!fi(a.signing_worker,i.signing_worker)||a.activation_epoch!==i.activation_epoch||a.wallet_id!==e.walletId||a.ecdsa_threshold_key_id!==t.walletKey.ecdsaThresholdKeyId||a.signing_root_id!==t.walletKey.signingRootId||a.signing_root_version!==t.walletKey.signingRootVersion)throw Error(`Passkey ECDSA session activation changed custody continuity`)}function dS(e){let t=e.signer.walletKey.publicCapability.public_identity;if(e.publicFacts.contextBinding32B64u!==t.context_binding_b64u||e.publicFacts.derivationClientSharePublicKey33B64u!==t.derivation_client_share_public_key33_b64u||e.publicFacts.relayerPublicKey33B64u!==t.server_public_key33_b64u||e.publicFacts.groupPublicKey33B64u!==t.threshold_public_key33_b64u||e.publicFacts.ethereumAddress!==US(t.ethereum_address20_b64u)||e.publicFacts.clientShareRetryCounter!==t.client_share_retry_counter||e.publicFacts.relayerShareRetryCounter!==t.server_share_retry_counter)throw Error(`Passkey ECDSA custody rejoin changed registered public identity`)}async function fS(e){let t=String(e.unlock.credential.rawId||e.unlock.credential.id||``).trim();if(!t)throw Error(`[login] passkey assertion credential id is missing`);await tc({walletId:e.walletId,credentialIdB64u:t,envelope:e.unlock.custody.envelope})}async function pS(e){let t=jo(e.context.configs.network.chains);if(!Cx({subjectSet:e.walletIdentity.subjectSet,selection:e.selection,hasConfiguredEcdsaTargets:t.length>0}).wantsEcdsaWarmup)return null;let n=t[0];if(!n)return null;let r=await yC(e.context,e.walletIdentity.walletId,void 0,`passkey`),i=H(n.chainTarget),a=r.ecdsaKeys.find(e=>e.targetKey===i);if(!a)throw cC(i);let o=r.runtimePolicyScope;if(!o)throw Error(`[login] passkey ECDSA activation requires runtime policy scope`);let s=aC(iC(`threshold-ecdsa-login`)),c=oC(iC(`wallet-session-mint`));return{targetKey:i,requiresCustodyRejoin:!a.existingRoleLocalMaterial,policy:{kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:a.keyHandle,session_policy:{threshold_session_id:s,wallet_session_mint_id:c,ttl_ms:e.ttlMs,remaining_uses:e.remainingUses,runtime_policy_scope:o}}}}function mS(e){switch(e.walletIdentity.kind){case`near_ed25519_capable_wallet`:return{kind:`requested`,remainingUses:e.remainingUses};case`evm_family_ecdsa_only_wallet`:return{kind:`not_requested`};default:return Q(e.walletIdentity)}}function hS(e){return e.activation?{type:`passkey_assertion`,challengeId:e.challengeId,walletId:String(e.walletIdentity.walletId),webauthn_authentication:e.credential,ed25519SessionRequest:e.ed25519SessionRequest,expected_origin:e.expectedOrigin,ecdsaSessionPolicy:e.activation.policy}:{type:`passkey_assertion`,challengeId:e.challengeId,webauthn_authentication:e.credential,ed25519SessionRequest:e.ed25519SessionRequest,expected_origin:e.expectedOrigin}}async function gS(e){let t=Tl(e.credential);if(!t)throw Error(`Passkey Wallet Session adoption requires WebAuthn credential identity`);let n=await Vs({walletId:e.walletIdentity.walletId,rpId:e.rpId,credentialIdB64u:t}),r=await _c({walletId:e.walletIdentity.walletId,authorization:e.authorization});if(e.authorization.record.walletId!==e.walletIdentity.walletId||e.authorization.record.authMethodId!==n.walletAuthMethodId||e.authorization.record.authorityId!==n.walletAuthorityId||r.reference.walletId!==e.walletIdentity.walletId)throw Error(`Passkey Wallet Session authorization changed auth-method identity`);return r}function _S(e,t){return{...e,session_policy:{...e.session_policy,wallet_session_mint_id:oC(t)}}}async function vS(e,t){js(e.onEvent,e.unlockSubjectId,{phase:G.STEP_03_PASSKEY_CHALLENGE_STARTED,status:`running`,authMethod:`passkey`});let n=await fetch(c(e.relayUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:String(e.walletIdentity.walletId),rpId:e.rpId})}),r=await n.json().catch(()=>({})),i=A(r)?r:{},a=typeof i.message==`string`?i.message:``;if(!n.ok||i.ok!==!0)throw Error(a||`wallet/unlock/challenge failed (HTTP ${n.status})`);let o=String(i.challengeId||``).trim(),s=String(i.challengeB64u||``).trim();if(!o||!s)throw Error(`wallet/unlock/challenge returned invalid challenge`);let l=e.activation?{...e.activation,policy:_S(e.activation.policy,o)}:null,u=Sx({authenticators:e.authenticators,signerSlot:e.signerSlot,serverCredentialIds:xx(i.credentialIds)}),d=await e.collectCredentialForChallenge({challengeB64u:s,credentialIds:u}),f=String(e.expectedOrigin??(typeof window<`u`?window.location.origin:``)).trim();if(!f)throw Error(`[login] passkey wallet unlock requires an expected origin`);let p=hS({challengeId:o,credential:d,ed25519SessionRequest:mS({walletIdentity:e.walletIdentity,remainingUses:e.remainingUses}),expectedOrigin:f,walletIdentity:e.walletIdentity,activation:l}),m=await Vs({walletId:e.walletIdentity.walletId,rpId:e.rpId,credentialIdB64u:Tl(d)}),h=await Os({walletId:e.walletIdentity.walletId,authMethodId:m.walletAuthMethodId}),g=await qo(e.relayUrl,p,t);if(!g.success)throw Error(g.error||`Passkey wallet unlock failed`);if(!g.walletCustody)throw Error(`Passkey wallet unlock omitted wallet custody continuity`);if(l&&(!g.ecdsaSession||!g.ecdsaActivationReceipt||!g.ecdsaCustody))throw Error(`Passkey wallet unlock omitted the requested ECDSA activation`);let _=g.walletSessionAuthorization??null;_&&await Ms({session:_.record,previous:h});let v=_?await gS({walletIdentity:e.walletIdentity,rpId:e.rpId,credential:d,authorization:_}):null,y=null;if(l&&g.ecdsaSession&&g.ecdsaActivationReceipt&&g.ecdsaCustody&&g.ecdsaSession.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){let e=g.walletSessionAuthorization;if(!e)throw Error(`Passkey credential-free activation omitted exact Wallet Session authority`);if(!v)throw Error(`Passkey credential-free activation omitted exact Passkey authority`);y={kind:`credential_free_ecdsa_session_activation_authorization_v1`,activation:g.ecdsaSession,authorization:e}}l&&g.ecdsaSession&&g.ecdsaActivationReceipt&&g.ecdsaCustody&&(uS({walletId:String(e.walletIdentity.walletId),prepared:l,response:g.ecdsaSession,activationReceipt:g.ecdsaActivationReceipt,continuity:g.ecdsaCustody}),g.ecdsaSession.kind===`router_ab_ecdsa_post_registration_session_activated_v1`&&(y=g.ecdsaSession));let b=y?await gS({walletIdentity:e.walletIdentity,rpId:e.rpId,credential:d,authorization:cS(y)}):null;if(_&&await q.writeExactWithOperationCredential(_),l?.requiresCustodyRejoin){if(!(`ecdsaCustody`in g)||!g.ecdsaCustody)throw Error(`Passkey wallet unlock omitted ECDSA custody rejoin continuity`);let t=wl(d);if(!t)throw Error(`Passkey ECDSA custody rejoin requires WebAuthn PRF.first`);let n=Tl(d),r=b?.reference??v?.reference??await Us({walletId:e.walletIdentity.walletId,rpId:e.rpId,credentialIdB64u:n});await GS({signingEngine:e.context.signingEngine,walletId:String(e.walletIdentity.walletId),custody:g.walletCustody,continuity:g.ecdsaCustody,authority:r,passkeyPrfFirstB64u:t})}return{credential:d,activation:l&&g.ecdsaSession&&y&&b?{...l,response:g.ecdsaSession,sessionActivation:y,authorizationIdentity:b.identity,activationReceipt:g.ecdsaActivationReceipt,continuity:g.ecdsaCustody}:null,custody:g.walletCustody,result:g}}var yS=class{promise;resolvePromise;rejectPromise;settled=!1;constructor(){this.promise=new Promise(this.capturePromise.bind(this))}resolve(e){this.settled||(this.settled=!0,this.resolvePromise(e))}reject(e){this.settled||(this.settled=!0,this.rejectPromise(I(e)))}async wait(){return await this.promise}capturePromise(e,t){this.resolvePromise=e,this.rejectPromise=t}};async function bS(e,t){e.sharedState.ed25519.thresholdSessionId=String(t.thresholdSessionId),e.sharedState.ed25519.authorizationId=t.authorizationId,e.sharedState.ed25519.walletSessionId=t.walletSessionId,e.sharedState.ed25519.quotaId=t.quotaId,e.sharedState.ed25519.operationCredential=t.operationCredential,e.sharedState.ed25519.expiresAtMs=t.expiresAtMs,e.sharedState.ed25519.remainingUses=t.remainingUses,e.sharedState.ed25519.runtimePolicyScope=t.runtimePolicyScope,e.authorityDeferred?.resolve(t)}function xS(e,t){e?.reject(t)}function SS(e){return{sessionId:String(e.session.thresholdSessionId),status:`active`,authMethod:e.authMethod,...e.authMethod===z.emailOtp?{retention:`session`}:{},remainingUses:e.session.remainingUses,expiresAtMs:e.session.expiresAtMs}}function CS(e){return e?.kind===`opaque_wallet_session_operation_credential_v1`}function wS(e){let t=e.thresholdEcdsaKeyRef.backendBinding;if(t)switch(t.materialKind){case`role_local_worker_handle`:case`role_local_durable_sealed_ref`:case`role_local_durable_public_anchor`:return t.publicFacts.publicCapability;case`role_local_ready_state_blob`:return t.ecdsaRoleLocalReadyRecord.publicFacts.publicCapability;case`metadata_only`:return}}function TS(e){return JSON.stringify(e)}function ES(e){let t=wS(e);if(!t)throw Error(`[login] ECDSA bootstrap is missing its public capability`);let n=e.session,r=e.thresholdEcdsaKeyRef.routerAbEcdsaDerivationNormalSigning;if(!r)throw Error(`[login] ECDSA bootstrap is missing normal-signing state`);return{kind:`router_ab_ecdsa_post_registration_session_activated_v1`,public_capability:t,session:{authorization_session_id:n.authorizationSessionId,authorization_id:n.authorizationId,threshold_session_id:aC(n.thresholdSessionId),wallet_session_id:n.walletSessionId,quota_id:n.quotaId,expires_at_ms:n.expiresAtMs,remaining_uses:n.remainingUses,wallet_session:n.walletSession,operation_credential:n.operationCredential},normal_signing:r}}function DS(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function OS(e,t){return e.kind===t.kind&&e.signingWorkerId===t.signingWorkerId}function kS(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}function AS(e){if(e.current.runtimePolicyScope&&e.incoming.runtimePolicyScope&&!kS(e.current.runtimePolicyScope,e.incoming.runtimePolicyScope))throw Error(`[login] threshold ECDSA ${e.source} has a conflicting runtime policy scope`);return Uy(e.current,e.incoming)}async function jS(e){if(e.targetEcdsaKey.publicCapability.kind===`persisted_public_capability`){let t=e.targetEcdsaKey.publicCapability.value;if(String(t.client_id)!==String(e.walletId))throw Error(`[login] threshold ECDSA persisted public capability wallet mismatch for ${H(e.chainTarget)}`);return t}let t=await dy({walletId:e.walletId,chainTarget:e.chainTarget});if(t.kind!==`resolved`)throw cC(H(e.chainTarget));let n=t.manifest.durableMaterial.roleLocalPublicFacts;if(String(n.keyHandle)!==String(e.targetEcdsaKey.keyHandle)||String(n.walletId)!==String(e.walletId))throw cC(H(e.chainTarget));return n.publicCapability}function MS(e){let t=[];for(let n of e)n!==`ed25519`&&n!==`ecdsa`||t.includes(n)||t.push(n);return t}async function NS(e){try{return await e.run(),{kind:`succeeded`,task:e}}catch(t){return e.onFailure?.(t),{kind:`failed`,task:e,error:I(t)}}}async function PS(e){let t=new Map;for(let n of e)t.set(n.signer,n);let n=new Set;for(;t.size>0;){let e=[];for(let r of t.values())r.dependencies.every(e=>n.has(e))&&e.push(r);if(e.length===0)throw Error(`[login] threshold warm-up task dependency graph is unsatisfied`);let r=await Promise.all(e.map(NS)),i=null;for(let e of r)switch(e.kind){case`succeeded`:n.add(e.task.signer),t.delete(e.task.signer);break;case`failed`:i??=e.error;break;default:return Q(e)}if(i)throw i}}function FS(e){if(e.routeAuthorization.kind,e.credentialState.kind===`available`)return{};throw Error(`[login] threshold ECDSA warm-up requires route authorization`)}function IS(e){return String((e&&typeof e==`object`&&`message`in e?e.message:e)||``)}function Q(e){throw Error(`[login] unexpected state: ${String(e)}`)}async function LS(e){switch(e.runtimeScopeBootstrapState.kind){case`available`:return await e.signingEngine.bootstrapEcdsaSession({...e.request,runtimeScopeBootstrap:e.runtimeScopeBootstrapState.runtimeScopeBootstrap});case`unavailable`:return await e.signingEngine.bootstrapEcdsaSession(e.request);default:return Q(e.runtimeScopeBootstrapState)}}function RS(e){if(`operationCredential`in e)return e.operationCredential;throw Error(`[login] wallet custody Ed25519 activation requires the exact issued operation credential`)}async function zS(e){let t=await e.signingEngine.getUserBySignerSlot(e.walletBinding.nearAccountId,e.signerSlot).catch(()=>null);if(t){if(t.walletId!==String(e.walletBinding.walletId)||t.nearEd25519SigningKeyId!==String(e.walletBinding.nearEd25519SigningKeyId)||t.signerSlot!==e.signerSlot)throw Error(`[login] local Ed25519 owner profile identity is invalid`);return}await e.signingEngine.storeUserData({walletId:String(e.walletBinding.walletId),nearAccountId:e.walletBinding.nearAccountId,nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),signerSlot:e.signerSlot,operationalPublicKey:`ed25519:${tn(e.registeredPublicKey)}`,passkeyCredential:{id:e.credentialIdB64u,rawId:e.credentialIdB64u},lastUpdated:Date.now(),version:2})}function BS(e,t){let n=e.ed25519.capability,r=n.registrationContinuity;return{materialActivation:n.materialActivation,lifecycleId:n.lifecycle.lifecycleId,signingRootVersion:n.lifecycle.rootShareEpoch,signingRootId:n.applicationBinding.signing_root_id,signerSetId:n.lifecycle.signerSetId,thresholdSessionId:t,activationTranscriptB64u:P(Uint8Array.from(r.activationTranscript)),activationCapabilityBindingB64u:P(Uint8Array.from(n.activeCapabilityBinding))}}function VS(e){let t=e.custody.ed25519,n=t.capability;if(t.nearAccountId!==String(e.walletBinding.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.walletBinding.nearEd25519SigningKeyId)||t.signerSlot!==e.signerSlot||n.applicationBinding.wallet_id!==String(e.walletBinding.walletId)||n.applicationBinding.near_ed25519_signing_key_id!==String(e.walletBinding.nearEd25519SigningKeyId)||n.applicationBinding.key_creation_signer_slot!==e.signerSlot||n.nearAccountId!==e.walletBinding.nearAccountId||n.lifecycle.accountId!==String(e.walletBinding.walletId)||n.lifecycle.signingWorkerId!==t.relayerKeyId)throw Error(`[login] wallet custody identity does not match the selected signing lane`)}async function HS(e){VS(e);let t=e.custody.ed25519.capability,r=await e.signingEngine.loadWalletCustodyEd25519Material({nearAccountId:String(e.walletBinding.nearAccountId),signerSlot:e.signerSlot,expectedRegisteredPublicKeyB64u:P(Uint8Array.from(t.registeredPublicKey))}),i=n(e.walletSession.thresholdSessionId);if(!i.ok)throw Error(`[login] wallet custody returned an invalid threshold session identity`);let a=BS(e.custody,i.value),o=Ko(e.custody.envelope),s=await Os({walletId:e.walletBinding.walletId,authMethodId:e.authority.walletAuthMethodId}),c=null,l=null,u=null;try{if(r.kind===`found`)u=F(e.passkeyPrfFirstB64u),c=await Po({material:r.material,activation:a,envelope:o,ownedFactorSecret:u});else{let n=Xs(e.custody.envelope);if(!n.ok)throw Error(n.reason);l=F(e.passkeyPrfFirstB64u),u=F(e.passkeyPrfFirstB64u);let r=await e.signingEngine.rejoinWalletCustodyNearEd25519KeySet({walletId:String(e.walletBinding.walletId),custodyJson:n.custodyJson,factorSecret:l.buffer,nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),recoveryBasis:t,routerOrigin:new URL(e.relayerUrl).origin,walletSessionToken:RS(e.walletSession).token}),i={kind:Mc,applicationBindingDigestB64u:r.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:P(r.metadata.registeredPublicKey),participantIds:r.metadata.participantIds,stateEpoch:String(r.metadata.stateEpoch),walletId:String(e.walletBinding.walletId),nearAccountId:String(e.walletBinding.nearAccountId),nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),signerSlot:e.signerSlot,signingWorkerId:e.custody.ed25519.relayerKeyId,signingWorkerVerifyingShareB64u:P(r.metadata.signingWorkerVerifyingShare)},a={ciphertextB64u:r.localMaterial.b64u,nonceB64u:r.localMaterial.nonceB64u};try{await e.signingEngine.persistWalletCustodyEd25519Material({binding:i,sealed:a})}catch(e){console.warn(`[login] wallet custody cache write failed; continuing with verified material`,{error:e})}c=await Po({material:{binding:i,sealed:a},activation:ys(r.metadata),envelope:o,ownedFactorSecret:u})}if(!c)throw Error(`[login] wallet custody produced no active client`);let i=n(c.metadata().scope.threshold_session_id);if(!i.ok)throw Error(`[login] wallet custody returned an invalid threshold session identity`);if(i.value!==e.walletSession.thresholdSessionId)throw Error(`[login] wallet custody changed the threshold session identity`);let d=e.custody.envelope.factor;if(d.kind!==`passkey`)throw Error(`[login] wallet custody returned a different factor authority`);await zS({signingEngine:e.signingEngine,walletBinding:e.walletBinding,signerSlot:e.signerSlot,credentialIdB64u:d.credentialIdB64u,registeredPublicKey:c.metadata().registeredPublicKey}),await Wo({store:K,activeClient:c,identity:{walletId:String(e.walletBinding.walletId),nearAccountId:String(e.walletBinding.nearAccountId),nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),thresholdSessionId:i.value,signerSlot:e.signerSlot,rpId:d.rpId,credentialIdB64u:d.credentialIdB64u,signingRootId:t.applicationBinding.signing_root_id,signingRootVersion:t.lifecycle.rootShareEpoch,signingWorkerId:e.custody.ed25519.relayerKeyId},stableServerScope:{relayerKeyId:e.custody.ed25519.relayerKeyId,participantIds:e.custody.ed25519.participantIds,runtimePolicyScope:t.runtimePolicyScope,routerAbNormalSigning:e.routerAbNormalSigning},passkeyPrfFirstB64u:e.passkeyPrfFirstB64u});let f=await e.signingEngine.activateVerifiedNearEd25519YaoMaterial({activeClient:c,facts:{thresholdSessionId:i.value,signer:fl({walletId:e.walletBinding.walletId,nearAccountId:e.walletBinding.nearAccountId,nearEd25519SigningKeyId:e.walletBinding.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),signingRootId:t.applicationBinding.signing_root_id,signingRootVersion:t.lifecycle.rootShareEpoch,routerAbNormalSigning:e.routerAbNormalSigning,runtimePolicyScope:t.runtimePolicyScope,relayerUrl:e.relayerUrl}}),p=cs({walletId:String(e.walletBinding.walletId),nearAccountId:String(e.walletBinding.nearAccountId),nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),walletSessionId:e.walletSession.walletSessionId,authorizationId:e.walletSession.authorizationId,quotaId:e.walletSession.quotaId,thresholdSessionId:i.value,remainingUses:e.walletSession.remainingUses,expiresAtMs:e.walletSession.expiresAtMs,runtimePolicyScope:e.walletSession.runtimePolicyScope,signingRootId:t.applicationBinding.signing_root_id,signingRootVersion:t.lifecycle.rootShareEpoch,routerAbNormalSigning:e.routerAbNormalSigning,walletSessionToken:RS(e.walletSession).token,home:RS(e.walletSession).home,nowMs:Math.min(Date.now(),e.walletSession.expiresAtMs-1)});if(!p.ok)throw Error(`[login] wallet custody returned an unusable Ed25519 Wallet Session: ${p.reason}`);let m=Bs({walletId:e.walletBinding.walletId,nearAccountId:e.walletBinding.nearAccountId,nearEd25519SigningKeyId:e.walletBinding.nearEd25519SigningKeyId,signerSlot:e.signerSlot,rpId:wa(d.rpId),credentialIdB64u:d.credentialIdB64u,relayerUrl:e.relayerUrl,authority:e.authority,signingWalletSession:p.value});return await ds({persistence:e.signingEngine,session:m,prfFirstB64u:e.passkeyPrfFirstB64u,ed25519Restore:es({rpId:d.rpId,nearAccountId:String(e.walletBinding.nearAccountId),nearEd25519SigningKeyId:String(e.walletBinding.nearEd25519SigningKeyId),relayerKeyId:e.custody.ed25519.relayerKeyId,participantIds:e.custody.ed25519.participantIds,runtimePolicyScope:e.walletSession.runtimePolicyScope,signerSlot:e.signerSlot,routerAbNormalSigning:e.routerAbNormalSigning,credentialIdB64u:d.credentialIdB64u,materialActivation:f.materialActivation}),materialActivation:f.materialActivation}),await e.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:e.custody.envelope,passkeyPrfFirstB64u:e.passkeyPrfFirstB64u,walletId:String(e.walletBinding.walletId),walletAuthMethodId:String(e.authority.walletAuthMethodId),walletSessionId:String(e.walletSession.walletSessionId),expiresAtMs:e.walletSession.expiresAtMs}),r.kind===`found`?{kind:`unchanged`}:{kind:`recovered`,materialActivation:f.materialActivation,previousAuthority:s}}catch(e){throw c?.dispose(),e}finally{l?.fill(0),u?.fill(0)}}function US(e){let t=F(e);if(t.length!==20)throw Error(`[login] ECDSA custody address is invalid`);let n=`0x`;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n}function WS(e){let[t,...n]=e;if(!t)throw Error(`[login] passkey ECDSA custody continuity is empty`);return[t.chainTarget,...n.map(e=>e.chainTarget)]}async function GS(e){let t=e.continuity.signers[0];if(!t)throw Error(`[login] passkey ECDSA custody continuity is empty`);if(t.walletKey.walletId!==e.walletId)throw Error(`[login] passkey ECDSA custody continuity changed wallet identity`);for(let n of e.continuity.signers)if(n.walletKey.walletId!==t.walletKey.walletId||n.walletKey.keyHandle!==t.walletKey.keyHandle||n.walletKey.ecdsaThresholdKeyId!==t.walletKey.ecdsaThresholdKeyId||n.walletKey.signingRootId!==t.walletKey.signingRootId||n.walletKey.signingRootVersion!==t.walletKey.signingRootVersion||n.walletKey.relayerKeyId!==t.walletKey.relayerKeyId||!ti(n.walletKey.publicCapability,t.walletKey.publicCapability)||!xi(n.activationReceipt,t.activationReceipt)||!kS(n.runtimePolicyScope,t.runtimePolicyScope))throw Error(`[login] passkey ECDSA custody continuity conflicts across targets`);let n=Xs(e.custody.envelope);if(!n.ok)throw Error(n.reason);let r=F(e.passkeyPrfFirstB64u);try{let i=await e.signingEngine.rejoinWalletCustodyEvmFamilyKeySet({walletId:e.walletId,custodyJson:n.custodyJson,factorSecret:r.buffer,evmFamilySigningKeySlotId:Ta({walletId:e.walletId,signingRootId:t.walletKey.signingRootId,signingRootVersion:t.walletKey.signingRootVersion}),applicationBindingDigestB64u:t.walletKey.publicCapability.context.application_binding_digest_b64u,registeredClientRootPublicKey33B64u:t.walletKey.derivationClientSharePublicKey33B64u,relayerPublicIdentityJson:JSON.stringify({relayerKeyId:t.walletKey.relayerKeyId,relayerPublicKey33B64u:t.activationReceipt.ecdsa_activation.public_identity.server_public_key33_b64u,groupPublicKey33B64u:t.activationReceipt.ecdsa_activation.public_identity.threshold_public_key33_b64u,ethereumAddress:US(t.activationReceipt.ecdsa_activation.public_identity.ethereum_address20_b64u),relayerShareRetryCounter:t.activationReceipt.ecdsa_activation.public_identity.server_share_retry_counter})});dS({publicFacts:i.publicFacts,signer:t}),await e.signingEngine.restoreWalletCustodyEcdsaContinuity({authority:e.authority,chainTargets:WS(e.continuity.signers),walletId:t.walletKey.walletId,keyHandle:t.walletKey.keyHandle,ecdsaThresholdKeyId:t.walletKey.ecdsaThresholdKeyId,signingRootId:t.walletKey.signingRootId,signingRootVersion:t.walletKey.signingRootVersion,relayerKeyId:t.walletKey.relayerKeyId,participantIds:t.walletKey.participantIds,publicCapability:t.walletKey.publicCapability,activationReceipt:t.activationReceipt,runtimePolicyScope:t.runtimePolicyScope,readyStateBlobB64u:i.readyStateBlobB64u,publicFacts:i.publicFacts})}finally{r.fill(0)}}async function KS(e){let t=MS(e.signersToWarm),n=e.credentialState.kind===`available`?e.credentialState.credential:void 0,r=e.credentialState.localPasskeyCredentialIdB64u,i=e.runtimeScopeBootstrapState.kind===`available`?e.runtimeScopeBootstrapState.runtimeScopeBootstrap:null,a=e.ecdsaContext,o={activeCanonicalEcdsaContext:a,ed25519:{thresholdSessionId:``,authorizationId:null,walletSessionId:null,quotaId:null,operationCredential:null,expiresAtMs:0,remainingUses:0,runtimePolicyScope:null}},s=e.ecdsaDependency.kind===`ed25519_wallet_session_authority`?new yS:null,c={generatedThresholdSessionId:e.passkeyExchangeEcdsaActivation?.policy.session_policy.threshold_session_id||``},l=e.unlockRemainingUses,u=[],d=null,f={outcome:{kind:`unchanged`}},p=null,m=[];if(t.includes(`ed25519`)&&m.push({signer:`ed25519`,dependencies:e.ed25519DependsOnEcdsa?[`ecdsa`]:[],onFailure:s?xS.bind(void 0,s):null,run:async()=>{let t=Eb(e.walletIdentity),c=p,u=ux({authority:lx(e.ed25519SessionAuthority),walletId:t.walletId,rpId:e.context.signingEngine.getRpId(),credentialIdB64u:r}),m=px({mintPlan:e.ed25519MintPlan,ecdsaMint:c,walletBinding:t,signerSlot:e.signerSlot,authority:u}),h=hx({mintPlan:e.ed25519MintPlan,fallback:{relayerKeyId:e.relayerKeyId,participantIds:e.participantIds,runtimePolicyScope:a.runtimePolicyScope??null,routerAbNormalSigning:_y(e.context.configs)}}),g={relayerUrl:e.relayerUrl,relayerKeyId:h.relayerKeyId,runtimePolicyScope:h.runtimePolicyScope||void 0,routerAbNormalSigning:h.routerAbNormalSigning,runtimeScopeBootstrap:i||void 0,participantIds:h.participantIds,ttlMs:e.ttlMs,remainingUses:l,onWalletSessionAuthorityReady:bS.bind(void 0,{sharedState:o,authorityDeferred:s})},_=m.kind===`fresh_ed25519_provisioning`?{...m,walletId:String(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:e.signerSlot,...g}:{...m,...g},v;switch(u.kind){case`email_otp`:v=await e.signingEngine.connectEd25519Session({..._,source:`email_otp`,authority:u.authority,emailOtpAuthContext:u.emailOtpAuthContext,materialActivation:void 0});break;case`passkey`:if(!e.passkeyUnlockEd25519Session)throw Error(`[login] verified wallet unlock omitted its Ed25519 Wallet Session`);if(e.ed25519MintPlan.kind!==`wallet_custody`)throw Error(`[login] verified unlock Ed25519 session requires wallet custody`);v=gx({session:e.passkeyUnlockEd25519Session,walletBinding:t,signerSlot:e.signerSlot,custody:e.ed25519MintPlan.custody,provisionScope:h,credential:n,remainingUses:l,unlockAuthorization:e.passkeyUnlockWalletSessionAuthorization});break;default:return Q(u)}if(!v.ok){let e=String(v.message||v.code||`Failed to connect threshold Ed25519 session`);throw Error(`[login] threshold Ed25519 warm-up failed: ${e}`)}if(d=v,!v.thresholdSessionId)throw Error(`[login] threshold Ed25519 warm-up did not return a thresholdSessionId`);let y=u.kind===`passkey`?await Us({walletId:t.walletId,rpId:e.context.signingEngine.getRpId(),credentialIdB64u:Tl(n||void 0)||r}):await U({authority:u.authority.authority});if(e.ed25519MintPlan.kind===`wallet_custody`){if(u.kind!==`passkey`)throw Error(`[login] wallet custody requires passkey authority`);let r=mx(m,e.ed25519MintPlan),i=n?wl(n):``;if(!i)throw Error(`[login] wallet custody requires WebAuthn PRF.first`);f.outcome=await e.signingEngine.withExactEd25519MaterialOwner({materialActivation:r,nearAccountId:t.nearAccountId,task:HS.bind(void 0,{signingEngine:e.signingEngine,custody:e.ed25519MintPlan.custody,walletBinding:t,signerSlot:e.signerSlot,passkeyPrfFirstB64u:i,walletSession:v,authority:y,routerAbNormalSigning:h.routerAbNormalSigning,relayerUrl:e.relayerUrl})})}}}),t.includes(`ecdsa`)&&m.push({signer:`ecdsa`,dependencies:[],onFailure:null,run:async()=>{await s?.promise;let t=null,i=!1,a=new Map,d=jo(e.context.configs.network.chains),f=e=>{let t=Wy({context:o.activeCanonicalEcdsaContext,configuredTargets:d});if(t.kind===`complete_configured_target_keys`){o.activeCanonicalEcdsaContext=t.context;return}t.kind!==`missing_configured_target_keys`&&Gy({completion:t,source:e})},m=e=>{if(p)return;let t=e.session.operationCredential,i=n?wl(n):``,a=Tl(n||void 0)||r;!t.token||!i||!a||(p={operationCredential:t,passkeyPrfFirstB64u:i,passkeyCredentialIdB64u:a,quotaId:e.session.quotaId})},h=()=>{if(o.ed25519.operationCredential)return{routeAuth:o.ed25519.operationCredential};let n=p?.operationCredential;return n?{routeAuth:n}:t||(t=FS({credentialState:e.credentialState,routeAuthorization:e.routeAuthorization}),t)},g=async(t,n)=>{if(!n.key)throw Error(`[login] threshold ECDSA warm-up requires configured target key identity`);let s=await jS({walletId:e.walletIdentity.walletId,chainTarget:t.chainTarget,targetEcdsaKey:n}),u=a.get(TS(s)),d=e.passkeyExchangeEcdsaActivation,f=d&&!i&&d.targetKey===H(t.chainTarget)?d:null,p=f?{sessionActivation:f.sessionActivation,authorizationIdentity:f.authorizationIdentity}:u??null,m=p?sS(p.sessionActivation):uC({sharedState:c}),g=o.activeCanonicalEcdsaContext.runtimePolicyScope;if(!g)throw Error(`[login] ECDSA session lane requires runtimePolicyScope`);let _=Ea({chainTarget:t.chainTarget,thresholdSessionId:m,ttlMs:e.ttlMs,remainingUses:l,runtimePolicyScope:g}),v=n.existingRoleLocalMaterial;if(!v)throw cC(H(t.chainTarget));if(!r)throw Error(`[login] ECDSA role-local activation requires passkey identity`);let y=v.authority;if(p)return f&&(i=!0),await LS({signingEngine:e.signingEngine,runtimeScopeBootstrapState:e.runtimeScopeBootstrapState,request:{kind:`passkey_preauthorized_ecdsa_bootstrap`,source:`login`,relayerUrl:e.relayerUrl,keyHandle:xa(n.keyHandle),key:n.key,lanePolicy:_,publicCapability:s,existingRoleLocalMaterial:v,authorizationAuthority:y,authorizationIdentity:p.authorizationIdentity,passkeyCredentialIdB64u:r,sessionActivation:p.sessionActivation}});let b=h().routeAuth;if(!CS(b))throw Error(`[login] ECDSA role-local activation requires a verified Wallet Session`);return await LS({signingEngine:e.signingEngine,runtimeScopeBootstrapState:e.runtimeScopeBootstrapState,request:{kind:`wallet_session_reconnect_ecdsa_bootstrap`,source:`login`,relayerUrl:e.relayerUrl,keyHandle:xa(n.keyHandle),key:n.key,lanePolicy:_,publicCapability:s,existingRoleLocalMaterial:v,authorizationAuthority:y,passkeyCredentialIdB64u:r,routeAuth:b}})},_=async()=>{f(`login ECDSA warm-up preflight`);let t=[],n=e.passkeyExchangeEcdsaActivation?.targetKey||null;if(n)for(let e of d)H(e.chainTarget)===n&&t.push(e);for(let e of d)H(e.chainTarget)!==n&&t.push(e);for(let n of t){let t=H(n.chainTarget),r=o.activeCanonicalEcdsaContext.ecdsaKeys.find(e=>e.targetKey===t),i=String(r?.keyHandle||``).trim();if(!r?.key||!i)throw cC(t);let s=await g(n,r);u.push(s),ms({statusReads:e.statusReads,trigger:`unlock`,signingEngine:e.signingEngine,walletId:e.walletIdentity.walletId,chainTarget:n.chainTarget}),m(s);let c=ES(s),l=TS(c.public_capability);if(!a.has(l)){let t=await _c({walletId:e.walletIdentity.walletId,authorization:{record:s.session.walletSession,operationCredential:s.session.operationCredential}});a.set(l,{sessionActivation:c,authorizationIdentity:t.identity})}if(String(s.thresholdEcdsaKeyRef?.keyHandle||``).trim()!==r.keyHandle)throw Error(`[login] threshold ECDSA warm-up returned a different keyHandle for ${t}`)}if(e.passkeyExchangeEcdsaActivation&&!i)throw Error(`[login] passkey exchange ECDSA activation did not match a configured target`)};try{await _()}catch(e){let t=IS(e)||`Failed to bootstrap threshold ECDSA session`;throw Error(`[login] threshold ECDSA warm-up failed: ${t}`)}}}),await PS(m),f.outcome.kind===`recovered`){if(!e.passkeyUnlockWalletSessionAuthorization)throw Error(`Recovered passkey material requires its exact Wallet Session`);await dc({authorization:e.passkeyUnlockWalletSessionAuthorization,materialActivation:f.outcome.materialActivation,relayerUrl:e.relayerUrl,statusReads:e.statusReads,previousAuthority:f.outcome.previousAuthority})}return{ecdsaBootstraps:u,ed25519Session:d}}async function qS(e,t,n){let r=e.signingEngine.readWalletAuthenticationState(),i=t??(r.kind===`signed_out`?void 0:r.walletId),a=null,o=null;if(i!==void 0){let e=_(String(i));if(e.ok){if(a=e.value,o=await ky({walletId:e.value,ports:Tg}),o.kind===`upgrade_required`)throw new Ra(`[WalletSession] Wallet Session authorization requires a newer client`);o.kind===`missing`&&(r={kind:`signed_out`})}}let s=await vb(i);if(s.kind===`no_session_for_wallet`){let e=await Fx(String(s.walletId));e&&(s={kind:`resolved`,walletId:s.walletId,subjectSet:e,source:`local_wallet_authority`})}let c=!1;if(s.kind===`no_session_request`)return dt();if(s.kind===`no_session_for_wallet`){let t=await $y(s.walletId);if(t.kind!==`resolved`)return await XS({context:e,walletId:s.walletId,reason:`activation_reconciliation_failed`});if(t.selectors.length>0){c=!0;let n=await kb({workerCtx:e.signingEngine.getSignerWorkerContext(),selectors:t.selectors});if(n.didFinalize&&(s=await vb(s.walletId)),s.kind===`no_session_for_wallet`&&n.kind!==`settled`)return await XS({context:e,walletId:s.walletId,reason:n.kind===`pending`?`activation_reconciliation_pending`:`activation_reconciliation_failed`})}}if(s.kind===`no_session_for_wallet`)return await XS({context:e,walletId:s.walletId,reason:s.reason});if(s.kind===`no_session_request`)return dt();if(s.kind===`unresolvable_profile`)return console.warn(`[WalletSession] wallet session profile is unresolvable`,{profileId:s.profileId,reason:s.reason}),dt();if(s.kind===`unresolvable`)return console.warn(`[WalletSession] wallet session identity is unresolvable`,{walletId:String(s.walletId),reason:s.reason}),await XS({context:e,walletId:s.walletId,reason:s.reason});let l=Ob(s.subjectSet);!c&&l.length>0&&Ab(await kb({workerCtx:e.signingEngine.getSignerWorkerContext(),selectors:l})),e.signingEngine.assertSealedRefreshStartupParity().catch(e=>{console.warn(`[WalletSession] sealed refresh startup parity check failed during session read; continuing with cached login state`,e instanceof Error?e.message:String(e||`unknown error`))});let[u,d]=await Promise.all([zC(e,s),ZS(e,s.walletId,n)]),f=o&&a&&String(a)===String(s.walletId)?o:await ky({walletId:s.walletId,ports:Tg}),p={kind:`signed_out`};switch(f.kind){case`authenticated`:await YS(e,f.state)&&(p=f.state);break;case`missing`:break;case`upgrade_required`:throw new Ra(`[WalletSession] Wallet Session authorization requires a newer client`)}let m=MC({subjectSet:p.kind===`authenticated`&&f.kind===`authenticated`?JS(s.subjectSet,f.walletAuthMethodId):s.subjectSet,availableLanes:d,configuredEcdsaTargets:jo(e.configs.network.chains).map(e=>e.chainTarget)});return{appIdentity:u,authentication:p,capabilityProjection:m,nonceDiagnostics:QS(e,u.nearAccountId)}}function JS(e,t){let[n,...r]=e.subjects.filter(e=>e.kind!==`evm_family_ecdsa_wallet`||String(e.authority.walletAuthMethodId)===String(t));return n?{...e,subjects:[n,...r]}:e}async function YS(e,t){if(t.authMethod===`voiceid`){let n=e.signingEngine.readWalletAuthenticationState();if(n.kind!==`authenticated`||n.walletId!==t.walletId||n.authMethod!==`voiceid`)return!1}let n=!1;try{let e=await K.resolveSelectedWalletAuthority(String(t.walletId));n=e.kind!==`resolved`||e.selection.lockState!==`unlocked`}catch{n=!0}return n?!1:(e.signingEngine.setWalletAuthenticated(t),!0)}async function XS(e){let[t,n]=await Promise.all([RC(e.context,e.walletId),ky({walletId:e.walletId,ports:Tg})]),r={kind:`signed_out`};switch(n.kind){case`authenticated`:await YS(e.context,n.state)&&(r=n.state);break;case`missing`:break;case`upgrade_required`:throw new Ra(`[WalletSession] Wallet Session authorization requires a newer client`)}return{appIdentity:t,authentication:r,capabilityProjection:{kind:`unresolvable`,reason:e.reason},nonceDiagnostics:QS(e.context,t.nearAccountId)}}function ZS(e,t,n){return e.signingEngine.readPersistedAvailableSigningLanes({walletId:t},n).then(e=>({kind:`available`,lanes:e})).catch(()=>({kind:`unavailable`}))}function QS(e,t){let n=String(t||``).trim();if(!n)return null;try{return e.signingEngine.getNonceCoordinator().getDiagnostics({accountId:n,emitMetrics:!0})}catch{return null}}function $S(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:``}async function eC(e,t){let n=jo(e.configs.network.chains).map(e=>e.chainTarget);if(!n.length)return[];let r=await K.listAccountSignersByProfile({profileId:String(t),status:`active`}).catch(()=>[]),i=[];for(let e of r){let r=zy({walletId:t,configuredTargets:n,signer:e});r.kind===`active_ecdsa_signer_record`&&i.push(r.walletKey)}return i}async function tC(e,t){let n=[...new Set((await eC(e,t)).map(e=>$S(e.keyFacts.thresholdOwnerAddress)).filter(Boolean))];return n.length===1?n[0]:(n.length>1&&console.warn(`[WalletSession] conflicting profile threshold ECDSA addresses`,{walletId:String(t),addresses:n}),null)}function nC(e){if(e.selection.mode===`ed25519_only`)return[`ed25519`];if(!e.configuredEcdsaTargets.length)return e.selection.mode===`ecdsa_only`?[]:[`ed25519`];let t=new Set((e.canonicalEcdsaContext?.ecdsaKeys||[]).map(e=>e.targetKey));if(t.size===0)throw Error(`[login] threshold ECDSA warm-up missing canonical key identity`);let n=e.configuredEcdsaTargets.map(e=>H(e.chainTarget)).filter(e=>!t.has(e));if(n.length)throw Error(`[login] threshold ECDSA warm-up missing configured-target key ids for ${n.join(`, `)}`);return e.selection.mode===`ecdsa_only`?[`ecdsa`]:[`ed25519`,`ecdsa`]}function rC(e){let t=Wy({context:e.storedCanonicalEcdsaContext,configuredTargets:e.selectedEcdsaTargets}),n=Gy({completion:t,source:`stored ECDSA key facts`}),r=nC({selection:e.selection,configuredEcdsaTargets:e.selectedEcdsaTargets,canonicalEcdsaContext:n});e.wantsEd25519Warmup&&!r.includes(`ed25519`)&&(r=[`ed25519`,...r]);let i=r.includes(`ed25519`)&&r.includes(`ecdsa`);if(!r.length)throw Error(`[login] ECDSA unlock requested with no configured ECDSA targets`);return{kind:`threshold_login_warmup_plan_ready`,storedCanonicalEcdsaContext:e.storedCanonicalEcdsaContext,configuredTargetKeyCompletion:t,ecdsaContext:n,signersToWarm:r,ed25519DependsOnEcdsa:!1,ecdsaDependsOnEd25519:i}}function iC(e){return ve(e,32,`threshold login warm session IDs`)}function aC(e){let t=l(e);if(!t.ok)throw Error(`[login] failed to create threshold ECDSA session identity`);return t.value}function oC(e){let t=wt(e);if(!t.ok)throw Error(`[login] failed to create Wallet Session mint identity`);return t.value}function sC(e){if(e==null||e<=0)throw Error(`[login] unlock warm-up requires positive unlock session uses`);return e}function cC(e){let t=Error(`[login] device_link_required: local threshold ECDSA material is unavailable for ${e}`);return t.code=`device_link_required`,t}function lC(){let e=Error(`[login] device_link_required: local threshold Ed25519 material is unavailable`);return e.code=`device_link_required`,e}function uC(e){let t=String(e.sharedState.generatedThresholdSessionId||``).trim();if(t)return t;let n=iC(`threshold-ecdsa-login`);return e.sharedState.generatedThresholdSessionId=n,n}async function dC(e){if(!e.collectCredential)throw Error(`[login] WebAuthn ECDSA key-facts inventory requires a credential collector`);let t=Yy(),n=await $i({walletId:e.walletId,rpId:e.rpId,keyTargets:e.keyTargets,serverNonceB64u:t,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{}}),r=await e.collectCredential(n);return await bo({relayerUrl:e.relayerUrl,walletId:e.walletId,rpId:e.rpId,credential:r,keyTargets:e.keyTargets,serverNonceB64u:t,expectedChallengeDigestB64u:n,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{}})}async function fC(e){let t=String(e.relayerUrl||``).trim(),n=String(e.rpId||``).trim();if(!t||!n)throw Error(`[login] threshold ECDSA key-facts inventory requires relayerUrl and rpId`);return e.authority?.kind===`wallet_session_operation_credential_v1`?await _o({relayerUrl:t,walletId:e.walletId,rpId:n,operationCredential:e.authority.operationCredential,keyTargets:e.keyTargets}):await dC({walletId:e.walletId,relayerUrl:t,rpId:n,keyTargets:e.keyTargets,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},collectCredential:e.collectWebAuthnInventoryCredential})}function pC(e){let t=zy({walletId:e.walletId,configuredTargets:e.configuredTargets,signer:e.signer});switch(t.kind){case`active_ecdsa_signer_record`:return t.targetKey===H(e.record.walletKey.chainTarget)&&String(t.walletKey.keyHandle)===String(e.record.walletKey.keyHandle);case`key_facts_inventory_required`:return t.targetKey===H(e.record.walletKey.chainTarget)&&t.keyHandle===String(e.record.walletKey.keyHandle);case`blocked`:case`skipped`:return!1}return!1}function mC(e){let t=e.record.walletKey,n=t.keyFacts,r=H(t.chainTarget);return{...e.signer.metadata||{},accountModel:`threshold-ecdsa`,accountAddress:e.record.accountAddress,ownerAddress:e.record.ownerAddress,thresholdOwnerAddress:n.thresholdOwnerAddress,keyScope:n.keyScope,keyHandle:t.keyHandle,walletId:t.walletId,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,publicCapability:e.record.publicCapability,thresholdEcdsaPublicKeyB64u:n.thresholdEcdsaPublicKeyB64u,participantIds:[...n.participantIds],chainTarget:t.chainTarget,targetMembership:{targetKey:r,chainTarget:t.chainTarget},sharedEvmFamilyKey:{walletId:t.walletId,keyScope:n.keyScope,keyHandle:t.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,participantIds:[...n.participantIds],thresholdOwnerAddress:n.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:n.thresholdEcdsaPublicKeyB64u},chainId:t.chainTarget.chainId}}async function hC(e){for(let t of e.records){let n=e.walletSigners.filter(n=>pC({walletId:e.walletId,configuredTargets:e.configuredTargets,signer:n,record:t}));if(n.length!==1)throw Error(`[login] authenticated ECDSA key inventory could not identify one profile signer for ${H(t.walletKey.chainTarget)}`);let r=n[0];if(String(t.walletKey.walletId)!==String(e.walletId)||t.accountAddress!==r.accountAddress||t.ownerAddress!==r.accountAddress||String(t.walletKey.keyFacts.thresholdOwnerAddress)!==r.accountAddress)throw Error(`[login] authenticated ECDSA key inventory profile identity mismatch for ${H(t.walletKey.chainTarget)}`);await e.store.activateAccountSigner({account:{profileId:r.profileId,chainIdKey:r.chainIdKey,accountAddress:r.accountAddress,accountModel:`threshold-ecdsa`},signer:{signerId:r.signerId,signerType:r.signerType,signerKind:r.signerKind,signerAuthMethod:r.signerAuthMethod,signerSource:r.signerSource,metadata:mC({signer:r,record:t})},activationPolicy:{mode:`allocate_next_free`},preferredSlot:r.signerSlot,selectAsActive:!1,mutation:{routeThroughOutbox:!1}})}}function gC(e,t){return t?{ecdsaKeys:e,runtimePolicyScope:t}:{ecdsaKeys:e}}function _C(e){let t=e.input?.keyFactsInventoryAuthority||null,n=e.input?.keyFactsInventoryRequested===!0,r=e.input?.relayerUrl||``,i=e.input?.rpId||``,a=e.input?.collectWebAuthnInventoryCredential;return e.runtimePolicyScope?{kind:`runtime_policy_scoped`,keyFactsInventoryAuthority:t,keyFactsInventoryRequested:n,relayerUrl:r,rpId:i,runtimePolicyScope:e.runtimePolicyScope,collectWebAuthnInventoryCredential:a}:{kind:`runtime_policy_unscoped`,keyFactsInventoryAuthority:t,keyFactsInventoryRequested:n,relayerUrl:r,rpId:i,collectWebAuthnInventoryCredential:a}}async function vC(e,t,n){let r=t.map(e=>e.chainTarget),i=await K.listAccountSignersByProfile({profileId:String(e),status:`active`}).catch(()=>[]),a=[],o=[],s=[];for(let t of i){let n=zy({walletId:e,configuredTargets:r,signer:t});switch(n.kind){case`active_ecdsa_signer_record`:a.push(n);break;case`key_facts_inventory_required`:o.push(n);break;case`blocked`:s.push(n);break;case`skipped`:break;default:}}if(!a.length&&!o.length&&!s.length)return[];let c=qy({selection:{mode:`ecdsa_only`,ecdsa:!0},configuredTargets:r,activeSignerRecords:a,keyFactsInventoryRequiredRecords:o,blockedRecords:s,runtimeConfig:{explicitKeyFactsInventoryMode:n?.keyFactsInventoryRequested===!0,allowAuthenticatedKeyFactsInventory:!!n?.keyFactsInventoryAuthority}});switch(c.kind){case`ready`:{let t=c.readyTargets.filter(e=>e.publicCapability.kind===`missing_public_capability`),a=new Map,o=[];if(t.length){let r=await fC({walletId:e,relayerUrl:n?.relayerUrl||``,rpId:n?.rpId||``,keyTargets:t.map(e=>({keyHandle:e.walletKey.keyHandle,chainTarget:e.chainTarget})),authority:n?.keyFactsInventoryAuthority||null,...n?.runtimePolicyScope?{runtimePolicyScope:n.runtimePolicyScope}:{},collectWebAuthnInventoryCredential:n?.collectWebAuthnInventoryCredential});o=r.records;for(let e of r.records)a.set(H(e.walletKey.chainTarget),e.publicCapability)}let s=Hy({source:`profile continuity`,keys:c.readyTargets.map(e=>Vy({chainTarget:e.chainTarget,keyHandle:e.walletKey.keyHandle,key:Ia(e.walletKey),publicCapability:e.publicCapability.kind===`persisted_public_capability`?e.publicCapability.value:a.get(e.targetKey)}))}),l=s.filter(e=>e.publicCapability.kind===`missing_public_capability`).map(e=>e.targetKey);if(l.length)throw Error(`[login] authenticated ECDSA key inventory did not return public capabilities for ${l.join(`, `)}`);return await hC({store:K,walletId:e,configuredTargets:r,walletSigners:i,records:o}),s}case`no_configured_ecdsa_targets`:return[];case`awaiting_authenticated_key_facts_inventory`:{let a=n?.keyFactsInventoryAuthority;if(!a)throw Error(`[login] threshold ECDSA key-facts inventory requires authenticated inventory authority`);let o=await fC({walletId:e,relayerUrl:n.relayerUrl,rpId:n.rpId,keyTargets:c.keyTargets,authority:a,...n.runtimePolicyScope?{runtimePolicyScope:n.runtimePolicyScope}:{},collectWebAuthnInventoryCredential:n.collectWebAuthnInventoryCredential}),s=Wy({context:{ecdsaKeys:Hy({source:`profile continuity inventory`,keys:o.records.map(e=>Vy({chainTarget:e.walletKey.chainTarget,keyHandle:e.walletKey.keyHandle,key:Ia(e.walletKey),publicCapability:e.publicCapability}))})},configuredTargets:t});if(s.kind!==`complete_configured_target_keys`)throw Error(`[login] threshold ECDSA key-facts inventory returned incomplete key facts`);return await hC({store:K,walletId:e,configuredTargets:r,walletSigners:i,records:o.records}),s.context.ecdsaKeys}case`key_facts_inventory_required`:{let e=c.keyFactsInventoryRequiredRecords.map(e=>e.targetKey).join(`, `);throw n?.keyFactsInventoryRequested?Error(`[login] threshold ECDSA key-facts inventory requires authenticated inventory authority for ${e}`):Error(`[login] threshold ECDSA warm-up requires complete local key facts for ${e}; run explicit authenticated ECDSA key-facts inventory before unlock`)}case`blocked`:{let e=c.blockedRecords.map(e=>`${e.targetKey||`unknown`}:${e.reason}`).join(`, `);throw Error(`[login] threshold ECDSA warm-up requires complete local key facts before unlock; run explicit authenticated ECDSA key-facts inventory before unlock; blocked profile signer records: ${e}`)}}return[]}async function yC(e,t,n,r){let i=jo(e.configs.network.chains),a=gC(Hy({source:`stored`,keys:[]}),void 0),o=await cy({walletId:t,chainTargets:i.map(e=>e.chainTarget),...r?{authMethod:r}:{}}),s=[],c;for(let e of o){let t=e.manifest;for(let{chainTarget:n}of i){if(!t.signer.scope.targetMemberships.some(e=>H(e)===H(n)))continue;let r=t.durableMaterial.roleLocalPublicFacts,i=String(r.keyHandle),a=r.publicCapability,o=e.material,l=t.durableMaterial.runtimePolicyScope,u=Ca({runtimePolicyScope:l});if(String(u.signingRootId)!==String(t.signer.signingRootId)||String(u.signingRootVersion)!==String(t.signer.signingRootVersion))throw Error(`[login] threshold ECDSA canonical runtime policy scope mismatch for ${H(n)}`);if(c&&l&&!kS(c,l))throw Error(`[login] threshold ECDSA durable lanes have conflicting runtime policy scopes`);!c&&l&&(c=l),s.push(Vy({chainTarget:n,keyHandle:i,key:Pa({walletId:t.signer.walletId,ecdsaThresholdKeyId:t.durableMaterial.roleLocalBinding.ecdsaThresholdKeyId,signingRootId:t.signer.signingRootId,signingRootVersion:t.signer.signingRootVersion,participantIds:t.signer.registeredPublicFacts.participantIds,thresholdOwnerAddress:t.signer.registeredPublicFacts.thresholdOwnerAddress}),publicCapability:a,existingRoleLocalMaterial:o}))}}let l=Hy({source:`available lane`,keys:s});a=AS({current:a,incoming:gC(l,c),source:`durable lanes`});let u=Wy({context:a,configuredTargets:i});if(u.kind===`complete_configured_target_keys`)return u.context;let d=new Set(u.missingTargets),f=await vC(t,i.filter(e=>d.has(H(e.chainTarget))),_C({input:n,runtimePolicyScope:a.runtimePolicyScope}));return a=AS({current:a,incoming:{ecdsaKeys:f},source:`profile continuity`}),a}async function bC(e,t){let n=[...new Set((await eC(e,t)).map(e=>String(e.keyFacts.thresholdEcdsaPublicKeyB64u||``).trim()).filter(Boolean))];return n.length===1?n[0]:(n.length>1&&console.warn(`[WalletSession] conflicting profile threshold ECDSA public keys`,{walletId:String(t),publicKeyCount:n.length}),null)}async function xC(e,t){let[n,r]=await Promise.all([tC(e,t),bC(e,t)]);if(n&&r)return{ethereumAddress:n,thresholdEcdsaPublicKeyB64u:r};let i=await cy({walletId:t,chainTargets:jo(e.configs.network.chains).map(e=>e.chainTarget)}),a=new Set,o=new Set;for(let e of i){let t=e.manifest.signer.registeredPublicFacts;a.add($S(t.thresholdOwnerAddress)),o.add(t.publicKeyB64u)}return{ethereumAddress:n??(a.size===1?[...a][0]:null),thresholdEcdsaPublicKeyB64u:r??(o.size===1?[...o][0]:null)}}function SC(e){return{kind:`failed`,reason:e}}function CC(){return{kind:`failed`,reason:`persistence_unavailable`}}function wC(e){switch(e.state){case`ready`:return{kind:`ready`};case`restorable`:return{kind:`pending`,resume:`restore_material`};case`deferred`:return{kind:`pending`,resume:`resolve_deferred_state`};case`expired`:return{kind:`authorization_required`,requirement:`wallet_session_expired`};case`exhausted`:return{kind:`authorization_required`,requirement:`wallet_session_exhausted`}}throw Error(`[SeamsWeb] unsupported capability lane readiness`)}function TC(e,t){let n=e.diagnostics?.invalidLanes.find(e=>e.curve===t);return n?n.reason===`ambiguous_material`||n.reason===`conflicting_key_material`?`ambiguous_lane`:`malformed`:null}function EC(e,t){let n=H(t),r=e.diagnostics?.invalidLanes.find(e=>e.curve===`ecdsa`&&(e.targetKey===void 0||e.targetKey===n));return r?r.reason===`ambiguous_material`||r.reason===`conflicting_key_material`?`ambiguous_lane`:`malformed`:null}function DC(e,t){return String(t.walletId)===String(e.walletId)&&String(t.nearAccountId)===String(e.nearAccountId)&&String(t.nearEd25519SigningKeyId)===String(e.nearEd25519SigningKeyId)&&t.signerSlot===e.signerSlot}function OC(e,t){return String(t.key.walletId)===String(e.walletId)&&String(t.key.ecdsaThresholdKeyId)===String(e.ecdsaThresholdKeyId)}function kC(e){if(e.availableLanes.kind===`unavailable`)return{kind:`near_ed25519`,subject:e.subject,lane:CC()};let t=e.availableLanes.lanes;if(String(t.walletId)!==String(e.subject.walletId))return{kind:`near_ed25519`,subject:e.subject,lane:SC(`identity_mismatch`)};let n=TC(t,`ed25519`);if(n)return{kind:`near_ed25519`,subject:e.subject,lane:SC(n)};let r=t.lanes.ed25519.near;return Jd(r)?{kind:`near_ed25519`,subject:e.subject,lane:DC(e.subject,r)?wC(r):SC(`identity_mismatch`)}:{kind:`near_ed25519`,subject:e.subject,lane:SC(`missing`)}}function AC(e){if(e.availableLanes.kind===`unavailable`)return CC();let t=e.availableLanes.lanes;if(String(t.walletId)!==String(e.subject.walletId))return SC(`identity_mismatch`);let n=EC(t,e.chainTarget);if(n)return SC(n);let r=ef(t,e.chainTarget);return Jd(r)?OC(e.subject,r)?r.source===`canonical_capability`&&!r.authorization?{kind:`authorization_required`,requirement:`same_method_step_up`}:wC(r):SC(`identity_mismatch`):SC(`missing`)}function jC(e){let[t,...n]=e.configuredTargets;return t?{kind:`evm_family_ecdsa`,subject:e.subject,targets:{kind:`configured_targets`,lanes:[{chainTarget:t,readiness:AC({subject:e.subject,availableLanes:e.availableLanes,chainTarget:t})},...n.map(t=>({chainTarget:t,readiness:AC({subject:e.subject,availableLanes:e.availableLanes,chainTarget:t})}))]}}:{kind:`evm_family_ecdsa`,subject:e.subject,targets:{kind:`no_configured_target`}}}function MC(e){let t=e.subjectSet.subjects.map(t=>{switch(t.kind){case`near_ed25519_wallet`:return kC({subject:t,availableLanes:e.availableLanes});case`evm_family_ecdsa_wallet`:return jC({subject:t,availableLanes:e.availableLanes,configuredTargets:e.configuredEcdsaTargets})}return Q(t)}),n=t[0];if(!n)throw Error(`[WalletSession] resolved capability subjects must be non-empty`);return{kind:`resolved`,subjectSet:e.subjectSet,capabilities:[n,...t.slice(1)]}}function NC(e){return e?e.operationalPublicKey:null}function PC(e,t){return!!(e&&String(e.walletId)===String(t.walletId)&&String(e.nearAccountId)===String(t.nearAccountId)&&e.signerSlot===t.signerSlot)}async function FC(e,t){let n=await e.getLastUser().catch(()=>null);if(PC(n,t))return n;let r=await Ac(K,t.nearAccountId,t.signerSlot).catch(()=>null);if(PC(r,t))return r;let i=await e.getUserBySignerSlot(t.nearAccountId,t.signerSlot).catch(()=>null);return PC(i,t)?i:null}function IC(e,t){return e.walletId===t.walletId&&e.nearAccountId===t.nearAccountId&&e.nearEd25519SigningKeyId===t.nearEd25519SigningKeyId&&e.signerSlot===t.signerSlot}async function LC(e){let t=_(String(e.walletId));if(!t.ok)return null;let n=t.value,r;try{r=await K.resolveSelectedWalletAuthority(String(n))}catch{return null}if(r.kind!==`resolved`)return null;let{selection:i,authMethod:a,authority:o}=r;if(Rb({walletId:n,selection:i,authMethod:a,authority:o}).length>0||a.status!==`active`||o.state!==`active`||o.provenance.kind!==`device_link`)return null;let s=await Nx({walletId:n,authMethod:a,authority:o,signerMaterials:r.signerMaterials});if(s.kind!==`resolved`||!IC(s.subject,e))return null;let c=o.signerActivations.ed25519;return c?`ed25519:${tn(F(c.signer.registeredPublicKeyB64u))}`:null}async function RC(e,t){let[n,r]=await Promise.all([Qb(t),xC(e,t).catch(()=>({ethereumAddress:null,thresholdEcdsaPublicKeyB64u:null}))]);return{kind:`resolved`,walletId:t,nearAccountId:null,nearOperationalPublicKey:null,userData:null,authMethods:n,thresholdEcdsaEthereumAddress:r.ethereumAddress,thresholdEcdsaPublicKeyB64u:r.thresholdEcdsaPublicKeyB64u}}async function zC(e,t){let n=t.walletId,r=wb(t.subjectSet),i=r?.nearAccountId||null,[a,o]=await Promise.all([r?FC(e.signingEngine,r):null,RC(e,n)]),s=NC(a)||(r?await LC(r):null);return{...o,nearAccountId:i,nearOperationalPublicKey:s,userData:a}}async function BC(e){let[t,n,r]=await Promise.all([e.signingEngine.getAllUsers(),K.listWalletSelections(),e.signingEngine.getLastUser()]),i=(await Promise.all(n.map(Yb))).filter(e=>e!==null),a=new Map;for(let e of t){let t=Jb(e);a.set(Xb(t),t)}for(let e of i)a.set(Xb(e),e);let o=[...a.values()],s=[...new Set([...o.map(e=>e.walletId),...n.map(e=>String(e.walletId))])],c=[...new Set(o.map(e=>e.nearAccountId))],l=r?Jb(r):null;return{walletIds:s,accountIds:c,accounts:o,lastUsedAccount:Zb([...i,...l?[l]:[]])}}function VC(e){if(e.record.status!==`active`)return null;switch(e.kind){case`passkey`:return{walletId:e.record.walletId,authMethod:`passkey`};case`email_otp`:{let t=e.presentation.email.kind===`verified`?String(e.presentation.email.address):null;return{walletId:e.record.walletId,authMethod:`email_otp`,emailAddress:t}}case`voiceid`:return null;default:return Q(e)}}function HC(e){let t=[];for(let n of e){let e=VC(n);e&&t.push(e)}return t}async function UC(e){return HC(await GC(e,await K.listLocalWalletAuthMethodProjectionsV2ForWallet(e)))}function WC(e){return e.kind===`email_otp`&&e.record.status===`active`&&e.presentation.email.kind===`unavailable`}async function GC(e,t){let n=[];for(let e of t)WC(e)&&n.push(e);if(n.length===0)return[...t];let r=u(await na(K,e));if(!r.ok)return[...t];let i=!1;for(let t of n){let n=await K.retainVerifiedEmailOtpLocalPresentation({walletId:e,walletAuthMethodId:t.record.walletAuthMethodId,emailAddress:r.value});switch(n.kind){case`retained`:i=!0;break;case`not_retained`:break;default:Q(n)}}return i?await K.listLocalWalletAuthMethodProjectionsV2ForWallet(e):[...t]}async function KC(){let e=await K.listWalletSelectionWalletIds();return(await Promise.all([...new Set(e)].map(UC))).flat()}async function qC(e){let{signingEngine:t}=e,n=t.readWalletAuthenticationState(),r,i=!1,a=!1,o=[];try{o=n.kind===`authenticated`?[n.walletId]:await K.listWalletSelectionWalletIds()}catch(e){r=e,i=!0}for(let e of o){try{await t.advanceWalletLockGeneration(e)}catch(e){r=e,i=!0}try{await t.retireActiveWalletSessionAuthorizationForLock(e)}catch(e){i||=(r=e,!0)}}try{a=t.clearWalletAuthenticationIfCurrent(n)}catch(e){i||=(r=e,!0)}if(a){try{t.getNonceCoordinator().clearAll()}catch{}try{t.clearThresholdEcdsaSigningQueue()}catch{}}try{await t.clearVolatileWarmSigningMaterial(n.kind===`authenticated`?n.walletId:void 0)}catch(e){i||=(r=e,!0)}if(i)throw r}async function JC(e){try{await(await import(`./registration-C7w_51wE.js`).then(e=>e.o)).resumeNearRegistrationAfterUnlock(e)}catch(e){console.warn(`[login] NEAR continuation could not start`,e instanceof Error?e.message:`module unavailable`)}finally{new Uint8Array(e.ownedFactorSecret).fill(0)}}function YC(e,t,n){try{e?.(Xi({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function XC(e){let t=Cn(B(e.nearAccountId));return{walletSession:En(e.walletSession),nearAccount:t}}function ZC(e){let t=e.transaction,n=String(t.signerId||``).trim();if(!n)throw Error(`Signed transaction is missing signerId`);return n}function QC(e){let t=ZC(e.signedTransaction);if(t!==String(e.nearAccountId))throw Error(`Signed transaction signerId ${t} does not match NEAR account ${String(e.nearAccountId)}`)}function $C(e){if(!(e.serverDispatch||e.nonceLease))throw Error(`near.sendTransaction requires an SDK-produced signed transaction with nonce readiness`)}function ew(e){let t=String(e||``).trim();if(!t)throw Error(`NEAR broadcast response is missing transaction hash`);return t}function tw(e){return!e.signedTransaction.serverDispatch&&!e.signedTransaction.nonceLease&&e.signingResult.nonceLease&&(e.signedTransaction.nonceLease=e.signingResult.nonceLease),e.signedTransaction}async function nw(){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){await new Promise(e=>{window.requestAnimationFrame(()=>e())});return}await Promise.resolve()}async function rw(e){return sw({context:e.context,nearAccountId:e.nearAccountId,walletSession:e.walletSession,transactionInput:e.transactionInput,options:e.options,confirmationConfigOverride:e.options.confirmationConfig})}async function iw(e){try{return cw({context:e.context,nearAccountId:e.nearAccountId,walletSession:e.walletSession,transactionInput:e.transactionInput,options:e.options,confirmationConfigOverride:e.options.confirmationConfig})}catch(e){throw I(e)}}async function aw({context:e,nearAccountId:t,walletSession:n,signedTransaction:r,options:i}){let a=r.nonceLease,o={kind:`not_started`},s,c;try{let l=XC({nearAccountId:t,walletSession:n}).nearAccount.accountId;if(QC({signedTransaction:r,nearAccountId:l}),$C(r),YC(i?.onEvent,l,{phase:W.STEP_12_BROADCAST_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}}),r.serverDispatch){if(o={kind:`dispatching`},s=r.serverDispatch.rpcResult,c=ew(r.serverDispatch.transactionHash),c!==r.transactionHash)throw Error(`NEAR dispatch returned a different transaction hash`);return o={kind:`accepted`,transactionId:c},a&&(await e.signingEngine.getNonceCoordinator().markBroadcastAccepted({leaseId:a.leaseId,operationId:a.operationId,operationFingerprint:a.operationFingerprint,txHash:c}),await e.signingEngine.getNonceCoordinator().markFinalized({leaseId:a.leaseId,operationId:a.operationId,operationFingerprint:a.operationFingerprint,txHash:c})),YC(i?.onEvent,l,{phase:W.STEP_12_BROADCAST_ACCEPTED,status:`succeeded`,message:`Transaction ${c} sent successfully`,interaction:{kind:`none`,overlay:`none`},data:{txId:c}}),YC(i?.onEvent,l,{phase:W.STEP_15_COMPLETED,status:`succeeded`,message:`Transaction ${c} completed`,interaction:{kind:`none`,overlay:`none`},data:{txId:c}}),{success:!0,transactionId:c,result:s}}if(o={kind:`dispatching`},s=await e.nearClient.sendTransaction(r,i?.waitUntil),c=ew(s.transaction.hash),c!==r.transactionHash)throw Error(`NEAR RPC returned a different transaction hash`);o={kind:`accepted`,transactionId:c},a&&(await e.signingEngine.getNonceCoordinator().markBroadcastAccepted({leaseId:a.leaseId,operationId:a.operationId,operationFingerprint:a.operationFingerprint,txHash:c}),await e.signingEngine.getNonceCoordinator().markFinalized({leaseId:a.leaseId,operationId:a.operationId,operationFingerprint:a.operationFingerprint,...c?{txHash:c}:{}})),YC(i?.onEvent,l,{phase:W.STEP_12_BROADCAST_ACCEPTED,status:`succeeded`,message:`Transaction ${c} sent successfully`,interaction:{kind:`none`,overlay:`none`},...c?{data:{txId:c}}:{}}),YC(i?.onEvent,l,{phase:W.STEP_15_COMPLETED,status:`succeeded`,message:`Transaction ${c} completed`,interaction:{kind:`none`,overlay:`none`},...c?{data:{txId:c}}:{}})}catch(e){let n=I(e);console.error(`[sendTransaction] failed:`,n);let a=n.details;switch(a&&console.error(`[sendTransaction] RPC error details:`,a),YC(i?.onEvent,t,{phase:W.FAILED,status:`failed`,interaction:{kind:`none`,overlay:`hide`},error:{message:n.message}}),o.kind){case`not_started`:return ft(n,`not_submitted`);case`dispatching`:return gt(r.transactionHash,n);case`accepted`:return gt(o.transactionId,n);default:return ow(o)}}return{success:!0,transactionId:c,result:s}}function ow(e){throw Error(`Unsupported NEAR submission state: ${String(e)}`)}async function sw({context:e,nearAccountId:t,walletSession:n,transactionInput:r,options:i,confirmationConfigOverride:a}){try{let o=await cw({context:e,nearAccountId:t,walletSession:n,transactionInput:r,options:i,confirmationConfigOverride:a});return await aw({context:e,nearAccountId:t,walletSession:n,signedTransaction:tw({signedTransaction:o.signedTransaction,signingResult:o}),options:{onEvent:i?.onEvent,waitUntil:i?.waitUntil}})}catch(e){let n=I(e),r=n.short||en(n)||n.message;return YC(i?.onEvent,t,{phase:W.FAILED,status:`failed`,message:`Action failed: ${r}`,interaction:{kind:`none`,overlay:`hide`},error:{message:r}}),ft(n,`not_submitted`)}}async function cw({context:e,nearAccountId:t,walletSession:n,transactionInput:r,options:i,confirmationConfigOverride:a}){let{onEvent:o,onError:s,waitUntil:c,confirmerText:l,signerSlot:u}=i||{};try{YC(o,t,{phase:W.STEP_01_STARTED,status:`started`,message:`Starting ${r.actions[0].type} action`,interaction:{kind:`none`,overlay:`none`}}),await lw(t,[r],{onEvent:o,onError:s,waitUntil:c}),await nw();let i={receiverId:r.receiverId,actions:r.actions.map(e=>an(e))},d=await e.signingEngine.signNear({chain:`near`,kind:`transactionWithActions`,args:{commandSubject:XC({nearAccountId:t,walletSession:n}),transaction:i,rpcCall:{nearRpcUrl:Ke(e.configs.network.chains),nearAccountId:t},signerSlot:u,confirmationConfigOverride:a,title:l?.title,body:l?.body,onEvent:o}});if(!d?.signedTransaction)throw Error(`NEAR signing returned no signed transaction`);return d}catch(e){console.error(`[signTransaction] Error during execution:`,e);let n=I(e),r=n.short||en(n)||n.message;throw s?.(n),YC(o,t,{phase:W.FAILED,status:`failed`,message:`Action failed: ${r}`,interaction:{kind:`none`,overlay:`hide`},error:{message:r}}),n}}async function lw(e,t,n){let{onEvent:r}=n||{};if(!e)throw Error(`User not logged in or NEAR account ID not set for direct action.`);if(YC(r,e,{phase:W.STEP_02_REQUEST_PREPARED,status:`running`,message:`Validating inputs`,interaction:{kind:`none`,overlay:`none`}}),t.length===0)throw Error(`No payloads provided for signing`);if(t.length!==1)throw Error(`NEAR signing supports exactly one transaction per operation; received ${t.length}`);for(let e of t){if(!e.receiverId)throw Error(`Missing required parameter: receiverId`);for(let t of e.actions){if(t.type===on.FunctionCall&&(!t.methodName||t.args===void 0))throw Error(`Missing required parameters for function call: methodName or args`);if(t.type===on.Transfer&&!t.amount)throw Error(`Missing required parameter for transfer: amount`)}}}async function uw(e,t,n,r,i){let a;try{a=await e.captureConnection(t.authentication),n()}catch(e){return Yl(e)?{kind:`cancelled`}:{kind:`failed`,error:Lt(e)}}let o=e.getContext(),s=globalThis.navigator.locks;if(!s)return{kind:`failed`,error:`This browser cannot coordinate owner operations.`};let c=await j(ne({walletId:t.authentication.walletId,associationId:t.authentication.associationId,environmentId:t.authentication.environmentId,nearAccountId:t.recovery.nearAccountId,parentOrigin:e.parentOrigin,nearRpcUrl:Ke(o.configs.network.chains)})),l=new dw(o,t,c,a,n,r,i);return await s.request(`seams:owner-near:${c}`,l.run.bind(l))}var dw=class{key;pendingKey;broadcastContext;submission=`not_started`;constructor(e,t,n,r,i,a,o){this.context=e,this.command=t,this.binding=n,this.assertConnection=r,this.assertActive=i,this.onEvent=a,this.onSubmission=o,this.broadcastContext={signingEngine:e.signingEngine,configs:e.configs,theme:e.theme,nearClient:new df(Ke(e.configs.network.chains))},this.key=`owner-near:${t.recovery.operationId}`,this.pendingKey=`owner-near-pending:${n}`}assertCurrent(){if(this.assertActive(),this.assertConnection(),this.command.action===`approve`&&this.command.expiresAtMs<=Date.now())throw new pw}async run(){try{return await this.execute()}catch(e){return this.submission===`dispatched`?this.unknown():e instanceof pw?{kind:`expired`}:Yl(e)?{kind:`cancelled`}:{kind:`failed`,error:Lt(e)}}}async execute(){this.assertCurrent();let e=await K.getAppState(this.key),t=e===void 0?null:fw(e);if(t&&t.binding!==this.binding)throw Error(`The owner operation belongs to another connection.`);if(this.command.action===`recover`)return await this.recover(t);let n=await this.readPending();if(n&&n.operationId!==this.command.recovery.operationId)return{kind:`unknown`,recovery:n};let r=this.command;if(r.expiresAtMs>Date.now()+12e4)throw Error(`The owner operation deadline is too long.`);let i=await j(ne(r.transaction));if(t){if(t.requestDigest!==i)throw Error(`The owner operation contents changed.`);return await this.recover(t)}await this.store({kind:`approving`,binding:this.binding,requestDigest:i});let a;try{let e=await this.context.signingEngine.signNearOwnerTransaction(r,this.assertCurrent.bind(this),this.onEvent);this.assertCurrent(),await K.setAppState(this.pendingKey,{kind:`pending`,recovery:r.recovery}),await this.store({kind:`submitting`,binding:this.binding,requestDigest:i,transactionId:e.signedTransaction.transactionHash}),this.assertCurrent(),this.submission=`dispatched`;try{this.onSubmission()}catch{}let t=await aw({context:this.broadcastContext,walletSession:{walletId:V(r.authentication.walletId),walletSessionUserId:String(r.authentication.walletId)},nearAccountId:Cn(r.recovery.nearAccountId).accountId,signedTransaction:e.signedTransaction,options:{onEvent:this.onEvent}});if(t.success)a={kind:`completed`,result:t};else{if(t.kind!==`not_submitted`)return this.unknown();a={kind:`failed`,error:t.error}}}catch(e){if(this.submission===`dispatched`)return this.unknown();a=e instanceof pw?{kind:`expired`}:Yl(e)?{kind:`cancelled`}:{kind:`failed`,error:Lt(e)||`The owner operation failed.`}}return await this.store({kind:`settled`,binding:this.binding,requestDigest:i,outcome:a}),await this.clearPending(),a}unknown(){return{kind:`unknown`,recovery:this.command.recovery}}async recover(e){if(!e||e.kind===`approving`)return await this.clearPending(),{kind:`failed`,error:`This operation did not reach broadcast. Prepare a new operation for another approval.`};if(e.kind===`settled`)return await this.clearPending(),e.outcome;try{let t=await this.context.nearClient.txStatus(e.transactionId,String(this.command.recovery.nearAccountId));if(t.transaction.hash!==e.transactionId)throw Error(`Transaction recovery identity mismatch.`);if(t.final_execution_status!==`FINAL`||typeof t.status!=`object`)return this.unknown();let n=`Failure`in t.status?{kind:`reverted`,transactionId:e.transactionId,error:`The transaction failed on NEAR.`}:{kind:`completed`,result:{success:!0,transactionId:e.transactionId,result:t}};return await this.store({kind:`settled`,binding:e.binding,requestDigest:e.requestDigest,outcome:n}),await this.clearPending(),n}catch{return this.unknown()}}async store(e){await K.setAppState(this.key,e)}async readPending(){let e=await K.getAppState(this.pendingKey);if(e===void 0)return null;let t=E(e,`pending owner transaction`);if(t.kind===`clear`)return null;if(t.kind!==`pending`)throw Error(`Invalid pending owner transaction.`);return _t(t.recovery)}async clearPending(){(await this.readPending())?.operationId===this.command.recovery.operationId&&await K.setAppState(this.pendingKey,{kind:`clear`})}};function fw(e){let t=E(e,`owner transaction receipt`),n=D(t.binding,`binding`),r=D(t.requestDigest,`requestDigest`);switch(t.kind){case`approving`:return{kind:`approving`,binding:n,requestDigest:r};case`submitting`:return{kind:`submitting`,binding:n,requestDigest:r,transactionId:D(t.transactionId,`transactionId`)};case`settled`:return{kind:`settled`,binding:n,requestDigest:r,outcome:ht(t.outcome)};default:throw Error(`Invalid owner transaction receipt.`)}}var pw=class extends Error{constructor(){super(`The owner operation expired.`)}};let mw=null,hw=null;function gw(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function _w(e,t){let n=e[t];if(typeof n!=`string`||n.length===0||n.trim()!==n)throw Error(`${t} must be a non-empty canonical string`);return n}function vw(e,t,n){if(Object.keys(e).length!==t.size)throw Error(`${n} fields are invalid`);for(let r of t)if(!Object.hasOwn(e,r))throw Error(`Missing ${n} field: ${r}`)}function yw(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a canonical HTTP origin`);let n;try{n=new URL(e)}catch{throw Error(`${t} must be a canonical HTTP origin`)}if(n.protocol!==`https:`&&n.protocol!==`http:`||n.origin!==e||n.pathname!==`/`||n.search!==``||n.hash!==``)throw Error(`${t} must be a canonical HTTP origin`);return n.origin}function bw(e){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`relayUrl must be a non-empty canonical string`);return i(e)}function xw(e){if(!Number.isSafeInteger(e)||Number(e)<=Date.now())throw Error(`hosted-wallet Wallet Session is expired or invalid`);return Number(e)}function Sw(e,t){let n=gw(e);if(vw(n,new Set([`ok`,`code`,`message`]),`hosted-wallet exchange failure`),n.ok!==!1)throw Error(`hosted-wallet exchange failure is invalid`);let r=_w(n,`code`),i=_w(n,`message`),a=Error(i);return a.code=r,a.status=t,a}function Cw(e){if(typeof e!=`string`||!/^wsh_[A-Za-z0-9_-]{43}$/.test(e))throw Error(`hosted-wallet operationCredential.token is invalid`);return e}function ww(e){let t=Tt(e);if(!t.ok)throw Error(`walletSessionId is invalid: ${t.error.message}`);return t.value}function Tw(e){let t=gw(e);if(vw(t,new Set([`kind`,`home`,`token`,`walletSessionId`]),`hosted-wallet operationCredential`),t.kind!==`opaque_hosted_wallet_session_operation_credential_v1`)throw Error(`hosted-wallet operationCredential.kind is invalid`);return{kind:t.kind,home:He(t.home),token:Cw(t.token),walletSessionId:ww(t.walletSessionId)}}function Ew(e){let t=gw(e);if(t.ok!==!0)throw Sw(t,400);vw(t,new Set([`ok`,`walletSessionId`,`operationCredential`,`expiresAtMs`]),`hosted-wallet session redemption response`);let n=ww(t.walletSessionId),r=Tw(t.operationCredential);if(r.walletSessionId!==n)throw Error(`hosted-wallet operationCredential does not identify its parent Wallet Session`);return{operationCredential:r,expiresAtMs:xw(t.expiresAtMs)}}async function Dw(e){try{return await e.json()}catch{return null}}function Ow(e){hw=yw(e,`adopted parent origin`)}function kw(e){let t=mw;if(t){if(t.expiresAtMs<=Date.now()||t.appOrigin!==hw||t.walletOrigin!==window.location.origin||e!==void 0&&t.relayUrl!==bw(e)){mw=null;return}return t.operationCredential}}function Aw(){mw=null,hw=null}function jw(e){return JSON.stringify({exchangeCode:e.exchangeCode,nonce:e.nonce,appOrigin:e.appOrigin,walletOrigin:e.walletOrigin})}async function Mw(e,t){let n=at(e),r=bw(t);if(bw(n.relayUrl)!==r)throw Error(`Hosted-wallet redemption relayUrl does not match its request boundary`);if(n.walletOrigin!==window.location.origin)throw Error(`Hosted-wallet redemption walletOrigin does not match the wallet host`);if(hw===null||n.appOrigin!==hw)throw Error(`Hosted-wallet redemption appOrigin does not match the adopted iframe parent`);let i=await fetch(c(r,`/wallet/session/exchange/redeem`),{method:`POST`,headers:{"Content-Type":`application/json`,...n.home.kind===`regional`?{"X-Seams-Wallet-Region":n.home.region}:{}},body:jw(n)}),a=await Dw(i);if(!i.ok)throw Sw(a,i.status);let o=Ew(a),s={kind:`active_hosted_wallet_seams_session`,operationCredential:o.operationCredential,expiresAtMs:o.expiresAtMs,relayUrl:r,appOrigin:n.appOrigin,walletOrigin:n.walletOrigin};return mw=s,s}async function Nw(e,t){switch(t.state){case`unavailable`:return;case`settled`:await ya(e,t.generation);return;case`moving`:await ya(e,t.move.destinationGeneration);return;case`completed`:await ya(e,t.destinationGeneration);return;default:throw Error(`Unsupported wallet placement observation`)}}async function Pw(e,t,n){let r=e.readAuthentication();if(await Nw(t,n),r.kind!==`authenticated`||r.walletId!==t)return;let i=Fw(n);if(i===null)return;let a=await K.resolveSelectedWalletAuthority(t);if(a.kind!==`resolved`)return;let o=await q.readExactWithOperationCredential({walletId:t,authorityId:a.authority.authorityId,authMethodId:a.authMethod.walletAuthMethodId});o.kind===`found`&&o.operationCredential.ownershipGeneration<i&&e.readAuthentication()===r&&await e.lockWallet()}function Fw(e){switch(e.state){case`unavailable`:return null;case`settled`:return e.generation;case`completed`:return e.destinationGeneration;case`moving`:return e.move.progress.availability===`active`?e.move.destinationGeneration:null;default:throw Error(`Unsupported wallet activation observation`)}}function Iw(e){if(!Lw(e))throw Error(`Wallet move identity is invalid`);return e}function Lw(e){return typeof e==`string`&&/^wmove_[A-Za-z0-9_-]{43}$/u.test(e)}function Rw(e){let t=E(e,`Wallet move request`),n=_(t.walletId);if(!n.ok||Object.keys(t).length!==4)throw Error(`Wallet move request is invalid`);return{walletId:n.value,moveId:Iw(t.moveId),destinationRegion:Bw(t.destinationRegion),expectedGeneration:Vw(t.expectedGeneration)}}function zw(e){let t=E(e,`Wallet placement`);switch(t.state){case`settled`:if(Object.keys(t).length!==4)break;return{state:`settled`,region:Bw(t.region),generation:Vw(t.generation),nextMoveAtMs:Re(t.nextMoveAtMs,`Next relocation time`)};case`unavailable`:if(Object.keys(t).length!==2||t.code!==`not_found`&&t.code!==`wallet_not_established`)break;return{state:`unavailable`,code:t.code};case`moving`:{if(Object.keys(t).length!==2)break;let e=E(t.move,`Wallet relocation`);if(Object.keys(e).length!==8)break;let{moveId:n,sourceRegion:r,destinationRegion:i,sourceGeneration:a,destinationGeneration:o,admittedAtMs:s}=Gw(e),c=Re(e.nextMoveAtMs,`Next relocation time`);if(c<s)break;return{state:`moving`,move:{moveId:n,sourceRegion:r,destinationRegion:i,sourceGeneration:a,destinationGeneration:o,admittedAtMs:s,nextMoveAtMs:c,progress:Hw(e.progress)}}}}throw Error(`Wallet placement response is invalid`)}function Bw(e){switch(e){case`US`:case`WEUR`:case`APAC`:case`OC`:return e;default:throw Error(`Wallet region is invalid`)}}function Vw(e){let t=Re(e,`Wallet placement generation or time`);if(t===0)throw Error(`Wallet placement generation or time must be positive`);return t}function Hw(e){let t=E(e,`Wallet relocation progress`);if(Object.keys(t).length!==3)throw Error(`Wallet relocation progress fields are invalid`);let n=Uw(t.execution);switch(t.state){case`freezing`:case`copying`:case`verified`:case`activating`:if(t.availability===`paused`)return{state:t.state,availability:`paused`,execution:n};break;case`cleanup`:if(t.availability===`active`)return{state:`cleanup`,availability:`active`,execution:n};break}throw Error(`Wallet relocation availability is invalid`)}function Uw(e){let t=E(e,`Wallet relocation execution`);switch(t.state){case`ready`:case`running`:if(Object.keys(t).length===1)return{state:t.state};break;case`retry_wait`:if(Object.keys(t).length!==3)break;if(t.code===`transport_unavailable`||t.code===`authority_unavailable`)return{state:`retry_wait`,code:t.code,retryAtMs:Vw(t.retryAtMs)};break;case`blocked`:if(Object.keys(t).length!==2)break;switch(t.code){case`transport_unavailable`:case`authority_unavailable`:case`identity_conflict`:case`receipt_conflict`:case`content_conflict`:return{state:`blocked`,code:t.code}}}throw Error(`Wallet relocation execution is invalid`)}function Ww(e,t){let n=E(e,`Wallet move status`);if(n.state===`moving`){let e=zw(n);if(e.state!==`moving`||e.move.moveId!==t)throw Error(`Wallet move identity changed`);return e}if(n.state!==`completed`||Object.keys(n).length!==8)throw Error(`Wallet move status is invalid`);let{moveId:r,sourceRegion:i,destinationRegion:a,sourceGeneration:o,destinationGeneration:s,admittedAtMs:c}=Gw(n),l=Vw(n.completedAtMs);if(r!==t||l<c)throw Error(`Wallet move completion is invalid`);return{state:`completed`,moveId:r,sourceRegion:i,destinationRegion:a,sourceGeneration:o,destinationGeneration:s,admittedAtMs:c,completedAtMs:l}}function Gw(e){let t=Iw(e.moveId),n=Bw(e.sourceRegion),r=Bw(e.destinationRegion),i=Vw(e.sourceGeneration),a=Vw(e.destinationGeneration),o=Vw(e.admittedAtMs);if(n===r||a!==i+1)throw Error(`Wallet move generations or regions are invalid`);return{moveId:t,sourceRegion:n,destinationRegion:r,sourceGeneration:i,destinationGeneration:a,admittedAtMs:o}}function Kw(e){return`wallet_move_request:${e}`}async function qw(e){let t=await K.getAppState(Kw(e));if(t===void 0)return null;let n=Rw(t);if(n.walletId!==e)throw Error(`Stored wallet move identity is invalid`);return n}async function Jw(e){await K.setAppState(Kw(e.walletId),{walletId:e.walletId,moveId:e.moveId,destinationRegion:e.destinationRegion,expectedGeneration:e.expectedGeneration})}var Yw=class extends Error{constructor(e,t){super(`Owner Router request failed: ${t}`),this.code=e,this.name=`WalletHostOwnerRequestTransportError`}};function Xw(e){let t=Qw(e);return{readOwnerCredential:Zw.bind(null,t),ownerAuthorization:{authenticateOwnerForLinkingV1:async e=>await eT(t,e)},ownerRequest:{requestOwnerV1:async e=>await tT(t,e)},managementRequest:{request:async e=>await nT(t,e)}}}async function Zw(e,t){let n=e.readWalletAuthenticationState();if(n.kind!==`authenticated`||n.walletId!==t)throw $w();return(await rT(e,t)).operationCredential}function Qw(e){let t=String(e.relayerUrl||``).trim().replace(/\/+$/,``);if(!t)throw Error(`Wallet-host device linking requires a Router URL`);return{...e,baseUrl:t}}function $w(){return new X(`wallet_unlock_required`,Z.WALLET_UNLOCK_REQUIRED,`authorization`)}async function eT(e,t){let n=e.readWalletAuthenticationState();if(n.kind!==`authenticated`)throw $w();await fs(n.walletId);let r=await rT(e,n.walletId),i=await iT(e,r,{method:`POST`,canonicalPath:`/wallet/device-linking/v1/owner-authorization`,body:qn({payload:t.payload,requestedAtMs:t.requestedAtMs})});if(i.status<200||i.status>=300)throw Error(pT(i));let a=oT(i.body,r),o=We(t.payload.requestedPermission,`export_keys`)&&a.sourceSignerManifest.keyFamilies.some(e=>e===`ed25519`),s=o?e.readUnlockedEd25519ExportRootCapabilityV1(n.walletId):void 0;if(o&&(!s||s.walletId!==String(n.walletId)||s.walletSessionId!==String(r.operationCredential.walletSessionId)||s.expiresAtMs<=Date.now()))throw $w();let c=await e.confirmDeviceLinking({walletId:n.walletId,payload:t.payload}),l=e.readWalletAuthenticationState();if(l.kind!==`authenticated`||l.walletId!==n.walletId)throw $w();let u=await rT(e,n.walletId);if(c.assertCurrent(),u.operationCredential.walletSessionId!==r.operationCredential.walletSessionId||u.record.authorizationId!==r.record.authorizationId)throw $w();if(o){if(!s)throw $w();return{...a,exportRootRequirement:`required`,ed25519ExportRootCapability:s}}return{...a,exportRootRequirement:`not_required`}}async function tT(e,t){if(t.authentication.source.kind!==`wallet_session`)throw Error(`Wallet-host device linking requires a reusable owner Wallet Session`);let n=e.readWalletAuthenticationState();if(n.kind!==`authenticated`)throw $w();let r=await rT(e,n.walletId);if(t.authentication.source.walletSessionId!==r.operationCredential.walletSessionId||t.authentication.source.authorizationId!==r.record.authorizationId)throw Error(`Owner Wallet Session identity changed after authorization`);return await iT(e,r,t)}async function nT(e,t){return await iT(e,await rT(e,t.walletId),t)}async function rT(e,t){let n=await e.resolveSelectedWalletAuthority(t);if(n.kind!==`resolved`)throw $w();let{selection:r,authMethod:i,authority:a}=n;if(r.lockState!==`unlocked`||r.walletId!==t||r.walletAuthMethodId!==i.walletAuthMethodId||i.walletId!==t||i.walletAuthorityId!==a.authorityId||i.status!==`active`||a.walletId!==t||a.state!==`active`)throw $w();let o=await e.walletSessions.readExactWithOperationCredential({walletId:t,authorityId:a.authorityId,authMethodId:i.walletAuthMethodId});switch(o.kind){case`found`:break;case`missing`:throw $w();case`upgrade_required`:throw new Ra(`Stored owner Wallet Session requires a newer client`);default:throw Error(`Unsupported owner Wallet Session read result`)}if(o.record.authorityDigestB64u!==a.authorityDigestB64u||o.record.authorityRevocationEpoch!==a.revocationEpoch||o.record.expiresAtMs<=Date.now())throw $w();return o}async function iT(e,t,n){return await aT(e,t.operationCredential.token,n)}async function aT(e,t,n){let r=await e.http.request({method:n.method,url:`${e.baseUrl}${n.canonicalPath}`,headers:{authorization:`Bearer ${t}`},...n.body===void 0?{}:{body:n.body}});if(!r.ok)throw new Yw(r.code,r.message);return r.value}function oT(e,t){let n=lT(e),r=dT(n.authentication);if(r.kind!==`link_session_authenticated_request_v1`)throw Error(`Owner authorization authentication kind is invalid`);let i=Tr(r.source),a=Tr(n.ownerAuthorization);sT(i,t),cT(i,a);let o={kind:`link_session_authenticated_request_v1`,source:i,proofDigestB64u:Pt(r.proofDigestB64u)},s=_(n.walletId);if(!s.ok||s.value!==t.record.walletId)throw Error(`Owner authorization wallet identity changed`);return{authentication:o,walletId:s.value,ownerAuthorization:a,sourceSignerManifest:Vr(n.sourceSignerManifest),expiresAtMs:gT(n.expiresAtMs,`expiresAtMs`)}}function sT(e,t){if(e.kind!==`wallet_session`)throw Error(`Owner authorization did not return a Wallet Session source`);if(e.walletSessionId!==t.operationCredential.walletSessionId)throw Error(`Owner authorization Wallet Session id changed`);if(e.authorizationId!==t.record.authorizationId)throw Error(`Owner authorization id changed`)}function cT(e,t){if(e.kind!==`wallet_session`||t.kind!==`wallet_session`||e.walletSessionId!==t.walletSessionId||e.authorizationId!==t.authorizationId)throw Error(`Owner authorization source changed`)}function lT(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Owner authorization response must be an object`);if(!uT(e))throw Error(`Owner authorization response has unexpected fields`);return e}function uT(e){return Object.keys(e).sort().join(`|`)===`authentication|expiresAtMs|ownerAuthorization|sourceSignerManifest|walletId`}function dT(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Owner authorization response must be an object`);if(!fT(e))throw Error(`Owner authorization response has unexpected fields`);return e}function fT(e){return Object.keys(e).sort().join(`|`)===`kind|proofDigestB64u|source`}function pT(e){let t=mT(e.body);return t?`Owner authorization failed: ${t}`:`Owner authorization failed with HTTP ${e.status}`}function mT(e){return typeof e!=`object`||!e||Array.isArray(e)||!hT(e)||e.ok!==!1||typeof e.code!=`string`?null:typeof e.message==`string`&&e.message.trim()?e.message:null}function hT(e){return Object.keys(e).sort().join(`|`)===`code|message|ok`}function gT(e,t){if(!Number.isSafeInteger(e)||Number(e)<=0)throw Error(`${t} must be a positive safe integer`);return Number(e)}const _T=`/wallet/placement/v1/relocations`;function vT(e){if(e.host.readAuthentication()!==e.authentication)throw Error(`Wallet authentication changed during relocation approval`)}function yT(e,t){let n=E(e,`Wallet relocation challenge`);if(n.kind!==`challenge`||n.walletId!==t.walletId||n.moveId!==t.moveId||n.destinationRegion!==t.destinationRegion||n.expectedGeneration!==t.expectedGeneration||typeof n.requestDigest!=`string`||!/^[a-f0-9]{64}$/u.test(n.requestDigest)||typeof n.expiresAtMs!=`number`||!Number.isSafeInteger(n.expiresAtMs)||n.expiresAtMs<=Date.now())throw Error(`Wallet relocation challenge does not match the requested move`);let r=Pt(n.challengeB64u),i=E(n.factor,`Wallet relocation factor`);if(i.kind===`passkey`)return{challengeB64u:r,expiresAtMs:n.expiresAtMs,factor:{kind:`passkey`}};if(i.kind!==`email_otp`)throw Error(`Wallet relocation factor is unsupported`);let a=E(i.delivery,`Wallet relocation email delivery`);return{challengeB64u:r,expiresAtMs:n.expiresAtMs,factor:{kind:`email_otp`,challengeId:D(i.challengeId,`OTP challenge`),emailHint:D(a.emailHint,`Email hint`)}}}async function bT(e){vT(e);let t=await e.host.managementRequest.request({walletId:e.request.walletId,method:`POST`,canonicalPath:`${_T}/challenge`,body:e.request});if(vT(e),t.status!==200)throw Error(`Wallet relocation challenge failed (${t.status})`);return yT(t.body,e.request)}async function xT(e){let t=await bT(e);if(t.factor.kind!==`email_otp`)throw Error(`Wallet relocation factor changed`);return{challengeId:t.factor.challengeId,emailHint:t.factor.emailHint}}async function ST(e,t){switch(t.factor.kind){case`passkey`:{let n=await K.resolveSelectedWalletAuthority(e.request.walletId);if(vT(e),n.kind!==`resolved`||n.authMethod.kind!==`passkey`)throw Error(`Wallet relocation requires the selected owner passkey`);return{kind:`passkey`,credential:Tc(await e.host.signingEngine.getAuthenticationCredentialsSerialized({subjectId:e.request.walletId,challengeB64u:t.challengeB64u,allowCredentials:[{id:n.authMethod.credentialIdB64u,type:`public-key`,transports:[]}],includeSecondPrfOutput:!1}))}}case`email_otp`:{let n=await e.host.signingEngine.requestEmailOtpOwnerConfirmation({purpose:`move_wallet`,walletId:e.request.walletId,emailAddress:t.factor.emailHint,emailHint:t.factor.emailHint,challengeId:t.factor.challengeId,confirmerText:{title:`Move wallet region`,body:`Enter the code to move this wallet to ${e.request.destinationRegion}.`},onResend:xT.bind(null,e)});return{kind:`email_otp`,challengeId:n.challengeId,otpCode:n.otpCode}}default:return CT(t.factor)}}function CT(e){throw Error(`Unsupported wallet relocation factor: ${String(e)}`)}async function wT(e,t){return vT(e),e.host.managementRequest.request({walletId:e.request.walletId,method:`POST`,canonicalPath:_T,body:t})}async function TT(e,t){let n=Rw(t),r=e.readAuthentication();if(r.kind!==`authenticated`||r.walletId!==n.walletId)return{ok:!1,code:`wallet_unlock_required`};let i={host:e,request:n,authentication:r},a=await e.managementRequest.request({walletId:n.walletId,method:`GET`,canonicalPath:`${_T}/${encodeURIComponent(n.moveId)}?walletId=${encodeURIComponent(n.walletId)}`});if(vT(i),a.status===200)return ET(a.body,i);if(a.status===401||a.status===403)return{ok:!1,code:`unauthorized`};if(a.status!==404)return{ok:!1,code:`transport_unavailable`};await Jw(n),vT(i);let o=await wT(i,{walletId:n.walletId,moveId:n.moveId,destinationRegion:n.destinationRegion,expectedGeneration:n.expectedGeneration,sourceProof:null});if(vT(i),o.status===200)return ET(o.body,i);if(o.status===401||o.status===403)return{ok:!1,code:`unauthorized`};if(!DT(o))return{ok:!1,code:`transport_unavailable`};let s=await bT(i),c=await ST(i,s);if(vT(i),s.expiresAtMs<=Date.now())throw Error(`Wallet relocation approval expired`);let l={walletId:n.walletId,moveId:n.moveId,destinationRegion:n.destinationRegion,expectedGeneration:n.expectedGeneration,sourceProof:c},u;try{u=await wT(i,l)}catch(e){if(!(e instanceof Yw)||e.code!==`network_error`)throw e;u=await wT(i,l)}return vT(i),u.status===401||u.status===403?{ok:!1,code:`unauthorized`}:u.status===200?ET(u.body,i):{ok:!1,code:`transport_unavailable`}}async function ET(e,t){let n=t.request,r;try{r=Ww(e,n.moveId);let t=r.state===`moving`?r.move:r;if(t.destinationRegion!==n.destinationRegion||t.sourceGeneration!==n.expectedGeneration)throw Error(`Wallet relocation conflicts with the request`)}catch{return{ok:!1,code:`invalid_response`}}return await Pw(t.host,n.walletId,r),t.host.readAuthentication()===t.authentication?{ok:!0,status:r}:{ok:!1,code:`wallet_unlock_required`}}function DT(e){if(e.status!==409)return!1;try{let t=E(e.body,`Wallet relocation approval result`);return t.ok===!1&&t.code===`owner_approval_required`}catch{return!1}}function OT(e){return{getLastMoveRequest:qw,move:TT.bind(null,e),get:kT.bind(null,e),getMove:MT.bind(null,e)}}async function kT(e,t){let n=e.readAuthentication(),r=await NT(e,t,`/wallet/placement/v1?walletId=${encodeURIComponent(t)}`,AT);return r.ok&&await Pw(e,t,r.placement),e.readAuthentication()===n?r:{ok:!1,code:`wallet_unlock_required`}}function AT(e){return{ok:!0,placement:zw(e)}}function jT(e,t){return{ok:!0,status:Ww(t,e)}}async function MT(e,t,n){let r=e.readAuthentication(),i=await NT(e,t,`/wallet/placement/v1/relocations/${encodeURIComponent(n)}?walletId=${encodeURIComponent(t)}`,jT.bind(null,n));return i.ok&&await Pw(e,t,i.status),e.readAuthentication()===r?i:{ok:!1,code:`wallet_unlock_required`}}async function NT(e,t,n,r){let i=e.readAuthentication();if(i.kind!==`authenticated`||i.walletId!==t)return{ok:!1,code:`wallet_unlock_required`};let a;try{a=await e.managementRequest.request({walletId:t,method:`GET`,canonicalPath:n})}catch(t){return t instanceof X&&t.code===Z.WALLET_UNLOCK_REQUIRED||e.readAuthentication()!==i?{ok:!1,code:`wallet_unlock_required`}:{ok:!1,code:`transport_unavailable`}}if(e.readAuthentication()!==i)return{ok:!1,code:`wallet_unlock_required`};if(a.status===401||a.status===403)return{ok:!1,code:`unauthorized`};if(a.status!==200)return{ok:!1,code:`transport_unavailable`};try{return r(a.body)}catch{return{ok:!1,code:`invalid_response`}}}function PT(e){let t;return()=>(t??=e().catch(e=>{throw t=void 0,e}),t)}function FT(){return{ecdsaSessions:{exportArtifactsByLane:new Map}}}function IT(e){let t=PT(async()=>{let{createWarmSessionHydrationService:t}=await import(`./warmSessionHydration-B-A5Tdx7.js`);return t({getWarmSessionMaterialWriter:e.ui.warmSessions.getWarmSessionMaterialWriter})}),n={hydrateSigningSession:async e=>(await t()).hydrateSigningSession(e)},r=PT(async()=>{let{createRegistrationAccountsService:t}=await import(`./registrationAccounts-Bso0ntMs.js`);return t(e.registration.accountLifecycle)}),i={storeUserData:async e=>(await r()).storeUserData(e),getAllUsers:async()=>(await r()).getAllUsers(),getUserBySignerSlot:async(e,t)=>(await r()).getUserBySignerSlot(e,t),getLastUser:async()=>(await r()).getLastUser(),nearAuthenticatorsByAccount:async e=>(await r()).nearAuthenticatorsByAccount(e),setLastUser:async(e,t)=>(await r()).setLastUser(e,t),activateAuthenticatedWalletState:async e=>(await r()).activateAuthenticatedWalletState(e),setWalletNearProvisioningState:async e=>(await r()).setWalletNearProvisioningState(e),getWalletNearProvisioningState:async e=>(await r()).getWalletNearProvisioningState(e),storeAuthenticator:async e=>(await r()).storeAuthenticator(e),rollbackUserRegistration:async e=>(await r()).rollbackUserRegistration(e),hasPasskeyCredential:async e=>(await r()).hasPasskeyCredential(e),storeWalletEd25519RegistrationData:async e=>(await r()).storeWalletEd25519RegistrationData(e),storeWalletEd25519RecoveryRegistrationData:async e=>(await r()).storeWalletEd25519RecoveryRegistrationData(e),storeWalletEmailOtpEd25519RegistrationData:async e=>(await r()).storeWalletEmailOtpEd25519RegistrationData(e),storeWalletEmailOtpMixedRegistrationData:async e=>(await r()).storeWalletEmailOtpMixedRegistrationData(e),finalizeWalletEd25519SignerRegistration:async e=>(await r()).finalizeWalletEd25519SignerRegistration(e),rollbackWalletEd25519SignerRegistration:async e=>(await r()).rollbackWalletEd25519SignerRegistration(e)},a=PT(async()=>{let{createEcdsaWalletRecordsService:t}=await import(`./ecdsaWalletRecords-CKaXfsVu.js`);return t({accountLifecycle:e.registration.accountLifecycle})}),o={storeWalletEcdsaSignerRecords:async e=>(await a()).storeWalletEcdsaSignerRecords(e),storeWalletEmailOtpEcdsaSignerRecords:async e=>(await a()).storeWalletEmailOtpEcdsaSignerRecords(e),storeWalletEcdsaRecoverySignerRecords:async e=>(await a()).storeWalletEcdsaRecoverySignerRecords(e),finalizeWalletEcdsaRegistration:async e=>(await a()).finalizeWalletEcdsaRegistration(e),storeWalletEmailOtpEcdsaRegistrationData:async e=>(await a()).storeWalletEmailOtpEcdsaRegistrationData(e)},s={signNear:async t=>{let{signNear:n}=await import(`./signNear-DyFk--I3.js`).then(e=>e.n);return n(e.signing.near.getDeps(),t)}},c={signEvmFamily:async t=>{let{signEvmFamily:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)},reportTempoBroadcastAccepted:async t=>{let{reportTempoBroadcastAccepted:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)},reportTempoBroadcastRejected:async t=>{let{reportTempoBroadcastRejected:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)},reportTempoFinalized:async t=>{let{reportTempoFinalized:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)},reportTempoDroppedOrReplaced:async t=>{let{reportTempoDroppedOrReplaced:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)},reconcileTempoNonceLane:async t=>{let{reconcileTempoNonceLane:n}=await import(`./signEvmFamily-CMrXkVsZ.js`).then(e=>e.s);return n(e.signing.evmFamily.getDeps(),t)}};return{...e,services:{warmSessions:n,registrationAccounts:i,nearSigning:s,evmFamilySigning:c,ecdsaWalletRecords:o}}}function LT(e){return{network:e.network,registration:e.registration,signing:e.signing}}function RT(e){return rh({indexedDB:K,workerCtx:e})}function zT(e){let t=FT(),n=LT(e.config);return IT({runtimePorts:RT(e.workerCtx),workers:{emailOtp:e.workerCtx},signing:{near:{getDeps:e.getNearSigningDeps},evmFamily:{getDeps:e.getEvmFamilySigningDeps}},registration:{accountLifecycle:e.accountLifecycle,ecdsaBootstrapStore:e.ecdsaBootstrapStore},ui:{warmSessions:{getWarmSessionMaterialWriter:e.getWarmSessionMaterialWriter}},config:n,state:t})}var BT=class extends Error{code=`browser_capability_unavailable`;selection;constructor(e){super(`Browser capability ${e.operation.capabilityKind} is unavailable for ${e.operation.operationKind}: ${e.reason}`),this.name=`BrowserCapabilityUnavailableError`,this.selection=e}};function VT(e){return{kind:`selected`,operation:e}}function HT(e,t){return{kind:`disabled`,operation:e,reason:t}}function UT(e,t){switch(t.operationKind){case jt.signTransaction:case jt.signDelegateAction:case jt.signNep413Message:{let n=St(t.operationKind);return e.signing.routerAb.normalSigning.mode===`enabled`?VT(n):HT(n,`router_ab_normal_signing_disabled`)}case jt.exportKey:return VT(St(t.operationKind))}}function WT(e,t){let n=Tn(e.network.chains).some(e=>wn(e,t.chainTarget));switch(t.operationKind){case kt.signTransaction:case kt.exportKey:{let e=Et(t.operationKind);return n?VT(e):HT(e,`ecdsa_target_not_configured`)}}}function GT(e,t){switch(t.capabilityKind){case Mt.vaultAccess:return HT(At(t.operationKind),`capability_not_deployed`);case Mt.nearEd25519MpcSigning:return UT(e,t);case Mt.evmEcdsaMpcSigning:return WT(e,t)}}function KT(e,t){let n=GT(e,t);switch(n.kind){case`selected`:return n.operation;case`disabled`:throw new BT(n)}}function qT(e){return typeof e==`object`&&!!e&&`kind`in e}function JT(e,t){return typeof t==`string`?e.networkSlug===t:`chainId`in t?e.chainId===t.chainId:e.kind===t.family}function YT(e){return typeof e==`string`?e:qT(e)?H(e):`chainId`in e?`chainId ${e.chainId}`:`family ${e.family}`}function XT(e,t){if(qT(t))return xn(t);let n=Tn(e),r=n.filter(e=>JT(e,t)),i=r[0];if(r.length===1&&i)return i;if(r.length>1)throw Error(`[threshold-ecdsa] ambiguous chain selector "${YT(t)}": matched ${r.map(H).join(`, `)}. Name one exact network slug instead.`);let a=n.map(e=>e.networkSlug).join(`, `);throw Error(`[threshold-ecdsa] no configured ECDSA chain matches "${YT(t)}". Configured chains: ${a||`(none)`}.`)}function ZT(e,t){let n=XT(e,t);if(n.kind!==`tempo`)throw Error(`[threshold-ecdsa] expected a Tempo chain target, resolved ${H(n)}`);return n}function QT(e,t){let n=XT(e,t);if(n.kind!==`evm`)throw Error(`[threshold-ecdsa] expected an EVM chain target, resolved ${H(n)}`);return n}function $T(e,t){switch(t.kind){case`ed25519`:KT(e,{capabilityKind:Mt.nearEd25519MpcSigning,operationKind:jt.exportKey});return;case`ecdsa`:KT(e,{capabilityKind:Mt.evmEcdsaMpcSigning,operationKind:kt.exportKey,chainTarget:t.chainTarget});return}}function eE(e){return{exportKey:tE.bind(null,e)}}async function tE(e,t){let n=t.options??{};if(t.kind===`ed25519`){let r={kind:`ed25519`,...await e.currentWallet.nearSubject(t)};$T(e.configs,r);let i=await e.domain.resolveExactKeyExportLane(r);if(i.kind!==`ed25519`)throw Error(`[key-export] expected an Ed25519 lane, received ${i.kind}`);return await e.domain.exportKeypairWithUI({...r,laneIdentity:i.laneIdentity,materialActivation:i.materialActivation,options:n}),{kind:`exported`}}let r={kind:`ecdsa`,walletSession:await e.currentWallet.walletSession(t.walletSession),chainTarget:XT(e.configs.network.chains,t.chainTarget)};$T(e.configs,r);let i=await e.domain.resolveExactKeyExportLane(r);if(i.kind!==`ecdsa`)throw Error(`[key-export] expected an ECDSA lane, received ${i.kind}`);return await e.domain.exportKeypairWithUI({...r,laneIdentity:i.laneIdentity,options:n}),{kind:`exported`}}function nE(e,t,n){let r=String(e[t]||``).trim();if(!r)throw Error(`${n} returned missing ${t}`);return r}function rE(e,t){let n=typeof e==`number`?e:Number(e);if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} returned invalid signerSlot`);return Math.floor(n)}function iE(e,t){if(!A(e))throw Error(`${t} returned missing walletBinding`);let n=ki(nE(e,`walletId`,t)),r=B(nE(e,`nearAccountId`,t)),i=Oi(nE(e,`nearEd25519SigningKeyId`,t)),o=nE(e,`rpId`,t),s=a(nE(e,`credentialIdB64u`,t));if(!s.ok)throw Error(`${t} returned invalid credentialIdB64u`);let c=rE(e.signerSlot,t);return{walletId:n,nearAccountId:r,nearEd25519SigningKeyId:i,rpId:o,credentialIdB64u:s.value,signerSlot:c}}function aE(e,t){return iE(A(e.walletBinding)?e.walletBinding:e,t)}function oE(e,t,n){if(String(e.walletId)!==String(t.walletId)||String(e.nearAccountId)!==String(t.nearAccountId)||String(e.nearEd25519SigningKeyId)!==String(t.nearEd25519SigningKeyId)||e.rpId!==t.rpId||e.signerSlot!==t.signerSlot)throw Error(`${n} returned mismatched wallet binding`)}function sE(e){return{success:!1,error:e}}function cE(e,t){return globalThis.fetch(e,t)}function lE(e){try{e.onEvent?.(Yi({flowId:e.flowId,...e.event}))}catch{}}function uE(e){let t=String(e.configs.network.relayer?.url||``).trim();if(!t)throw Error(`missing_relayer_url`);return t}function dE(e){let t=o(e.signingEngine.getRpId());if(!t.ok)throw Error(`missing_rp_id`);return t.value}function fE(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=typeof n==`string`?n.trim():``;e&&t.push(e)}return t}function pE(e,t){let n=String(e[t]||``).trim();if(!n)throw Error(`sync-account ${t} is required`);return n}function mE(e){if(!k(e))throw Error(`sync-account ECDSA chain target is invalid`);let t=Number(e.chainId);if(!Number.isSafeInteger(t)||t<=0)throw Error(`sync-account ECDSA chain id is invalid`);if(e.kind===`evm`&&e.namespace===`eip155`)return{kind:`evm`,namespace:`eip155`,chainId:t,networkSlug:String(e.networkSlug||``).trim()||`evm-${t}`};if(e.kind===`tempo`)return{kind:`tempo`,chainId:t,networkSlug:String(e.networkSlug||``).trim()||`tempo-${t}`};throw Error(`sync-account ECDSA chain family is invalid`)}function hE(e){if(!Array.isArray(e)||e.length!==2||e[0]!==1||e[1]!==2)throw Error(`sync-account ECDSA participant ids are invalid`);return[1,2]}function gE(e){return e.kind===`sign`&&e.keyFamily===`ecdsa_secp256k1`}function _E(e){for(let t of e)if(gE(t))return t;return null}function vE(e,t){let n=k(e)?e:{},r=n.ecdsaCustody;if(!k(r)||r.kind!==`wallet_custody_ecdsa_sync_continuity_v1`)throw Error(`sync-account ECDSA custody continuity is invalid`);if(!Array.isArray(r.signers))throw Error(`sync-account ECDSA custody signer list is invalid`);let i=[];for(let e of r.signers){if(!k(e)||!k(e.walletKey))throw Error(`sync-account ECDSA custody signer is invalid`);let n=e.walletKey,r=pE(n,`walletId`);if(r!==String(t.walletId))throw Error(`sync-account ECDSA custody signer changed the wallet identity`);i.push({chainTarget:mE(e.chainTarget),walletKey:{walletId:r,keyHandle:pE(n,`keyHandle`),ecdsaThresholdKeyId:pE(n,`ecdsaThresholdKeyId`),signingRootId:pE(n,`signingRootId`),signingRootVersion:pE(n,`signingRootVersion`),relayerKeyId:pE(n,`relayerKeyId`),contextBinding32B64u:pE(n,`contextBinding32B64u`),derivationClientSharePublicKey33B64u:pE(n,`derivationClientSharePublicKey33B64u`),participantIds:hE(n.participantIds),publicCapability:ci(n.publicCapability)},activationReceipt:Zr(e.activationReceipt),runtimePolicyScope:Fe(e.runtimePolicyScope)})}let a=i[0];if(!a){if(n.ecdsaSession!==void 0||n.ecdsaActivationReceipt!==void 0)throw Error(`sync-account returned an ECDSA session without custody continuity`);return{kind:`wallet_custody_ecdsa_sync_continuity_v1`,state:`absent`,signers:[]}}let o=mi(n.ecdsaSession),s=Zr(n.ecdsaActivationReceipt),c=_E(t.walletSession.capabilitySubjects);if(!c||o.session.authorization_id!==t.walletSession.authorizationId||!ti(o.public_capability,a.walletKey.publicCapability)||!xi(s,a.activationReceipt)||!g(c.materialActivation,ii(o.public_capability.material_activation))||o.session.wallet_session_id!==t.session.walletSessionId||o.session.quota_id!==t.session.quotaId||o.session.expires_at_ms!==t.session.expiresAtMs||o.session.remaining_uses!==t.session.remainingUses)throw Error(`sync-account ECDSA session changed the Wallet Session or custody identity`);return{kind:`wallet_custody_ecdsa_sync_continuity_v1`,state:`activated`,signers:[a,...i.slice(1)],sessionActivation:o}}async function yE(e){try{return await e.json()}catch{return null}}async function bE(e){let t=await e.fetch(`${e.relayerUrl}/sync-account/options`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({rp_id:e.rpId,...e.walletId?{account_id:e.walletId}:{}})}),n=await yE(t);if(!t.ok||!k(n)||n.ok!==!0){let e=k(n)?String(n.message||n.code||``):``;throw Error(e||`sync-account/options failed (HTTP ${t.status})`)}let r=String(n.challengeId||``).trim(),i=String(n.challengeB64u||``).trim();if(!r||!i)throw Error(`sync-account/options returned an invalid challenge`);let a=k(n.walletBinding)?aE(n,`sync-account/options`):null,o=fE(n.credentialIds);if(e.walletId&&(!a||o.length===0))throw Error(`No passkey recovery capability found for wallet ${e.walletId}`);return{challengeId:r,challengeB64u:i,credentialIds:o,walletBinding:a}}async function xE(e,t){let n=t?ki(String(t)):null,r=uE(e),i=dE(e),a=await bE({relayerUrl:r,rpId:i,walletId:n?String(n):null,fetch:cE});return Object.freeze({walletId:n?String(n):null,relayerUrl:r,rpId:i,syncOptions:a})}function SE(e){let t=String(e.id||``).trim(),n=String(e.rawId||``).trim();if(!t||!n||t!==n)throw Error(`selected passkey credential identity is invalid`);let r=a(n);if(!r.ok)throw Error(`selected passkey credential identity is invalid`);return r.value}function CE(e,t){if(t===null)return e.credentialIds;if(!e.credentialIds.includes(t))throw Error(`replacement account-sync challenge changed the selected passkey`);return[t]}function wE(e,t){if(typeof e!=`string`||e.trim()!==e||!e)return null;let n=t(e);return n.ok?n.value:null}function TE(e){if(e.response.status!==409||!k(e.raw))return null;let t=e.raw;if(t.ok!==!1||t.code!==`already_committed`||t.kind!==`already_committed`||t.next!==`unlock_exact_method`||[`walletId`,`authorityId`,`walletAuthMethodId`,`mintId`,`authorizationId`,`walletSessionId`,`quotaId`].some(e=>{let n=t[e];return typeof n!=`string`||!n.trim()})||`walletSessionToken`in t||`walletSessionJwt`in t||`sessionKind`in t||`walletSession`in t||`operationCredential`in t||`credential`in t)return null;let n=wE(t.walletId,_),i=wE(t.authorityId,s),a=wE(t.walletAuthMethodId,r),o=wE(t.mintId,wt),c=wE(t.authorizationId,Ot),l=wE(t.walletSessionId,Tt),u=wE(t.quotaId,Ct);return!n||!i||!a||!o||!c||!l||!u||e.expectedWalletId!==null&&n!==e.expectedWalletId?null:{walletId:n,walletAuthMethodId:a}}async function EE(e){let t=await e.fetch(`${e.relayerUrl}/sync-account/verify`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({challengeId:e.challengeId,webauthn_authentication:Tc(e.credential)})}),n=await yE(t);if(!t.ok||!k(n)||n.ok!==!0||n.verified!==!0){let r=TE({response:t,raw:n,expectedWalletId:e.expectedWalletId});if(r)return{kind:`already_committed`,walletId:r.walletId,walletAuthMethodId:r.walletAuthMethodId,credentialIdB64u:e.selectedCredentialId};let i=k(n)?String(n.message||n.code||``):``;throw Error(i||`sync-account/verify failed (HTTP ${t.status})`)}let r=aE(n,`sync-account/verify`);e.onRelayVerifySucceeded?.(r);let i=yc(n);return{kind:`verified`,response:{verifiedBinding:r,parsedYaoResponse:i,ecdsaContinuity:vE(n,i)}}}function DE(e){throw Error(`Unexpected recovered capability ownership: ${String(e)}`)}async function OE(e){let t=e.ownership;switch(t.kind){case`caller_owned`:t.recovery.activeClient.dispose(),await e.context.signingEngine.clearVolatileWarmSigningMaterial(t.recovery.parsed.walletId);return;case`registry_owned`:await e.context.signingEngine.clearVolatileWarmSigningMaterial(t.recovery.parsed.walletId);return;case`empty`:case`committed`:return;default:return DE(t)}}function kE(e){e.optionsBinding&&oE(e.optionsBinding,e.verifiedBinding,`sync-account/verify`);let t=e.parsed;if(e.verifiedBinding.rpId!==e.rpId||e.requestedWalletId!==null&&e.requestedWalletId!==e.verifiedBinding.walletId||String(t.walletId)!==String(e.verifiedBinding.walletId)||String(t.nearAccountId)!==String(e.verifiedBinding.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.verifiedBinding.nearEd25519SigningKeyId)||t.credentialIdB64u!==e.verifiedBinding.credentialIdB64u||t.credentialIdB64u!==e.selectedCredentialId||e.expectedWalletAuthMethodId!==null&&String(t.walletAuthMethodId)!==e.expectedWalletAuthMethodId||t.signerSlot!==e.verifiedBinding.signerSlot)throw Error(`recovered Yao capability does not match the verified wallet binding`)}function AE(e){let t=e.capability.registrationContinuity;return{materialActivation:e.capability.materialActivation,lifecycleId:e.capability.lifecycle.lifecycleId,signingRootVersion:e.capability.lifecycle.rootShareEpoch,signingRootId:e.capability.applicationBinding.signing_root_id,signerSetId:e.capability.lifecycle.signerSetId,thresholdSessionId:e.capability.lifecycle.thresholdSessionId,activationTranscriptB64u:P(Uint8Array.from(t.activationTranscript)),activationCapabilityBindingB64u:P(Uint8Array.from(e.capability.activeCapabilityBinding))}}async function jE(e){return await e.load({nearAccountId:String(e.parsed.nearAccountId),signerSlot:e.parsed.signerSlot,expectedRegisteredPublicKeyB64u:P(Uint8Array.from(e.parsed.capability.registeredPublicKey))})}function ME(e){return{kind:Mc,applicationBindingDigestB64u:e.applicationBindingDigestB64u,registeredPublicKeyB64u:P(e.metadata.registeredPublicKey),participantIds:e.metadata.participantIds,stateEpoch:String(e.metadata.stateEpoch),walletId:String(e.parsed.walletId),nearAccountId:String(e.parsed.nearAccountId),nearEd25519SigningKeyId:e.parsed.nearEd25519SigningKeyId,signerSlot:e.parsed.signerSlot,signingWorkerId:e.parsed.relayerKeyId,signingWorkerVerifyingShareB64u:P(e.metadata.signingWorkerVerifyingShare)}}function NE(e){return`sealLocalMaterial`in e&&typeof e.sealLocalMaterial==`function`}async function PE(e){let t=Xs(e.parsed.walletCustody.envelope);if(!t.ok)throw Error(t.reason);let r=e.ownedFactorSecret.slice(),i=null,a=null,o=null;try{let s=Ko(e.parsed.walletCustody.envelope),c=AE(e.parsed),l=await bc({loadCachedMaterial:jE.bind(void 0,{load:e.loadWalletCustodyEd25519Material,parsed:e.parsed}),activation:c,envelope:s,ownedFactorSecret:r});if(l.kind===`opened`)o=l.activeClient;else{i=e.ownedFactorSecret.slice(),a=e.ownedFactorSecret.slice();let n=await e.rejoinWalletCustodyNearEd25519KeySet({walletId:String(e.parsed.walletId),custodyJson:t.custodyJson,factorSecret:i.buffer,nearEd25519SigningKeyId:e.parsed.nearEd25519SigningKeyId,recoveryBasis:e.parsed.capability,routerOrigin:new URL(e.relayerUrl).origin,walletSessionToken:e.parsed.operationCredential.token}),r=ME({parsed:e.parsed,applicationBindingDigestB64u:n.localMaterial.applicationBindingDigestB64u,metadata:n.metadata});await e.persistWalletCustodyEd25519Material({binding:r,sealed:{ciphertextB64u:n.localMaterial.b64u,nonceB64u:n.localMaterial.nonceB64u}}),o=await Po({material:{binding:r,sealed:{ciphertextB64u:n.localMaterial.b64u,nonceB64u:n.localMaterial.nonceB64u}},activation:ys(n.metadata),envelope:s,ownedFactorSecret:a})}if(!o)throw Error(`Wallet custody recovery produced no active Ed25519 client`);if(!NE(o))throw Error(`Wallet custody recovery produced an unsealable Ed25519 client`);let u=n(o.metadata().scope.threshold_session_id);if(!u.ok)throw Error(`Wallet custody recovery returned an invalid threshold session identity`);let d=e.parsed.walletCustody.envelope.factor;if(d.kind!==`passkey`)throw Error(`Wallet custody recovery returned a different factor authority`);await Wo({store:K,activeClient:o,identity:{walletId:String(e.parsed.walletId),nearAccountId:String(e.parsed.nearAccountId),nearEd25519SigningKeyId:String(e.parsed.nearEd25519SigningKeyId),thresholdSessionId:u.value,signerSlot:e.parsed.signerSlot,rpId:d.rpId,credentialIdB64u:d.credentialIdB64u,signingRootId:e.parsed.capability.applicationBinding.signing_root_id,signingRootVersion:e.parsed.capability.lifecycle.rootShareEpoch,signingWorkerId:e.parsed.relayerKeyId},stableServerScope:{relayerKeyId:e.parsed.relayerKeyId,participantIds:e.parsed.session.participantIds,runtimePolicyScope:e.parsed.capability.runtimePolicyScope,routerAbNormalSigning:e.parsed.session.routerAbNormalSigning},passkeyPrfFirstB64u:P(e.ownedFactorSecret)});let f=us({parsed:e.parsed,relayerUrl:e.relayerUrl,rpId:e.rpId,thresholdSessionId:u.value}),p={activeClient:o,walletSessionState:f,parsed:e.parsed},m=fo(p.activeClient.metadata());await ds({persistence:e.sessionPersistence,session:p.walletSessionState,prfFirstB64u:P(e.ownedFactorSecret),ed25519Restore:es({rpId:d.rpId,nearAccountId:String(e.parsed.nearAccountId),nearEd25519SigningKeyId:String(e.parsed.nearEd25519SigningKeyId),relayerKeyId:e.parsed.relayerKeyId,participantIds:e.parsed.session.participantIds,runtimePolicyScope:e.parsed.session.runtimePolicyScope,signerSlot:e.parsed.signerSlot,routerAbNormalSigning:e.parsed.session.routerAbNormalSigning,credentialIdB64u:d.credentialIdB64u,materialActivation:m}),materialActivation:m});let h=await e.activateCapability({activeClient:p.activeClient,facts:{thresholdSessionId:p.walletSessionState.thresholdSessionId,signer:p.walletSessionState.signingLane.identity.signer,signingRootId:p.walletSessionState.signingRootId,signingRootVersion:p.walletSessionState.signingRootVersion,routerAbNormalSigning:p.walletSessionState.routerAbNormalSigning,runtimePolicyScope:p.walletSessionState.runtimePolicyScope,relayerUrl:p.walletSessionState.relayerUrl}});if(!g(h.materialActivation,m))throw Error(`Passkey Ed25519 registry activation changed during recovery commit`);let _=await Ur({authority:e.parsed.foundingAuthority,materialActivation:h.materialActivation,updatedAtMs:Date.now()});return await K.persistFoundingWalletAuthority({authority:_,authMethod:e.parsed.foundingAuthMethod}),await e.sessionPersistence.upsertEd25519YaoPublicCapabilityLaneReference(No({walletSessionState:p.walletSessionState,materialActivation:h.materialActivation})),p}catch(e){throw o?.dispose(),e}finally{r.fill(0),i?.fill(0),a?.fill(0)}}function FE(e){let t=F(e);if(t.length!==20)throw Error(`ECDSA custody address must contain 20 bytes`);let n=`0x`;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n}function IE(e){if(e.state===`absent`)return null;let t=e.signers[0],n=new Set;for(let n of e.signers.slice(1))if(n.walletKey.keyHandle!==t.walletKey.keyHandle||!ti(n.walletKey.publicCapability,t.walletKey.publicCapability)||!xi(n.activationReceipt,t.activationReceipt)||!Fs(n.runtimePolicyScope,t.runtimePolicyScope))throw Error(`sync-account returned conflicting ECDSA custody identities`);for(let t of e.signers){let e=H(t.chainTarget);if(n.has(e))throw Error(`sync-account returned duplicate ECDSA custody chain targets`);n.add(e)}return t}async function LE(e){let t=IE(e.continuity);if(!t)return;let n=Xs(e.parsed.walletCustody.envelope);if(!n.ok)throw Error(n.reason);let r=t.walletKey,i=t.activationReceipt.ecdsa_activation.public_identity,a=e.ownedFactorSecret.slice(),[o,...s]=e.continuity.signers.map(e=>e.chainTarget);if(o)try{let c=await e.signingSurface.rejoinWalletCustodyEvmFamilyKeySet({walletId:r.walletId,custodyJson:n.custodyJson,factorSecret:a.buffer,evmFamilySigningKeySlotId:ai({walletId:r.walletId,signingRootId:r.signingRootId,signingRootVersion:r.signingRootVersion}),applicationBindingDigestB64u:r.publicCapability.context.application_binding_digest_b64u,registeredClientRootPublicKey33B64u:r.derivationClientSharePublicKey33B64u,relayerPublicIdentityJson:JSON.stringify({relayerKeyId:r.relayerKeyId,relayerPublicKey33B64u:i.server_public_key33_b64u,groupPublicKey33B64u:i.threshold_public_key33_b64u,ethereumAddress:FE(i.ethereum_address20_b64u),relayerShareRetryCounter:i.server_share_retry_counter})});await e.signingSurface.restoreWalletCustodyEcdsaContinuity({authority:e.parsed.authority,chainTargets:[o,...s],walletId:r.walletId,keyHandle:r.keyHandle,ecdsaThresholdKeyId:r.ecdsaThresholdKeyId,signingRootId:r.signingRootId,signingRootVersion:r.signingRootVersion,relayerKeyId:r.relayerKeyId,participantIds:r.participantIds,publicCapability:r.publicCapability,activationReceipt:t.activationReceipt,runtimePolicyScope:t.runtimePolicyScope,readyStateBlobB64u:c.readyStateBlobB64u,publicFacts:c.publicFacts})}finally{a.fill(0)}}async function RE(e){let t=e.walletId===null?null:String(e.walletId).trim();if(e.walletId!==null&&!t)throw Error(`passkey Yao unlock recovery requires a valid walletId`);let n=t?ki(t):null,r=e.prepared??await bE({relayerUrl:e.relayerUrl,rpId:e.rpId,walletId:n?String(n):null,fetch:e.fetch});if(e.prepared&&!e.credential)throw Error(`prepared account-sync challenge requires a CTA credential`);let i=CE(r,e.expectedCredentialIdB64u);e.onPromptStarted?.();let a=e.credential?e.credential:await e.collectCredential({challengeB64u:r.challengeB64u,credentialIds:i});e.onPromptSucceeded?.();let o=SE(a);if(e.expectedCredentialIdB64u!==null&&o!==e.expectedCredentialIdB64u)throw Error(`replacement account-sync assertion changed the selected passkey`);let s=Sc(a);if(!s)throw Error(`selected passkey did not return PRF.first`);e.onRelayVerifyStarted?.();let c=await EE({relayerUrl:e.relayerUrl,challengeId:r.challengeId,expectedWalletId:n,selectedCredentialId:o,credential:a,fetch:e.fetch,onRelayVerifySucceeded:e.onRelayVerifySucceeded});if(c.kind===`already_committed`)return c;let{verifiedBinding:l,parsedYaoResponse:u,ecdsaContinuity:d}=c.response,f=F(s);try{kE({requestedWalletId:n,expectedWalletAuthMethodId:e.expectedWalletAuthMethodId,rpId:e.rpId,optionsBinding:r.walletBinding,verifiedBinding:l,parsed:u,selectedCredentialId:o}),await e.prepareLocalProfile(u,a);let t=await e.withExactEd25519MaterialOwner({materialActivation:u.capability.materialActivation,nearAccountId:u.nearAccountId,task:PE.bind(void 0,{parsed:u,ownedFactorSecret:f,relayerUrl:e.relayerUrl,rpId:e.rpId,sessionPersistence:e.sessionPersistence,activateCapability:e.activateCapability,rejoinWalletCustodyNearEd25519KeySet:e.rejoinWalletCustodyNearEd25519KeySet,loadWalletCustodyEd25519Material:e.loadWalletCustodyEd25519Material,persistWalletCustodyEd25519Material:e.persistWalletCustodyEd25519Material})});return await tc({walletId:String(u.walletId),credentialIdB64u:u.credentialIdB64u,envelope:u.walletCustody.envelope}),await LE({signingSurface:{rejoinWalletCustodyEvmFamilyKeySet:e.rejoinWalletCustodyEvmFamilyKeySet,restoreWalletCustodyEcdsaContinuity:e.restoreWalletCustodyEcdsaContinuity},parsed:u,continuity:d,ownedFactorSecret:f}),{kind:`recovered`,recovery:t,verifiedBinding:l}}finally{f.fill(0)}}async function zE(e){let t=e.parsed,n=F(t.credentialPublicKeyB64u);await e.context.signingEngine.storeUserData({walletId:String(t.walletId),nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,operationalPublicKey:t.operationalPublicKey,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,lastUpdated:Date.now(),passkeyCredential:{id:String(e.credential.id||``),rawId:String(e.credential.rawId||``)},version:2}),await e.context.signingEngine.setWalletNearProvisioningState({walletId:t.walletId,status:`near_ready`,nearAccountId:t.nearAccountId});let r=(await K.listWalletPasskeyAuthenticators(String(t.walletId))).find(e=>e.credentialId===t.credentialIdB64u);if(r){if(r.signerSlot!==t.signerSlot||P(r.credentialPublicKey)!==t.credentialPublicKeyB64u)throw Error(`Stored linked passkey authenticator does not match account sync`)}else await e.context.signingEngine.storeAuthenticator({nearAccountId:t.nearAccountId,credentialId:t.credentialIdB64u,credentialPublicKey:n,transports:[],name:`Passkey for ${String(t.walletId)}`,registered:new Date().toISOString(),syncedAt:new Date().toISOString(),signerSlot:t.signerSlot});await K.persistFoundingWalletAuthority({authority:t.foundingAuthority,authMethod:t.foundingAuthMethod})}async function BE(e,t){await e.storeNearThresholdKeyMaterial({nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,publicKey:t.operationalPublicKey,relayerKeyId:t.relayerKeyId,keyVersion:t.keyVersion,participants:ce({clientParticipantId:t.session.participantIds[0],relayerParticipantId:t.session.participantIds[1],relayerKeyId:t.relayerKeyId,clientShareDerivation:`prf_first_v1`}),signerId:t.operationalPublicKey})}async function VE(e){await q.writeExactWithOperationCredential({record:e.walletSession,operationCredential:e.operationCredential})}async function HE(e,t,n){await zE({context:e,parsed:t,credential:n})}function UE(e){return{id:e,type:`public-key`,transports:[]}}async function WE(e,t){return await e.signingSurface.getAuthenticationCredentialsSerialized({subjectId:e.requestedWalletId||`account-sync`,challengeB64u:t.challengeB64u,allowCredentials:t.credentialIds.map(UE),includeSecondPrfOutput:!1})}function GE(e){lE({onEvent:e.onEvent,flowId:e.flowId,event:{phase:Qi.STEP_02_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,...e.requestedWalletId?{accountId:e.requestedWalletId}:{},interaction:{kind:`passkey_assert`,overlay:`show`}}})}function KE(e){lE({onEvent:e.onEvent,flowId:e.flowId,event:{phase:Qi.STEP_02_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,...e.requestedWalletId?{accountId:e.requestedWalletId}:{},interaction:{kind:`passkey_assert`,overlay:`hide`}}})}function qE(e){lE({onEvent:e.onEvent,flowId:e.flowId,event:{phase:Qi.STEP_03_RELAY_VERIFY_STARTED,status:`started`,...e.requestedWalletId?{accountId:e.requestedWalletId}:{}}})}function JE(e,t){lE({onEvent:e.onEvent,flowId:e.flowId,event:{phase:Qi.STEP_03_RELAY_VERIFY_SUCCEEDED,status:`succeeded`,accountId:String(t.walletId)}})}async function YE(e,t,n,r,i,a){let o=t?ki(String(t)):null;if(n.kind===`replacement_after_committed`&&o!==n.walletId)throw Error(`replacement account-sync attempt changed the committed wallet`);if(i&&i.walletId!==(o?String(o):null))throw Error(`prepared account-sync challenge wallet binding changed`);let s=`account-sync:${String(o||`discovery`)}`,c={kind:`empty`};try{let t=i?.relayerUrl??uE(e),l=i?.rpId??dE(e);if(i&&(uE(e)!==t||dE(e)!==l))throw Error(`prepared account-sync challenge runtime binding changed`);lE({onEvent:r?.onEvent,flowId:s,event:{phase:Qi.STEP_01_STARTED,status:`started`,...o?{accountId:String(o)}:{}}});let u={signingSurface:e.signingEngine,requestedWalletId:o?String(o):null,onEvent:r?.onEvent,flowId:s},d=await RE({walletId:o?String(o):null,relayerUrl:t,rpId:l,fetch:cE,expectedCredentialIdB64u:n.kind===`replacement_after_committed`?n.credentialIdB64u:null,expectedWalletAuthMethodId:n.kind===`replacement_after_committed`?n.walletAuthMethodId:null,...i?{prepared:i.syncOptions,credential:a}:{},collectCredential:WE.bind(void 0,u),activateCapability:e.signingEngine.activateVerifiedNearEd25519YaoMaterial.bind(e.signingEngine),withExactEd25519MaterialOwner:e.signingEngine.withExactEd25519MaterialOwner.bind(e.signingEngine),sessionPersistence:e.signingEngine,rejoinWalletCustodyNearEd25519KeySet:e.signingEngine.rejoinWalletCustodyNearEd25519KeySet.bind(e.signingEngine),rejoinWalletCustodyEvmFamilyKeySet:e.signingEngine.rejoinWalletCustodyEvmFamilyKeySet.bind(e.signingEngine),restoreWalletCustodyEcdsaContinuity:e.signingEngine.restoreWalletCustodyEcdsaContinuity.bind(e.signingEngine),loadWalletCustodyEd25519Material:e.signingEngine.loadWalletCustodyEd25519Material.bind(e.signingEngine),persistWalletCustodyEd25519Material:e.signingEngine.persistWalletCustodyEd25519Material.bind(e.signingEngine),prepareLocalProfile:HE.bind(void 0,e),onPromptStarted:GE.bind(void 0,u),onPromptSucceeded:KE.bind(void 0,u),onRelayVerifyStarted:qE.bind(void 0,u),onRelayVerifySucceeded:JE.bind(void 0,u)});if(d.kind===`already_committed`){if(n.kind===`initial`)return await YE(e,d.walletId,{kind:`replacement_after_committed`,walletId:d.walletId,walletAuthMethodId:d.walletAuthMethodId,credentialIdB64u:d.credentialIdB64u},r);throw Error(`sync-account/verify remained already committed after one replacement attempt`)}let{recovery:f,verifiedBinding:p}=d;return c={kind:`registry_owned`,recovery:f},await VE(f.parsed),await BE(e.signingEngine,f.parsed),lE({onEvent:r?.onEvent,flowId:s,event:{phase:Qi.STEP_04_AUTHENTICATOR_SAVED,status:`succeeded`,accountId:String(p.walletId)}}),lE({onEvent:r?.onEvent,flowId:s,event:{phase:Qi.STEP_05_THRESHOLD_SESSION_READY,status:`succeeded`,accountId:String(p.walletId)}}),await e.signingEngine.activateAuthenticatedWalletState({walletId:p.walletId,nearAccountId:p.nearAccountId,signerSlot:p.signerSlot,nearClient:e.nearClient}),c={kind:`committed`},lE({onEvent:r?.onEvent,flowId:s,event:{phase:Qi.STEP_06_COMPLETED,status:`succeeded`,accountId:String(p.walletId)}}),{success:!0,accountId:String(p.walletId),walletId:String(p.walletId),nearAccountId:String(p.nearAccountId),nearEd25519SigningKeyId:String(p.nearEd25519SigningKeyId),publicKey:f.parsed.operationalPublicKey,message:`Account synced successfully`,loginState:{isLoggedIn:!0}}}catch(t){let n=L(t)||`syncAccount failed`;try{await OE({context:e,ownership:c})}catch(e){let t=L(e)||`recovered capability cleanup failed`;n=`${n}; ${t}`}return lE({onEvent:r?.onEvent,flowId:s,event:{phase:Qi.FAILED,status:`failed`,...o?{accountId:String(o)}:{},error:{message:n}}}),sE(n)}}async function XE(e,t,n){return await YE(e,t,{kind:`initial`},n)}async function ZE(e,t,n,r){return await YE(e,t.walletId,{kind:`initial`},r,t,n)}async function QE(){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){await new Promise(eD);return}await Promise.resolve()}async function $E(e){let{context:t,delegate:n,options:r}=e,i=B(String(e.nearAccountId)),a=r?.confirmerText?.title,o=r?.confirmerText?.body,s={...n,senderId:n.senderId||String(i)};YC(r?.onEvent,i,{phase:W.STEP_01_STARTED,status:`started`,message:`Preparing delegate action inputs`,interaction:{kind:`none`,overlay:`none`}}),await QE();try{let n=await t.signingEngine.signNear({chain:`near`,kind:`delegateAction`,args:{commandSubject:XC({nearAccountId:i,walletSession:e.walletSession}),delegate:s,rpcCall:{nearRpcUrl:Ke(t.configs.network.chains),nearAccountId:String(i)},signerSlot:r?.signerSlot,confirmationConfigOverride:r?.confirmationConfig,title:a,body:o,onEvent:r?.onEvent}}),c={hash:n.hash,signedDelegate:n.signedDelegate,nearAccountId:String(i),logs:n.logs};return YC(r?.onEvent,i,{phase:W.STEP_15_COMPLETED,status:`succeeded`,message:`Delegate action signed`,interaction:{kind:`none`,overlay:`none`},data:{hash:c.hash}}),await r?.afterCall?.(!0,c),c}catch(e){let t=I(e);throw r?.onError?.(t),await r?.afterCall?.(!1),YC(r?.onEvent,i,{phase:W.FAILED,status:`failed`,message:t.message,interaction:{kind:`none`,overlay:`hide`},error:{message:t.message}}),t}}function eD(e){window.requestAnimationFrame(e)}async function tD(e){let{context:t,nearAccountId:n,params:r,options:i}=e,a=i?.confirmerText,o=i?.confirmationConfig,{signingEngine:s}=t,c=i?.signerSlot,l=typeof c==`number`&&Number.isSafeInteger(c)&&c>=1;try{let u=r.callbackUrl===void 0?null:D(r.callbackUrl,`callbackUrl`),d=r.state===void 0?null:te(r.state,`state`);if(YC(i?.onEvent,n,{phase:W.STEP_01_STARTED,status:`started`,message:`Preparing NEP-413 message signing`,interaction:{kind:`none`,overlay:`none`}}),c!==void 0&&!l)throw Error(`Invalid signerSlot for NEP-413 signing: ${c}`);let f=l?await s.getUserBySignerSlot(n,c):await s.getLastUser();if(!f||!f.operationalPublicKey)throw Error(`Operational NEAR key data not found for ${n}`);let p=new Uint8Array(32);if(typeof crypto>`u`||typeof crypto.getRandomValues!=`function`)throw Error(`Secure random not available to generate NEP-413 nonce`);crypto.getRandomValues(p);let m=ge(p);YC(i?.onEvent,n,{phase:W.STEP_10_COMMIT_STARTED,status:`running`,message:`Signing NEP-413 message`,interaction:{kind:`none`,overlay:`none`}});let h=await t.signingEngine.signNear({chain:`near`,kind:`nep413`,args:{commandSubject:XC({nearAccountId:n,walletSession:e.walletSession}),onEvent:i?.onEvent,message:r.message,recipient:r.recipient,nonce:m,callbackUrl:u,state:d,signerSlot:l?c:void 0,title:a?.title,body:a?.body,confirmationConfigOverride:o}});if(h.success)return YC(i?.onEvent,n,{phase:W.STEP_15_COMPLETED,status:`succeeded`,message:`NEP-413 message signed successfully`,interaction:{kind:`none`,overlay:`none`}}),{success:!0,accountId:h.accountId,publicKey:h.publicKey,signature:h.signature,nonce:m,...h.state===void 0?{}:{state:h.state}};throw Error(`NEP-413 signing failed: ${h.error||`Unknown error`}`)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return YC(i?.onEvent,n,{phase:W.FAILED,status:`failed`,message:`NEP-413 signing failed: ${t}`,interaction:{kind:`none`,overlay:`hide`},error:{message:t}}),i?.onError?.(e instanceof Error?e:Error(t)),{success:!1,error:t}}}function nD(e,t){let n=new rD(e);return{ownerOperation:iD.bind(null,t),signAndSendTransaction:n.signAndSendTransaction.bind(n),signTransaction:n.signTransaction.bind(n),sendTransaction:n.sendTransaction.bind(n),signDelegateAction:n.signDelegateAction.bind(n),signMessage:n.signMessage.bind(n)}}var rD=class{constructor(e){this.getContext=e}async signAndSendTransaction(e){let t=e.nearAccount.accountId,n={receiverId:e.receiverId,actions:e.actions};try{return await rw({context:this.getContext(),nearAccountId:t,walletSession:e.walletSession,transactionInput:n,options:e.options})}catch(e){return ft(e,`not_submitted`)}}async signTransaction(e){let t=e.nearAccount.accountId,{transaction:n,options:r}=e;try{return await iw({context:this.getContext(),nearAccountId:t,walletSession:e.walletSession,transactionInput:n,options:r})}catch(e){let t=I(e);throw await r?.afterCall?.(!1,void 0,t),t}}async sendTransaction(e){let t=e.nearAccount.accountId;return await aw({context:this.getContext(),nearAccountId:t,walletSession:e.walletSession,signedTransaction:e.signedTransaction,options:e.options})}async signDelegateAction(e){let t=e.nearAccount.accountId,{delegate:n,options:r}=e;return await $E({context:this.getContext(),nearAccountId:t,walletSession:e.walletSession,delegate:n,options:r})}async signMessage(e){let t=e.nearAccount.accountId,n=await tD({context:this.getContext(),nearAccountId:t,walletSession:e.walletSession,params:e.params,options:e.options});if(n?.success)await e.options?.afterCall?.(!0,n);else{let t=I(n?.error||`NEP-413 signing failed`);await e.options?.afterCall?.(!1,void 0,t)}return n}};async function iD(e,...t){let[n,r]=t;return await e(n,r.signal.throwIfAborted.bind(r.signal),aD,r.onSubmission)}function aD(e){}function oD(e){let t=new sD(e);return{signEvmFamily:t.signEvmFamily.bind(t),reportBroadcastAccepted:t.reportBroadcastAccepted.bind(t),reportBroadcastRejected:t.reportBroadcastRejected.bind(t),reportFinalized:t.reportFinalized.bind(t),reportDroppedOrReplaced:t.reportDroppedOrReplaced.bind(t),reconcileNonceLane:t.reconcileNonceLane.bind(t),onBroadcastStarted:t.onBroadcastStarted.bind(t)}}var sD=class{constructor(e){this.getContext=e}async signEvmFamily(e){let{chainTarget:t,walletSession:n}=e;return await this.getContext().signingEngine.signEvmFamily({walletSession:n,request:e.request,chainTarget:t,confirmationConfigOverride:e.options?.confirmationConfig,shouldAbort:e.options?.shouldAbort,onEvent:e.options?.onEvent})}async reportBroadcastAccepted(e){let t=V(e.walletSession.walletId);await this.getContext().signingEngine.reportTempoBroadcastAccepted({walletId:t,signedResult:e.signedResult,txHash:e.txHash,onEvent:e.options?.onEvent})}async reportBroadcastRejected(e){let t=V(e.walletSession.walletId);await this.getContext().signingEngine.reportTempoBroadcastRejected({walletId:t,signedResult:e.signedResult,...e.error===void 0?{}:{error:e.error},onEvent:e.options?.onEvent})}async reportFinalized(e){let t=V(e.walletSession.walletId);await this.getContext().signingEngine.reportTempoFinalized({walletId:t,signedResult:e.signedResult,...e.txHash?{txHash:e.txHash}:{},...e.receiptStatus?{receiptStatus:e.receiptStatus}:{},onEvent:e.options?.onEvent})}async reportDroppedOrReplaced(e){let t=V(e.walletSession.walletId);await this.getContext().signingEngine.reportTempoDroppedOrReplaced({walletId:t,signedResult:e.signedResult,reason:e.reason,...e.txHash?{txHash:e.txHash}:{},onEvent:e.options?.onEvent})}async reconcileNonceLane(e){let t=V(e.walletSession.walletId);return await this.getContext().signingEngine.reconcileTempoNonceLane({walletId:t,signedResult:e.signedResult,onEvent:e.options?.onEvent})}onBroadcastStarted(e){}};const cD=/^0x[0-9a-fA-F]{40}$/,lD=`0xfeec000000000000000000000000000000000000`,uD=[{type:`function`,name:`setUserToken`,inputs:[{name:`token`,type:`address`}]}];function dD(e,t){let n=String(t||``).trim();if(!cD.test(n))throw Error(`[tempo] invalid ${e}: expected 20-byte 0x-prefixed address`);return n.toLowerCase()}function fD(e){return`0xe7897444${dD(`fee token address`,e).slice(2).toLowerCase().padStart(64,`0`)}`}function pD(e){let{request:t,chainTarget:n}=e;if(t.chain!==`evm`||t.kind!==`eip1559`||t.senderSignatureAlgorithm!==`secp256k1`)throw Error(`[tempo] fee-token request must use the EIP-1559 secp256k1 envelope`);if(t.tx.chainId!==n.chainId)throw Error(`[tempo] fee-token request chain id does not match the Tempo target`);if(t.tx.to?.toLowerCase()!==`0xfeec000000000000000000000000000000000000`)throw Error(`[tempo] fee-token request must call the Tempo FeeManager`);if(t.tx.value!==0n)throw Error(`[tempo] fee-token request must not transfer value`);let r=String(t.tx.data??``).toLowerCase(),i=r.slice(10);if(!r.startsWith(`0xe7897444`)||!/^0{24}[0-9a-f]{40}$/.test(i))throw Error(`[tempo] fee-token request must call FeeManager.setUserToken(address)`);if(t.tx.accessList&&t.tx.accessList.length!==0)throw Error(`[tempo] fee-token request must not carry an access list`);let a=dD(`fee token address`,`0x${i.slice(24)}`);return{...t,tx:{...t.tx,to:lD,value:0n,data:fD(a)}}}function mD(e){return`0xed498fa8${dD(`user address`,e).slice(2).toLowerCase().padStart(64,`0`)}`}function hD(e){let t=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]*$/.test(t))throw Error(`[tempo] invalid userTokens(address) result: expected 0x-prefixed hex`);let n=t.slice(2);if(n.length<64)throw Error(`[tempo] invalid userTokens(address) result: expected at least 32 bytes`);let r=n.slice(0,64).slice(24);if(!/^[0-9a-f]{40}$/.test(r))throw Error(`[tempo] invalid userTokens(address) result: malformed address word`);return/^0+$/.test(r)?null:`0x${r}`}function gD(e){let t=dD(`fee token address`,e.token);return{to:dD(`fee manager contract address`,e.feeManager??`0xfeec000000000000000000000000000000000000`),value:0n,input:fD(t),abi:uD}}function _D(e,t){let n=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]+$/.test(n))throw Error(`[tempo] invalid ${t} result: expected 0x-prefixed hex`);let r=n.slice(2);if(r.length<128)throw Error(`[tempo] invalid ${t} result: missing ABI string header`);let i=Number(BigInt(`0x${r.slice(0,64)}`));if(!Number.isSafeInteger(i))throw Error(`[tempo] invalid ${t} result: unsafe ABI offset`);let a=i*2,o=a+64;if(o>r.length)throw Error(`[tempo] invalid ${t} result: ABI offset out of bounds`);let s=Number(BigInt(`0x${r.slice(a,o)}`));if(!Number.isSafeInteger(s))throw Error(`[tempo] invalid ${t} result: unsafe ABI string length`);let c=o;if(c+s*2>r.length)throw Error(`[tempo] invalid ${t} result: ABI string out of bounds`);let l=new Uint8Array(s);for(let e=0;e<s;e+=1)l[e]=Number.parseInt(r.slice(c+e*2,c+e*2+2),16);return new TextDecoder().decode(l)}function vD(e,t){let n=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw Error(`[tempo] invalid ${t} result: expected one ABI word`);let r=BigInt(n);if(r!==0n&&r!==1n)throw Error(`[tempo] invalid ${t} result: expected boolean`);return r===1n}async function yD(e){let t=await Sf({rpcUrl:e.rpcUrl,...e.timeoutMs===void 0?{}:{requestTimeoutMs:e.timeoutMs}}).request({method:`eth_call`,params:[{to:e.to,data:e.data},`latest`],...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}});if(typeof t!=`string`)throw Error(`[tempo] invalid eth_call response: expected a hex string`);return t}async function bD(e){let t=dD(`account address`,e.account);return hD(await yD({rpcUrl:e.rpcUrl,to:lD,data:mD(t),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}))}async function xD(e){let t=dD(`fee token address`,e.feeToken),n={rpcUrl:e.rpcUrl,to:t,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}},r=_D(await yD({...n,data:`0xe5a6b10f`}),`currency()`);return r===`USD`?vD(await yD({...n,data:`0x5c975abb`}),`paused()`)?{kind:`invalid`,feeToken:t,reason:`paused`,currency:`USD`}:{kind:`valid`,feeToken:t,currency:`USD`,paused:!1}:{kind:`invalid`,feeToken:t,reason:`unsupported_currency`,currency:r}}function SD(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<=0)throw Error(`[tempo] chainId must be a positive safe integer`);if(e.maxPriorityFeePerGas<0n)throw Error(`[tempo] maxPriorityFeePerGas must be non-negative`);if(e.maxFeePerGas<e.maxPriorityFeePerGas)throw Error(`[tempo] maxFeePerGas must be at least maxPriorityFeePerGas`);if(e.gasLimit<=0n)throw Error(`[tempo] gasLimit must be positive`);let t=gD({token:e.feeToken});return{chain:`evm`,kind:`eip1559`,senderSignatureAlgorithm:`secp256k1`,tx:{chainId:e.chainId,maxPriorityFeePerGas:e.maxPriorityFeePerGas,maxFeePerGas:e.maxFeePerGas,gasLimit:e.gasLimit,to:t.to,value:0n,data:t.input??`0x`,abi:t.abi,accessList:[]}}}function CD(e){return{managerStores:{userPreferencesStore:e,nonceLaneCoordinationStore:oa({indexedDB:e}),webauthnCredentialStore:e,passkeyAuthenticatorStore:e,nearKeyMaterialStore:e},signingEngineStores:{walletProfileAndSignerRecords:{accountStore:e,walletSignerStore:e,passkeyAuthenticatorStore:e,ecdsaBootstrapStore:e},recoveryAndDeviceLinking:{credentialStore:e},warmup:{store:e}},sealedSigningSessionStore:{writeExactSealedSession:qs,readExactSealedSession:Ro,listExactSealedSessionsForWallet:hs,listEcdsaSealedSessionsForWallet:mc,acquireSigningSessionRestoreLease:ps,releaseSigningSessionRestoreLease:os,updateExactSealedSessionPolicy:Mo},ed25519YaoPublicCapabilityReferences:new ia(e)}}function wD(){return np()||(typeof window<`u`?window.location.origin:``)}function TD(e){e.setWorkerBaseOrigin(wD()),typeof window<`u`&&ct(()=>{let t=wD();t!==e.getWorkerBaseOrigin()&&e.setWorkerBaseOrigin(t)}),e.userPreferencesManager.initFromIndexedDB().catch(()=>void 0)}async function ED(e){let t=Nl(),n=new Uint8Array(e.factorSecret.slice(0));try{return await OD(e,t,t=>{let r=Xs(e.custodyEnvelope);if(!r.ok)throw Error(r.reason);return e.worker.rotateRecoverySet({custodyJson:r.custodyJson,factorSecret:n.buffer.slice(0),recoveryCodesJson:kD(t)})})}finally{n.fill(0),t&&kl(t),t=null}}async function DD(e){let t=Nl();try{return await OD(e,t,t=>e.worker.rotateRecoverySet({recoveryCodesJson:kD(t)}))}finally{t&&kl(t),t=null}}async function OD(e,t,n){let r={walletId:e.walletId,requestId:e.statusRequestId},i=await Lf({relayUrl:e.relayUrl,walletId:e.walletId,requestId:e.statusRequestId,factorProof:await e.factorProof({operation:`recovery_status`,payload:r}),...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}});if(i.kind!==`ready`)return i.kind===`unauthorized`?{kind:`transport_failed`,message:i.message}:i;let a=Al(await n(t.codeBytes));if(a.walletId!==e.walletId)throw Error(`Recovery rotation worker returned a different wallet`);let o=await AD(t.codeBytes,a.manifestKekWraps),s=await Gf({relayUrl:e.relayUrl,walletId:e.walletId,factorProof:await e.factorProof({operation:`recovery_rotate`,payload:{walletId:e.walletId,expectedStoreVersion:i.storeVersion,manifestKekWraps:a.manifestKekWraps,entries:[a.entry],recoveryCodeLocators:o}}),expectedStoreVersion:i.storeVersion,replacement:a,recoveryCodeLocators:o,...e.fetchImpl?{fetchImpl:e.fetchImpl}:{}});return s.kind===`rotated`?{kind:`rotated`,walletId:e.walletId,recoveryCodes:t.codes,issuedAtMs:s.issuedAtMs,storeVersion:s.storeVersion}:s}function kD(e){return JSON.stringify(e.map(e=>({codeBytesB64u:P(e)})))}async function AD(e,t){if(e.length!==t.length)throw Error(`Recovery code locators do not match the replacement wraps`);let n=await Promise.all(e.map(async(e,n)=>{let r=t[n];if(!r)throw Error(`Recovery code locators do not match the replacement wraps`);return{locatorB64u:await jl(e),recoveryKeyId:r.recoveryKeyId}}));if(new Set(n.map(e=>e.locatorB64u)).size!==n.length)throw Error(`Recovery code locators must be unique`);return n}async function jD(e){let t=`${fe(e.relayUrl)}/wallets/custody/envelope`,n=e.fetchImpl||fetch,r;try{r=await n(t,le({body:{locator:e.locator,challengeId:e.challengeId,expectedOrigin:e.expectedOrigin,webauthnAuthentication:e.webauthnAuthentication}}))}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`custody envelope request failed`}}let i=await r.json().catch(()=>void 0);if(r.status===200&&ID(i))try{return{kind:`active`,envelope:ND(i).envelope}}catch{return{kind:`corrupt`,message:`custody envelope response was incomplete`}}let a=FD(i,`custody envelope response`),o=a.code??``,s=a.message??``;switch(r.status){case 404:return{kind:`missing`,message:s||`no custody envelope for this credential`};case 409:return{kind:`retired`,message:s||`this envelope was superseded`};case 401:case 403:return{kind:`credential_rejected`,message:s||`this credential does not open the wallet`};case 500:return o===`envelope_digest_mismatch`?{kind:`corrupt`,message:s||`stored custody envelope failed its digest`}:{kind:`transport_failed`,message:s||`custody envelope request failed (HTTP ${r.status})`};default:return{kind:`request_rejected`,message:s||`custody envelope request rejected (HTTP ${r.status})`}}}async function MD(e){let t=`${fe(e.relayUrl)}/wallets/${encodeURIComponent(e.walletId)}/custody/envelope/ownership`,n=e.fetchImpl||fetch,r;try{r=await n(t,le({body:{envelope:e.envelope},headers:ie({token:e.walletSessionToken,missingMessage:`custody envelope upgrade needs an active Wallet Session`})}))}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`custody envelope upgrade failed`}}let i=await r.json().catch(()=>void 0);if(r.status===200)try{let e=PD(i);if(e.kind===`already_owned`)return e;let t=Number(e.envelopeRevision);if(!Number.isSafeInteger(t)||t<=0)throw Error(`invalid envelope revision`);return{kind:`upgraded`}}catch{return{kind:`rejected`,message:`custody envelope upgrade returned an invalid response`}}return{kind:`rejected`,message:FD(i,`custody envelope upgrade response`).message||`custody envelope upgrade rejected (HTTP ${r.status})`}}function ND(e){let t=RD(e,[`ok`,`envelope`,`storeVersion`],`custody envelope response`);if(VD(t,`ok`)!==!0)throw Error(`custody envelope response did not succeed`);let n=HD(t,`storeVersion`);if(!n)throw Error(`custody envelope response is missing its store version`);return{envelope:vn(VD(t,`envelope`),`custody envelope response.envelope`),storeVersion:n}}function PD(e){let t=LD(e,`custody envelope upgrade response`),n=VD(t,`upgraded`);if(n===!0){if(RD(t,[`ok`,`upgraded`,`envelopeRevision`],`custody envelope upgrade response`),VD(t,`ok`)!==!0)throw Error(`custody envelope upgrade response did not succeed`);return{kind:`upgraded`,envelopeRevision:VD(t,`envelopeRevision`)}}if(n===!1){if(RD(t,[`ok`,`upgraded`],`custody envelope upgrade response`),VD(t,`ok`)!==!0)throw Error(`custody envelope upgrade response did not succeed`);return{kind:`already_owned`}}throw Error(`custody envelope upgrade response has an invalid branch`)}function FD(e,t){try{let n=LD(e,t),r=Object.keys(n);if(!r.includes(`ok`)||!BD(r,[`ok`,`code`,`message`]))throw Error(`${t} has an unexpected response shape`);if(VD(n,`ok`)!==!1)throw Error(`${t} is not a failure`);return{code:UD(n,`code`),message:UD(n,`message`)}}catch{return{code:null,message:null}}}function ID(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1;let n=Object.getOwnPropertyDescriptor(e,`ok`);return!!(n&&`value`in n&&n.value===!0)}function LD(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be a JSON object`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw Error(`${t} must be a plain JSON object`);return e}function RD(e,t,n){let r=LD(e,n),i=Object.keys(r);if(i.length!==t.length||!zD(i,t))throw Error(`${n} has an unexpected response shape`);return r}function zD(e,t){for(let n of t)if(!e.includes(n))return!1;return!0}function BD(e,t){for(let n of e)if(!t.includes(n))return!1;return!0}function VD(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!(`value`in n))throw Error(`response field ${t} is missing`);return n.value}function HD(e,t){let n=VD(e,t);return typeof n==`string`?n.trim():``}function UD(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return!n||!(`value`in n)?null:(typeof n.value==`string`?n.value.trim():``)||null}function WD(e){return Array.isArray(e)?e.filter(e=>{switch(e){case`ble`:case`hybrid`:case`internal`:case`nfc`:case`smart-card`:case`usb`:return!0;default:return!1}}):[]}function GD(e){let t=e.flatMap(e=>{let t=String(e.credentialId||``).trim();return t?[{id:t,type:`public-key`,transports:WD(e.transports)}]:[]});if(t.length===0)throw Error(`Wallet recovery-code rotation requires an active passkey`);return t}async function KD(e){let t=await fetch(c(e.relayUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:e.walletId,rpId:e.rpId})}),n=await t.json().catch(()=>({})),r=n&&typeof n==`object`&&!Array.isArray(n)?n:{};if(!t.ok||r.ok!==!0)throw Error(typeof r.message==`string`?r.message:`passkey envelope challenge failed`);let i=typeof r.challengeId==`string`?r.challengeId.trim():``,a=typeof r.challengeB64u==`string`?r.challengeB64u.trim():``;if(!i||!a)throw Error(`passkey envelope challenge is invalid`);return{challengeId:i,challengeB64u:a}}async function qD(e){let t=String(e.context.signingEngine.getRpId()||``).trim();if(!t)throw Error(`Wallet recovery-code rotation requires an RP ID`);let n=typeof window>`u`?``:window.location.origin;if(!n)throw Error(`Wallet recovery-code rotation requires a browser Origin`);let r=GD(await K.listProfileAuthenticators(e.walletId)),i=await KD({relayUrl:e.relayUrl,walletId:e.walletId,rpId:t}),a=await e.context.signingEngine.getAuthenticationCredentialsSerialized({subjectId:e.walletId,challengeB64u:i.challengeB64u,allowCredentials:r,includeSecondPrfOutput:!0}),o=Tl(a);if(!o)throw Error(`Wallet recovery-code rotation did not receive a passkey credential`);let s=await jD({relayUrl:e.relayUrl,locator:{walletId:e.walletId,factor:{kind:`passkey`,rpId:t,credentialIdB64u:o}},challengeId:i.challengeId,expectedOrigin:n,webauthnAuthentication:Tc(a)});if(s.kind!==`active`)throw Error(s.message);let c=s.envelope,l=F(El(a,`Wallet recovery-code rotation`));try{let i=e.context.signingEngine.getSignerWorkerContext();return await ED({relayUrl:e.relayUrl,walletId:e.walletId,factorProof:async({operation:i,payload:a})=>{let s=await Fl({walletId:e.walletId,operation:i,payload:a,requestOrigin:n}),c=await e.context.signingEngine.getAuthenticationCredentialsSerialized({subjectId:e.walletId,challengeB64u:s,allowCredentials:r,includeSecondPrfOutput:!1}),l=Tl(c);if(!l||l!==o)throw Error(`Wallet recovery-code rotation selected an unrelated passkey`);return{kind:`passkey`,walletId:e.walletId,rpId:t,credentialIdB64u:o,challenge_digest:s,webauthn_authentication:Tc(c)}},statusRequestId:ve(`wallet-recovery-status`,16,`wallet recovery status request IDs`),custodyEnvelope:c,factorSecret:l.buffer,worker:{rotateRecoverySet:async e=>await i.requestWorkerOperation({kind:`walletCustodyCeremony`,request:{type:`rotateWalletRecoverySet`,timeoutMs:3e4,payload:e,transfer:[e.factorSecret]}})}})}finally{l.fill(0)}}async function JD(e,t){return await Hf({context:e.context,relayUrl:e.relayUrl,request:t})}async function YD(e,t){let n=await Vf(e.walletId),r=await Ys({relayUrl:e.relayUrl,walletId:e.walletId,walletAuthMethodId:n.walletAuthMethodId,operation:Ht});if(r.walletAuthMethodId!==n.walletAuthMethodId)throw Error(`Recovery rotation Email OTP challenge selected another owner method`);let i=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:`recovery_unlock`,walletId:e.walletId,emailAddress:`your email`,challengeId:r.challengeId});if(i.challengeId!==r.challengeId)throw Error(`Recovery rotation Email OTP unlock changed its challenge`);let a=Ss({routeFamily:`login`,operation:Ht});return await e.context.signingEngine.getSignerWorkerContext().requestWorkerOperation({kind:`emailOtp`,request:{type:`rotateEmailOtpWalletRecoverySet`,timeoutMs:6e4,payload:{relayUrl:e.relayUrl,walletId:e.walletId,walletAuthMethodId:n.walletAuthMethodId,userId:e.walletId,groupId:Ze,routePlan:a,verification:{kind:`otp`,challengeId:i.challengeId,otpCode:i.otpCode},recoveryCodesJson:t.recoveryCodesJson}}})}async function XD(e){let t=JD.bind(null,{context:e.context,relayUrl:e.relayUrl});return await DD({relayUrl:e.relayUrl,walletId:e.walletId,factorProof:t,statusRequestId:ve(`wallet-recovery-status`,16,`wallet recovery status request IDs`),worker:{rotateRecoverySet:YD.bind(null,e)}})}async function ZD(e){switch(e.authorization.kind){case`existing_passkey`:return await qD(e);case`email_otp`:return await XD(e)}}function QD(e){return e?e.status===`near_ready`?{kind:`near_ready`,nearAccountId:e.nearAccountId}:e.status===`near_failed_retryable`?{kind:`near_failed_retryable`,reason:e.error}:null:null}async function $D(e,t){let n=String(t.walletId||``).trim();if(!n)throw Error(`[seams] waitForNearAccount requires a walletId`);let r=Math.max(1,Math.floor(t.timeoutMs??12e4)),i=null,a=null,o=null;try{return await new Promise((s,c)=>{let l=!1,u=e=>{l||(l=!0,s(e))};if(t.signal?.aborted){c(t.signal.reason??Error(`[seams] waitForNearAccount aborted`));return}t.signal&&(o=()=>{l||(l=!0,c(t.signal?.reason??Error(`[seams] waitForNearAccount aborted`)))},t.signal.addEventListener(`abort`,o,{once:!0})),i=e.onNearAccountChange(e=>{if(String(e.walletId)!==n)return;let t=QD(e.state);t&&u(t)}),a=setTimeout(()=>u({kind:`timed_out`}),r),e.getNearAccountState({walletId:n}).then(e=>{let t=QD(e);t&&u(t)}).catch(()=>{})})}finally{a&&clearTimeout(a),o&&t.signal&&t.signal.removeEventListener(`abort`,o);try{i?.()}catch{}}}function eO(e){return typeof e==`string`?En({walletId:e}):e}function tO(e){return typeof e==`string`?Cn(e):e}function nO(e){let t=async()=>{let t=await e.getWalletSession();if(t.authentication.kind!==`authenticated`)throw Error("[seams] no authenticated wallet: unlock a wallet first, or pass an explicit `walletSession`.");return t};return{walletSession:async e=>e?eO(e):En({walletId:(await t()).authentication.walletId}),nearSubject:async e=>{if(e.walletSession&&e.nearAccount)return{walletSession:eO(e.walletSession),nearAccount:tO(e.nearAccount)};let n=await t(),r=n.authentication.walletId,i=e.walletSession?eO(e.walletSession):En({walletId:r});if(e.nearAccount)return{walletSession:i,nearAccount:tO(e.nearAccount)};let a=n.appIdentity;if(a.kind!==`resolved`||String(a.walletId)!==String(r))throw Error("[seams] the authenticated wallet has no resolved NEAR account: pass an explicit `nearAccount`.");if(!a.nearAccountId)throw Error("[seams] this wallet has no NEAR account yet (NEAR provisioning may still be pending): pass an explicit `nearAccount`, or await `seams.registration.waitForNearAccount`.");return{walletSession:i,nearAccount:Cn(a.nearAccountId)}}}}function rO(e){let t=new iO(e.linkedDeviceManagement);return{startLinking:e.startLinking,cancelLinking:e.cancelLinking,approveLinking:e.approveLinking,list:t.list.bind(t),remove:t.remove.bind(t)}}var iO=class{constructor(e){this.management=e}async list(e){let t=hr({kind:`linked_device_list_request_v1`,walletId:aO(e.walletId),limit:e.limit,cursor:e.cursor});return ur(await this.management.listLinkedDevices({walletId:t.walletId,limit:t.limit,cursor:t.cursor}))}async remove(e){return nr(await this.management.revokeLinkedDevice({walletId:aO(e.walletId),walletAuthMethodId:oO(e.walletAuthMethodId)}))}};function aO(e){let t=_(e);if(!t.ok)throw Error(t.error.message);return t.value}function oO(e){let t=r(e);if(!t.ok)throw Error(t.error.message);return t.value}function sO(e,t){let n={operationId:Qt.signingOperation(`owner-near:${_e(32,`owner NEAR operation IDs`)}`),walletId:t.authentication.walletId,nearAccountId:B(t.nearAccountId)},r=yt({action:`approve`,authentication:t.authentication,recovery:n,expiresAtMs:Math.min(t.authentication.expiresAtMs,Date.now()+12e4),transaction:{receiverId:t.transaction.receiverId,actions:t.transaction.actions.map(an)}});if(r.action!==`approve`)throw Error(`Invalid prepared owner operation.`);return new lO(e,r,{kind:`prepared`,recovery:n,expiresAtMs:r.expiresAtMs})}function cO(e,t){let n=_t(t.recovery);return new lO(e,yt({action:`recover`,authentication:t.authentication,recovery:n}),{kind:`unknown`,recovery:n})}var lO=class{controller=new AbortController;listeners=new Set;inFlight=null;constructor(e,t,n){this.execute=e,this.command=t,this.state=n}getState(){return this.state}subscribe(e){return this.listeners.add(e),this.removeListener.bind(this,e)}removeListener(e){this.listeners.delete(e)}transition(e){this.state=e;for(let e of this.listeners)try{e()}catch{}}approve(){if(this.inFlight)return this.inFlight;if(this.command.action!==`approve`||this.state.kind!==`prepared`)throw Error(`This operation cannot request another approval.`);return this.command.expiresAtMs<=Date.now()?(this.transition({kind:`expired`,recovery:this.command.recovery}),Promise.resolve({kind:`expired`})):(this.transition({kind:`approval`,recovery:this.command.recovery,expiresAtMs:this.command.expiresAtMs}),this.inFlight=this.run(this.command),this.inFlight)}cancel(){this.state.kind===`prepared`?(this.controller.abort(),this.transition({kind:`cancelled`,recovery:this.command.recovery})):this.state.kind===`approval`&&this.controller.abort()}recover(){if(this.inFlight)return this.inFlight;if(this.state.kind!==`unknown`)throw Error(`Only an unknown outcome requires recovery.`);return this.inFlight=this.run({action:`recover`,authentication:this.command.authentication,recovery:this.state.recovery}),this.inFlight}submitted(){this.transition({kind:`submitting`,recovery:this.command.recovery})}async run(e){let t;try{t=await this.execute(e,{signal:e.action===`recover`?new AbortController().signal:this.controller.signal,onSubmission:this.submitted.bind(this)})}catch{t={kind:`unknown`,recovery:e.recovery}}return this.settle(t,e.recovery),this.inFlight=null,t}settle(e,t){switch(e.kind){case`completed`:this.transition({kind:`completed`,recovery:t,result:e.result});return;case`reverted`:this.transition({kind:`reverted`,recovery:t,transactionId:e.transactionId,error:e.error});return;case`cancelled`:this.transition({kind:`cancelled`,recovery:t});return;case`expired`:this.transition({kind:`expired`,recovery:t});return;case`unknown`:this.transition({kind:`unknown`,recovery:e.recovery});return;case`failed`:this.transition({kind:`failed`,recovery:t,error:e.error});return;default:throw Error(`Unsupported owner operation outcome.`)}}};function uO(e){return/UNKNOWN_ACCOUNT|unknown\s+account|account\b[^\n]*\bdoes not exist/iu.test(L(e))}function dO(e){return/server error|internal|temporar|timeout|throttl|too many requests|429|empty response|rpc request failed|failed to fetch/iu.test(L(e))}function fO(e){setTimeout(e,150)}async function pO(e,t){let n=B(t);try{return await e.viewAccount(n),!0}catch(e){if(uO(e))return!1;if(!dO(e))throw e}await new Promise(fO);try{return await e.viewAccount(n),!0}catch(e){if(uO(e))return!1;throw e}}function mO(e){let t={"content-type":`application/json`},n=String(e?.publishableKey??``).trim();n&&(t.Authorization=`Bearer ${n}`);let r=String(e?.environmentId??``).trim();return r&&(t[`X-Seams-Environment-Id`]=r),t}function hO(e,t){if(!A(e))return{ok:!1,error:`Relayer HTTP ${t}`};let n=typeof e.code==`string`?e.code.trim():``,r=(typeof e.message==`string`?e.message.trim():typeof e.error==`string`?e.error.trim():``)||`Relayer HTTP ${t}`;return{ok:!1,error:n?`${r} (${n})`:r}}function gO(e){let t=e?.registration;if(!t||typeof t!=`object`||t.mode!==`managed`)return{};let n=String(t.publishableKey??``).trim(),r=String(t.projectEnvironmentId??``).trim();return{...n?{publishableKey:n}:{},...r?{environmentId:r}:{}}}const _O=e=>Array.isArray(e)?e:Array.from(e),vO=e=>{let t=e.delegateAction,n=e.signature;return{delegateAction:{...t,publicKey:{...t.publicKey,keyData:_O(t.publicKey.keyData)}},signature:{...n,signatureData:_O(n.signatureData)}}};async function yO(e){let{url:t,payload:n,auth:r,signal:i,options:a}=e,o={...n,signedDelegate:vO(n.signedDelegate)};YC(a?.onEvent,`delegate`,{phase:W.STEP_12_BROADCAST_STARTED,status:`running`,message:`Submitting delegate to relayer`,interaction:{kind:`none`,overlay:`none`}});let s;try{s=await fetch(t,{method:`POST`,headers:mO(r),body:JSON.stringify(o),signal:i||AbortSignal.timeout(3e4)})}catch(e){let t=e instanceof DOMException&&e.name===`TimeoutError`?Error(`Relayer request timed out after 30 seconds`):e instanceof Error?e:Error(String(e));throw a?.onError?.(t),bO(a,t.message),await a?.afterCall?.(!1),t}if(!s.ok){let e=null;try{e=await s.json()}catch{}let t=hO(e,s.status);return a?.onError?.(Error(t.error)),bO(a,t.error),await a?.afterCall?.(!1),t}let c;try{let e=await s.json();c=A(e)?e:{}}catch(e){let t={ok:!1,error:`Relayer returned non-JSON response`},n=e instanceof Error?e:Error(String(e));return a?.onError?.(n),bO(a,t.error),await a?.afterCall?.(!1),t}let l={ok:!!(c.ok??!0),relayerTxHash:typeof c.relayerTxHash==`string`?c.relayerTxHash:typeof c.transactionId==`string`?c.transactionId:typeof c.txHash==`string`?c.txHash:void 0,status:typeof c.status==`string`?c.status:void 0,outcome:c.outcome,error:typeof c.error==`string`?c.error:void 0};if(l.ok!==!1)YC(a?.onEvent,`delegate`,{phase:W.STEP_15_COMPLETED,status:`succeeded`,message:`Delegate relayed successfully`,interaction:{kind:`none`,overlay:`none`}}),await a?.afterCall?.(!0,l);else{let e=l.error||`Relayer execution failed`;a?.onError?.(Error(e)),bO(a,e),await a?.afterCall?.(!1)}return l}function bO(e,t){YC(e?.onEvent,`delegate`,{phase:W.FAILED,status:`failed`,message:t,interaction:{kind:`none`,overlay:`hide`},error:{message:t}})}function xO(e){let t=new CO(e);return{prepareOwnerTransaction:sO.bind(null,e.commands.ownerOperation),resumeOwnerTransaction:cO.bind(null,e.commands.ownerOperation),accountExists:pO.bind(null,e.nearClient),signAndSendTransaction:t.signAndSendTransaction.bind(t),signTransaction:t.signTransaction.bind(t),sendTransaction:t.sendTransaction.bind(t),signDelegateAction:t.signDelegateAction.bind(t),signMessage:t.signMessage.bind(t),sendDelegateAction:t.sendDelegateAction.bind(t),signAndSendDelegateAction:t.signAndSendDelegateAction.bind(t)}}function SO(){}var CO=class{constructor(e){this.deps=e}async signAndSendTransaction(e){let t;try{t=await this.deps.currentWallet.nearSubject(e),KT(this.deps.configs,{capabilityKind:Mt.nearEd25519MpcSigning,operationKind:jt.signTransaction})}catch(e){return ft(e,`not_submitted`)}return this.deps.commands.signAndSendTransaction({...e,...t,options:e.options??{}})}async signTransaction(e){let t={...e,...await this.deps.currentWallet.nearSubject(e),options:e.options??{}};return KT(this.deps.configs,{capabilityKind:Mt.nearEd25519MpcSigning,operationKind:jt.signTransaction}),await this.deps.commands.signTransaction(t)}async sendTransaction(e){let t;try{t=await this.deps.currentWallet.nearSubject(e)}catch(e){return ft(e,`not_submitted`)}return this.deps.commands.sendTransaction({...e,...t,options:e.options??{}})}async signDelegateAction(e){let t={...e,...await this.deps.currentWallet.nearSubject(e),options:e.options??{}};return KT(this.deps.configs,{capabilityKind:Mt.nearEd25519MpcSigning,operationKind:jt.signDelegateAction}),await this.deps.commands.signDelegateAction(t)}async signMessage(e){let t={...e,...await this.deps.currentWallet.nearSubject(e),options:e.options??{}};return KT(this.deps.configs,{capabilityKind:Mt.nearEd25519MpcSigning,operationKind:jt.signNep413Message}),await this.deps.commands.signMessage(t)}async sendDelegateAction(e){return await yO({url:`${e.relayerUrl.replace(/\/+$/,``)}${(this.deps.configs.network.relayer?.routes?.delegateAction||`/signed-delegate`).replace(/^\/?/,`/`)}`,payload:{hash:e.hash,signedDelegate:e.signedDelegate},auth:gO(this.deps.configs),signal:e.signal,options:e.options})}async signAndSendDelegateAction(e){let t={...e,...await this.deps.currentWallet.nearSubject(e),options:e.options??{}},n={signerSlot:t.options.signerSlot,onEvent:t.options.onEvent,onError:t.options.onError,waitUntil:t.options.waitUntil,confirmationConfig:t.options.confirmationConfig,confirmerText:t.options.confirmerText,afterCall:SO},r;try{r=await this.signDelegateAction({walletSession:t.walletSession,nearAccount:t.nearAccount,delegate:t.delegate,options:n})}catch(e){let n=I(e);throw await t.options?.afterCall?.(!1,void 0,n),n}let i={onEvent:t.options.onEvent,onError:t.options.onError},a;try{a=await this.sendDelegateAction({relayerUrl:t.relayerUrl,hash:r.hash,signedDelegate:r.signedDelegate,signal:t.signal,options:i})}catch(e){let n=I(e);throw await t.options?.afterCall?.(!1,void 0,n),n}let o={signResult:r,relayResult:a};if(a.ok!==!1)await t.options?.afterCall?.(!0,o);else{let e=I(a.error||`Delegate relay failed`);await t.options?.afterCall?.(!1,void 0,e)}return o}};function wO(e){let t=new TO(e);return{signAndSendTransaction:e.signAndSendTransaction,advanced:e.advanced,signTransaction:t.signTransaction.bind(t)}}var TO=class{constructor(e){this.deps=e}async signTransaction(e){let t=QT(this.deps.configs.network.chains,e.chainTarget),n=await this.deps.currentWallet.walletSession(e.walletSession);KT(this.deps.configs,{capabilityKind:Mt.evmEcdsaMpcSigning,operationKind:kt.signTransaction,chainTarget:t});let r=await this.deps.commands.signEvmFamily({walletSession:n,request:e.request,chainTarget:t,options:e.options});if(r.chain!==`evm`||r.kind!==`eip1559`)throw Error(`[EVM capability] expected EVM result, received ${r.chain}`);return r}};function EO(e,t){let n=e.tx.chainId;if(n!==void 0&&Number(n)!==t.chainId)throw Error(`[evm-family] request tx.chainId ${n} does not match chain target ${H(t)}`);return{...e,tx:{...e.tx,chainId:t.chainId}}}const DO=5e3;function OO(e,t,n){try{e?.(Xi({...n,flowId:`signing:evm_family:${t}:${n.phase}`,accountId:t}))}catch{}}function kO(){let e=Error(`Request cancelled`);return e.code=`cancelled`,e}function AO(e){let t=Error(e);return t.code=`timeout`,t}async function jO(e){let t=Math.max(1,Math.floor(Number(e.timeoutMs)||0)),n=null,r=!1;try{return await new Promise((i,a)=>{n=setTimeout(()=>{if(!r){r=!0;try{e.onTimeout?.()}catch{}a(AO(e.message))}},t),e.promise.then(e=>{r||(r=!0,n&&clearTimeout(n),i(e))},e=>{r||(r=!0,n&&clearTimeout(n),a(e))})})}finally{n&&clearTimeout(n)}}function MO(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?DO:Math.min(DO,Math.max(250,t))}function NO(e){if(typeof e==`function`&&e())throw kO()}function PO(e){return String(e||``).trim().toLowerCase().replace(/[\s-]+/g,`_`)}function FO(e,t){return!e||typeof e!=`object`?!1:PO(e.code)===PO(t)}function IO(e){if(e instanceof Error){let t=String(e.code||``).trim(),n=`details`in e?e.details:void 0;return{...t?{code:t}:{},message:e.message,...n===void 0?{}:{details:n}}}if(e&&typeof e==`object`){let t=e,n=String(t.code||``).trim(),r=String(t.message||``).trim();return{...n?{code:n}:{},message:r||String(e),...t.details===void 0?{}:{details:t.details}}}return{message:String(e||`unknown error`)}}function LO(e){let t=PO(e instanceof Error||e&&typeof e==`object`&&`message`in e?e.message:e);return t.includes(`nonce_lane_blocked`)||t.includes(`nonce lane blocked`)}function RO(e){return!e||typeof e!=`object`||!FO(e,`tx_dropped_or_replaced`)?null:PO(e.reason)===`replaced`?`replaced`:`dropped`}function zO(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]*$/.test(t)?t:null}function BO(e){return String(e??``).trim()||null}function VO(e){let t=BO(e);return t?t.toLowerCase():null}function HO(e){throw Error(`[Tempo capability] unhandled finalized payload branch: ${String(e)}`)}function UO(e,t){let n=zO(e);if(!n)throw Error(`[Tempo capability] invalid ${t} payload input`);return n}function WO(e){return{kind:`evm_eip1559`,to:e.tx.to??null,input:UO(e.tx.data||`0x`,`EVM`)}}function GO(e){return{to:e.to,input:UO(e.input||`0x`,`Tempo call`)}}function KO(e){let[t,...n]=e.tx.calls;if(!t)throw Error(`[Tempo capability] Tempo transaction has no calls`);return{kind:`tempo_eip2718_calls`,calls:[GO(t),...n.map(GO)]}}function qO(e){switch(e.chain){case`evm`:return WO(e);case`tempo`:return KO(e);default:return HO(e)}}function JO(e){return e.input??e.data??null}function YO(e){return Array.isArray(e.calls)?{kind:`tempo_eip2718_calls`,calls:e.calls.map(e=>({to:e?.to??null,input:e?JO(e):null,data:e?.data??null}))}:{kind:`evm_eip1559`,to:e.to??null,input:e.input??null}}function XO(e){return VO(e.observed.to)===VO(e.expected.to)&&zO(e.observed.input)===zO(e.expected.input)}function ZO(e){return VO(e.observed.to)===VO(e.expected.to)&&zO(JO(e.observed))===zO(e.expected.input)}function QO(e){return e.observed.calls.length===e.expected.calls.length?e.expected.calls.every((t,n)=>{let r=e.observed.calls[n];return r?ZO({expected:t,observed:r}):!1}):!1}function $O(e){switch(e.expected.kind){case`evm_eip1559`:return e.observed.kind===`evm_eip1559`?XO({expected:e.expected,observed:e.observed}):!1;case`tempo_eip2718_calls`:return e.observed.kind===`tempo_eip2718_calls`?QO({expected:e.expected,observed:e.observed}):!1;default:return HO(e.expected)}}function ek(e){let t=H(e.chainTarget),n=e.chains.filter(e=>{let n=qe(e.network);return n!==`evm`&&n!==`tempo`?!1:H(Sn(e))===t});if(n.length===1){let e=String(n[0].rpcUrl||``).trim();if(!e)throw Error(`[Tempo capability] missing rpcUrl for ${n[0].network} ${t}`);return e}if(n.length>1){let e=n.map(e=>e.network).join(`, `);throw Error(`[Tempo capability] ambiguous RPC routing for ${t} across [${e}]`)}throw Error(`[Tempo capability] unable to resolve RPC URL for ${t}`)}function tk(e){let t=String(e?.managedNonce?.sender||``).trim(),n=/^0x[0-9a-fA-F]{40}$/.test(t)?t:void 0,r;try{let t=String(e?.managedNonce?.nonce||``).trim();if(t){let e=BigInt(t);e>=0n&&(r=e)}}catch{}return{...n?{managedNonceSenderAddress:n}:{},...typeof r==`bigint`?{nonceHint:r}:{}}}async function nk(e){let t=await Sf({rpcUrl:e.rpcUrl}).getTransactionByHash({txHash:e.txHash}).catch(()=>null);if(!t)return{kind:`tx_unavailable`,expected:e.expected};let n=YO(t);return $O({expected:e.expected,observed:n})?{kind:`matched`,expected:e.expected,observed:n}:{kind:`mismatch`,expected:e.expected,observed:n}}async function rk(e){if(!e.broadcastAccepted){await e.lifecycle.reportBroadcastRejected({walletSession:e.walletSession,signedResult:e.signedResult,error:e.error,options:{onEvent:e.onEvent}});return}let t=RO(e.error);if(t){await e.lifecycle.reportDroppedOrReplaced({walletSession:e.walletSession,signedResult:e.signedResult,reason:t,...e.txHash?{txHash:e.txHash}:{},options:{onEvent:e.onEvent}});return}try{await e.lifecycle.reconcileNonceLane({walletSession:e.walletSession,signedResult:e.signedResult,options:{onEvent:e.onEvent}})}catch(t){if(FO(t,`nonce_lane_blocked`)||LO(t)){await e.lifecycle.reportDroppedOrReplaced({walletSession:e.walletSession,signedResult:e.signedResult,reason:`dropped`,...e.txHash?{txHash:e.txHash}:{},options:{onEvent:e.onEvent}});return}throw t}}function ik(e){let t=String(e||``).trim();if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw Error(`[Tempo capability] invalid transaction hash from broadcast: ${t||`empty`}`);return t}function ak(e){let t=String(e||``).trim();if(!/^0x[0-9a-fA-F]+$/.test(t))throw Error(`[Tempo capability] signed rawTxHex is missing or invalid`);return t}function ok(e){return e.payloadExpectation??qO(e.request)}async function sk(e){let t=e.input.options?.onEvent,n=V(e.input.walletSession.walletId);NO(e.input.options?.shouldAbort);let r=null,i,a=!1,o=!1,s=e=>OO(t,n,e),c=e=>{if(e.phase!==W.STEP_15_COMPLETED)try{t?.(e)}catch{}};try{let n=e.input.request,l=ek({chains:e.chains,chainTarget:e.input.chainTarget}),u=Sf({rpcUrl:l});r=await e.lifecycle.signEvmFamily({walletSession:e.input.walletSession,request:n,chainTarget:e.input.chainTarget,options:e.input.options?{...e.input.options.voiceId===void 0?{}:{voiceId:e.input.options.voiceId},...e.input.options.confirmationConfig?{confirmationConfig:e.input.options.confirmationConfig}:{},...e.input.options.shouldAbort?{shouldAbort:e.input.options.shouldAbort}:{},...t?{onEvent:c}:{}}:void 0}),NO(e.input.options?.shouldAbort),s({phase:W.STEP_12_BROADCAST_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let d=ak(r.rawTxHex);e.lifecycle.onBroadcastStarted({walletSession:e.input.walletSession,signedResult:r}),i=ik(await u.request({method:`eth_sendRawTransaction`,params:[d]})),await e.lifecycle.reportBroadcastAccepted({walletSession:e.input.walletSession,signedResult:r,txHash:i,options:{...t?{onEvent:t}:{}}}),a=!0,s({phase:W.STEP_13_NONCE_RECONCILE_STARTED,status:`running`,message:`Waiting for transaction finalization`,interaction:{kind:`none`,overlay:`none`},data:{txHash:i}});let f=new AbortController,p=null;typeof e.input.options?.shouldAbort==`function`&&(p=setInterval(()=>{e.input.options?.shouldAbort?.()&&f.abort(kO())},100));let m=Math.max(1,Math.floor(Number(e.input.finalization?.timeoutMs??9e4)||0)),h=Math.max(1,Math.floor(Number(e.input.finalization?.pollIntervalMs??1250)||0)),g=Math.max(1,Math.floor(Number(e.input.finalization?.confirmations??1)||0)),_=tk(r),v=await jO({promise:u.waitForTransactionReceipt({txHash:i,timeoutMs:m,pollIntervalMs:h,confirmations:g,maxFeePerGasHint:n.tx.maxFeePerGas,signal:f.signal,..._.managedNonceSenderAddress?{transactionSenderAddress:_.managedNonceSenderAddress}:{},...typeof _.nonceHint==`bigint`?{nonceHint:_.nonceHint}:{}}).finally(()=>{p&&=(clearInterval(p),null),f.abort(Error(`finalization wait settled`))}),timeoutMs:m+2e3,message:`Timed out waiting for transaction finalization after ${m.toString()}ms`,onTimeout:()=>{f.abort(AO(`Transaction finalization watchdog timed out`))}}),y=Cf(v.status,`receipt.status`);if(y===0n){await e.lifecycle.reportFinalized({walletSession:e.input.walletSession,signedResult:r,txHash:i,receiptStatus:`reverted`,options:{...t?{onEvent:t}:{}}}),o=!0;let n=Error(`Transaction reverted with receipt status ${String(v.status||`unknown`)}`);throw n.code=`tx_reverted`,n.txHash=i,n}if(y!==1n)throw Error(`Unexpected transaction receipt status ${v.status}`);let b=ok(e.input),x=await nk({rpcUrl:l,txHash:i,expected:b});if(x.kind===`mismatch`){let e=Error(`Finalized transaction payload mismatch for ${i}.`);throw e.code=`tx_payload_mismatch`,e.details=x,e}if(await e.lifecycle.reportFinalized({walletSession:e.input.walletSession,signedResult:r,txHash:i,receiptStatus:`success`,options:{...t?{onEvent:t}:{}}}),o=!0,s({phase:W.STEP_13_RECEIPT_FINALIZED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{txHash:i}}),typeof e.input.postFinalizationCheck==`function`){s({phase:W.STEP_14_APP_STATE_SYNC_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`},data:{txHash:i}});try{await e.input.postFinalizationCheck()}catch(e){let t=e instanceof Error?e.message:String(e||``),n=Error(`Post-finalization state verification failed for ${i}: ${t||`unknown error`}`);throw n.code=`post_finalization_state_mismatch`,n.txHash=i,n.details={...e instanceof Error&&e.message?{message:e.message}:{},originalError:e},n}s({phase:W.STEP_14_APP_STATE_SYNC_SUCCEEDED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{txHash:i}})}return s({phase:W.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`execute`,txHash:i}}),{txHash:i,signedResult:r,payloadVerification:x}}catch(s){try{let t=r?a?o?`post_finalization`:`finalization`:`broadcast`:`sign`;console.warn(`[EvmFamilyLifecycle][failure]`,{stage:t,walletId:n,requestChain:e.input.request.chain,requestKind:e.input.request.kind,requestChainId:e.input.request.tx.chainId,chainTarget:e.input.chainTarget,signed:!!r,...r?.managedNonce?{managedNonce:{chain:r.managedNonce.chainTarget.kind,networkKey:r.managedNonce.chainTarget.networkSlug,chainId:r.managedNonce.chainTarget.chainId,sender:r.managedNonce.sender,nonce:r.managedNonce.nonce.toString(),...r.managedNonce.nonceKey==null?{}:{nonceKey:r.managedNonce.nonceKey.toString()}}}:{},broadcastAccepted:a,finalizedReported:o,...i?{txHash:i}:{},error:IO(s)})}catch{}throw!o&&r&&await jO({promise:rk({lifecycle:e.lifecycle,walletSession:e.input.walletSession,signedResult:r,error:s,broadcastAccepted:a,...i?{txHash:i}:{},...t?{onEvent:t}:{}}),timeoutMs:MO(e.input.finalization?.timeoutMs),message:`Timed out during best-effort nonce cleanup after EVM-family signing failure`}).catch(()=>null),s}}function ck(e,t){return ek({chains:e,chainTarget:t})}async function lk(e,t){return await bD({rpcUrl:ck(e,t.chainTarget),account:dD(`account address`,t.account),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}})}async function uk(e,t){return await xD({rpcUrl:ck(e,t.chainTarget),feeToken:dD(`fee token address`,t.feeToken),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}})}async function dk(e){let t=await bD(e);if(t?.toLowerCase()!==e.feeToken.toLowerCase())throw Error(`[Tempo capability] fee-token preference mismatch: expected ${e.feeToken}, received ${t??`unset`}`)}async function fk(e,t){let n=ck(e.chains,t.chainTarget),r=dD(`account address`,t.account),i=dD(`fee token address`,t.feeToken),a=await xD({rpcUrl:n,feeToken:i});if(a.kind===`invalid`)throw Error(`[Tempo capability] invalid fee token: ${a.reason}`);let o=SD({chainId:t.chainTarget.chainId,feeToken:i,maxPriorityFeePerGas:t.feeCaps.maxPriorityFeePerGas,maxFeePerGas:t.feeCaps.maxFeePerGas,gasLimit:t.gasLimit??1000000n});return await e.execute({walletSession:t.walletSession,chainTarget:t.chainTarget,request:o,payloadExpectation:{kind:`evm_eip1559`,to:o.tx.to??null,input:o.tx.data??`0x`},...t.finalization?{finalization:t.finalization}:{},...t.options?{options:t.options}:{},postFinalizationCheck:dk.bind(null,{rpcUrl:n,account:r,feeToken:i})})}function pk(e){let t=new mk(e),n=e.commands,r={reportBroadcastAccepted:n.reportBroadcastAccepted,reportBroadcastRejected:n.reportBroadcastRejected,reportFinalized:n.reportFinalized,reportDroppedOrReplaced:n.reportDroppedOrReplaced,reconcileNonceLane:n.reconcileNonceLane},i=t.signTempo.bind(t),a=t.executeEvmFamilyTransaction.bind(t);return{tempo:{signTransaction:i,signAndSendTransaction:a,advanced:r,getFeeToken:lk.bind(null,e.configs.network.chains),validateFeeToken:uk.bind(null,e.configs.network.chains),setFeeToken:fk.bind(null,{chains:e.configs.network.chains,execute:a})},evm:wO({...e,advanced:r,signAndSendTransaction:a})}}var mk=class{constructor(e){this.deps=e}async signEvmFamily(e){let t=XT(this.deps.configs.network.chains,e.chainTarget),n=await this.deps.currentWallet.walletSession(e.walletSession);return KT(this.deps.configs,{capabilityKind:Mt.evmEcdsaMpcSigning,operationKind:kt.signTransaction,chainTarget:t}),await this.deps.commands.signEvmFamily({walletSession:n,chainTarget:t,request:e.request,options:e.options})}async signTempo(e){let t=await this.signEvmFamily({...e,chainTarget:ZT(this.deps.configs.network.chains,e.chainTarget)});if(t.chain!==`tempo`||t.kind!==`tempoTransaction`)throw Error(`[Tempo capability] expected Tempo result, received ${t.chain}`);return t}async executeEvmFamilyTransaction(e){let t=XT(this.deps.configs.network.chains,e.chainTarget),n=await this.deps.currentWallet.walletSession(e.walletSession);return await sk({lifecycle:{...this.deps.commands,signEvmFamily:this.signEvmFamily.bind(this)},chains:this.deps.configs.network.chains,input:{...e,chainTarget:t,walletSession:n,request:EO(e.request,t)}})}};function hk(e){let t=e.auth,n=rO(e.devices),r=nO({getWalletSession:t.getSession}),i={createNearCommands:e.createNearCommands,createEvmFamilyCommands:e.createEvmFamilyCommands,nearClient:e.nearClient,configs:e.configs,currentWallet:r},a=xO({...i,commands:e.createNearCommands({kind:`ordinary`})}),o=e.createEvmFamilyCommands({kind:`ordinary`}),s=pk({...i,commands:o});return{preferences:e.preferences,auth:t,registration:{getNearAccountState:e.registration.getNearAccountState,onNearAccountChange:e.registration.onNearAccountChange,waitForNearAccount:$D.bind(null,e.registration),addSigner:e.registration.addSigner,addPasskey:e.registration.addPasskey,activateAuthMethod:e.registration.activateAuthMethod,getAuthMethodAvailability:e.registration.getAuthMethodAvailability,setAuthMethodEnabled:e.registration.setAuthMethodEnabled,addEmail:e.registration.addEmail,removeAuthMethod:e.registration.removeAuthMethod,registerOwnerWallet:_k.bind(null,e.registration),registerWallet:gk.bind(null,e.registration,e.configs)},recovery:e.recovery,devices:n,keys:eE({configs:e.configs,currentWallet:r,domain:e.keys}),near:a,tempo:s.tempo,evm:s.evm}}async function gk(e,t,n){let r;try{let e=n.wallet===void 0?{kind:`server_allocated`}:n.wallet,i=n.signerSelection===void 0?zo({configs:t,wallet:e,options:n.options??{}}):n.signerSelection;r={completion:`wallet_session`,authMethod:n.authMethod,wallet:e,signerSelection:i,options:n.options}}catch(e){let t=I(e);throw await n.options?.onError?.(t),await n.options?.afterCall?.(!1,void 0,t),t}return e.registerWallet(r)}async function _k(e,t){return await e.registerWallet({completion:`owner_operations`,authMethod:t.authMethod,wallet:t.wallet??{kind:`server_allocated`},signerSelection:t.signerSelection,options:t.options})}async function vk(e){let t=(await K.listWalletAuthMethodsV2ForWallet(String(e.walletId))).filter(t=>t.kind===R.passkey&&t.status===`active`&&t.walletId===e.walletId&&String(t.rpId)===e.rpId&&String(t.credentialIdB64u)===e.credentialIdB64u),[n]=t;return t.length!==1||!n||n.kind!==R.passkey?null:await U({authority:{walletId:n.walletId,factor:{kind:R.passkey,credentialIdB64u:n.credentialIdB64u},verifier:{kind:`webauthn`,rpId:n.rpId},bindingId:n.walletAuthMethodId}})}async function yk(e){let{identity:t}=e;if(t.auth.kind!==R.passkey)throw J(`binding_mismatch`);let n=await K.resolveSelectedWalletAuthority(String(e.walletId));if(n.kind!==`resolved`||n.selection.walletId!==e.walletId||n.authMethod.kind!==R.passkey||String(n.authMethod.rpId)!==String(t.auth.rpId)||n.authMethod.credentialIdB64u!==t.auth.credentialIdB64u)throw J(`binding_mismatch`);bk(e.access,n);let r=await Th({selected:{authMethod:n.authMethod,authority:n.authority},operation:{kind:`near_sign`,operation:`sign`,keyFamily:`ed25519`}});if(r.kind!==`resolved`)throw J(`missing_capability`);let i=await vk({walletId:e.walletId,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u});if(!i||i.walletAuthMethodId!==n.authMethod.walletAuthMethodId)throw J(`binding_mismatch`);let a=await ic({store:K,walletId:String(e.walletId),nearAccountId:String(t.signer.account.nearAccountId),nearEd25519SigningKeyId:String(t.signer.nearEd25519SigningKeyId),signerSlot:t.signer.signerSlot,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u,authority:i});if(a.kind!==`available`)throw J(`missing_runtime`);if(!g(a.locator.materialActivation,r.value.materialActivation))throw J(`binding_mismatch`);let o=a.locator.stableServerScope,s=Pe(o.runtimePolicyScope);if(!s.signingRootVersion)throw J(`binding_mismatch`);let c={walletId:String(e.walletId),nearAccountId:String(t.signer.account.nearAccountId),nearEd25519SigningKeyId:String(t.signer.nearEd25519SigningKeyId),thresholdSessionId:String(t.thresholdSessionId),signerSlot:t.signer.signerSlot,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u,signingRootId:s.signingRootId,signingRootVersion:s.signingRootVersion,signingWorkerId:o.routerAbNormalSigning.signingWorkerId},l={kind:`available`,walletId:c.walletId,nearAccountId:c.nearAccountId,signerSlot:c.signerSlot,materialActivation:a.locator.materialActivation},u=await xk({store:K,identity:c,authority:i,publicLocator:l});if(u.kind===`blocked`)throw Mf(u.plan.reason);return{prepared:u,localIdentity:c,authority:i,publicLocator:l,facts:{thresholdSessionId:t.thresholdSessionId,signer:t.signer,signingRootId:s.signingRootId,signingRootVersion:s.signingRootVersion,routerAbNormalSigning:o.routerAbNormalSigning,runtimePolicyScope:o.runtimePolicyScope,relayerUrl:e.relayerUrl},participantIds:o.participantIds}}function bk(e,t){switch(e.kind){case`wallet_session`:if(t.selection.lockState!==`unlocked`)throw J(`binding_mismatch`);return;case`owner_operation`:if(e.assertCurrent(),t.authority.state!==`active`||t.authority.authorityId!==e.authority.authorityId||t.authority.revocationEpoch!==e.authority.revocationEpoch||t.authMethod.status!==`active`||t.authMethod.walletAuthMethodId!==e.authMethod.walletAuthMethodId||t.authMethod.walletId!==e.authMethod.walletId)throw J(`binding_mismatch`);return;default:throw Error(`Unsupported passkey material access`)}}async function xk(e){try{return await Qo(e)}catch{throw J(`binding_mismatch`)}}async function Sk(e){try{return await xs(e)}catch{throw J(`corrupt`)}}function Ck(e){return e.laneIdentity===void 0?e.materialIdentity:{kind:`near_ed25519_material_identity`,signer:e.laneIdentity.signer,auth:e.laneIdentity.auth,thresholdSessionId:e.laneIdentity.thresholdSessionId}}function wk(e){return Ck(e).signer}function Tk(e){return String(Ck(e).thresholdSessionId)}function Ek(e){let t=e.material.facts,n=e.material.activeClient.metadata(),r=Tk(e.input),i=wk(e.input),a=t.signer;if(String(t.thresholdSessionId)!==r)throw Error(`[SigningEngine][near] active Ed25519 Yao capability session mismatch`);if(n.scope.threshold_session_id!==String(t.thresholdSessionId))throw Error(`[SigningEngine][near] active Ed25519 Yao metadata session mismatch`);if(n.scope.account_id!==String(e.input.walletId)||n.applicationBinding.wallet_id!==String(e.input.walletId))throw Error(`[SigningEngine][near] active Ed25519 Yao capability subject mismatch`);if(String(a.account.wallet.walletId)!==String(i.account.wallet.walletId)||String(a.account.nearAccountId)!==String(i.account.nearAccountId)||a.signerSlot!==i.signerSlot||String(a.nearEd25519SigningKeyId)!==String(i.nearEd25519SigningKeyId))throw Error(`[SigningEngine][near] active Ed25519 Yao capability signer mismatch`);let o=fo(n);if(!g(e.expectedActivation,o))throw Error(`[SigningEngine][near] active Ed25519 Yao capability activation mismatch`);return e.material}async function Dk(e,t){let n=await K.resolveSelectedWalletAuthority(String(e.input.walletId));if(n.kind!==`resolved`||(bk(e.access,n),String(t.rawId||t.id||``).trim()!==e.credentialIdB64u))throw J(`binding_mismatch`);let r=ff({credential:t,rpId:e.rpId}),i=await Sk({store:K,identity:e.identity,authority:e.authority,publicLocator:e.publicLocator,unlockSource:{kind:`available`,passkeyPrfFirstB64u:r.secretSource.prfFirstB64u},liveMaterial:null});if(i.kind===`blocked`)throw Mf(i.plan.reason);if(i.kind!==`rehydrated`)throw J(`corrupt`);if(!g(e.materialActivation,i.plan.materialActivation))throw i.activeClient.dispose(),J(`binding_mismatch`);let a={activeClient:i.activeClient,facts:e.facts};try{let t=await K.resolveSelectedWalletAuthority(String(e.input.walletId));if(t.kind!==`resolved`)throw J(`binding_mismatch`);return bk(e.access,t),Ek({material:a,input:e.input,expectedActivation:e.materialActivation})}catch{throw a.activeClient.dispose(),J(`binding_mismatch`)}}async function Ok(e,t,n){n.assertCurrent();let r=await K.resolveSelectedWalletAuthority(String(n.walletId));if(r.kind!==`resolved`||r.authMethod.kind!==`passkey`||r.authMethod.status!==`active`||r.authority.state!==`active`||r.authMethod.walletId!==n.walletId||r.authority.walletId!==n.walletId||r.authMethod.walletAuthorityId!==r.authority.authorityId)throw Error(`Enroll a wallet-origin owner passkey on this device before approving a transaction.`);let i={kind:`owner_operation`,authMethod:r.authMethod,authority:r.authority,assertCurrent:n.assertCurrent},a=[];for(let e of await t.listLanes())e.walletId===n.walletId&&e.nearAccountId===n.nearAccountId&&e.auth.kind===`passkey`&&String(e.auth.rpId)===String(r.authMethod.rpId)&&e.auth.credentialIdB64u===r.authMethod.credentialIdB64u&&r.authority.signerActivations.ed25519!==void 0&&g(e.materialActivation,r.authority.signerActivations.ed25519.materialActivation)&&a.push({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,thresholdSessionId:e.thresholdSessionId,runtimePolicyScope:e.runtimePolicyScope,materialActivation:e.materialActivation,auth:e.auth});let[o]=a;if(a.length!==1||!o)throw Error(`The wallet has no exact owner signing material on this device.`);let s=new Ak(n,i,o,e.getSignerWorkerContext);return{nearRpcUrl:e.nearRpcUrl,touchConfirm:e.touchConfirm,resolveOwnerLaneScope:s.resolveOwnerLaneScope.bind(s),prepareNearEd25519YaoMaterialBoundary:s.prepareMaterial.bind(s),signingSessionCoordinator:e.signingSessionCoordinator,readAvailableSigningLanesForSigning:s.readLanes.bind(s),createSigningSessionId:kk.bind(null,n.operationId,e.createSigningSessionId),getSignerWorkerContext:s.workerContext.bind(s),withThresholdEd25519CommitQueue:e.withThresholdEd25519CommitQueue}}function kk(e,t,n){return n===`near-transaction-sign`?e:t(n)}var Ak=class{constructor(e,t,n,r){this.input=e,this.access=t,this.lane=n,this.getContext=r}workerContext(){return{...this.getContext(),resolveOperationStepUpCredential:this.ownerCredential.bind(this)}}async ownerCredential(e){await this.assertCurrent();let t=e.proof;if(e.walletId!==this.input.walletId||t.kind!==`passkey`||t.authority.bindingId!==this.access.authMethod.walletAuthMethodId||t.authority.factor.credentialIdB64u!==this.access.authMethod.credentialIdB64u||String(t.authority.verifier.rpId)!==String(this.access.authMethod.rpId))throw Error(`The operation owner proof changed.`);return{kind:`operation_step_up`}}async resolveOwnerLaneScope(e){if(e!==this.input.walletId)throw Error(`The approval wallet changed.`);await this.assertCurrent();let t=Ai(this.lane.signerSlot,{min:1});if(t===null)throw Error(`The owner signer slot is invalid.`);return Yp({authMethod:this.access.authMethod,signerSlot:t})}async assertCurrent(){this.input.assertCurrent();let e=await K.resolveSelectedWalletAuthority(String(this.input.walletId));if(e.kind!==`resolved`)throw Error(`The selected wallet owner changed.`);bk(this.access,e)}async readLanes(e){if(await this.resolveOwnerLaneScope(this.input.walletId),String(e.walletId)!==String(this.input.walletId))throw Error(`The approval wallet changed.`);let t={auth:this.lane.auth,curve:`ed25519`,chain:`near`,materialActivation:this.lane.materialActivation,walletId:this.lane.walletId,nearAccountId:this.lane.nearAccountId,nearEd25519SigningKeyId:this.lane.nearEd25519SigningKeyId,signerSlot:this.lane.signerSlot,thresholdSessionId:this.lane.thresholdSessionId,source:`public_capability_reference`,state:`deferred`,authorizationState:`authorization_required`};return{walletId:this.input.walletId,generation:this.access.authority.updatedAtMs,ecdsa:{targets:[],lanesByTarget:{},candidatesByTarget:{}},lanes:{ed25519:{near:t}},candidates:{ed25519:{near:[t]}}}}async prepareMaterial(e){await this.assertCurrent();let t=Ck(e);this.assertIdentity(t);let n=await yk({walletId:this.input.walletId,identity:t,relayerUrl:this.input.relayerUrl,access:this.access});return{preparation:gl({hydration:n.prepared.plan,requirement:this.lane.auth}),executor:{resolveSigningKeyMaterial:this.resolveKeyMaterial.bind(this,n),preparePasskeyOperationStepUp:this.prepareStepUp.bind(this,e,n),resolve:jk,resolveWalletSessionState:jk,resolveFundingSession:jk,prepareEmailOtpOperationStepUp:jk}}}assertIdentity(e){let t=e.signer;if(t.account.wallet.walletId!==this.lane.walletId||t.account.nearAccountId!==this.lane.nearAccountId||t.nearEd25519SigningKeyId!==this.lane.nearEd25519SigningKeyId||t.signerSlot!==this.lane.signerSlot||String(e.thresholdSessionId)!==String(this.lane.thresholdSessionId)||e.auth.kind!==`passkey`||e.auth.rpId!==this.lane.auth.rpId||e.auth.credentialIdB64u!==this.lane.auth.credentialIdB64u)throw Error(`The approved signing identity changed.`)}async resolveKeyMaterial(e){await this.assertCurrent();let t=await Th({selected:{authMethod:this.access.authMethod,authority:this.access.authority},operation:{kind:`near_sign`,operation:`sign`,keyFamily:`ed25519`}});if(t.kind!==`resolved`||t.value.keyFamily!==`ed25519`||!g(t.value.materialActivation,this.lane.materialActivation))throw Error(`The owner cannot approve this signing material.`);let[n,r]=e.participantIds;if(n===void 0||r===void 0)throw Error(`The signing participants are invalid.`);return{nearAccountId:this.input.nearAccountId,signerSlot:this.lane.signerSlot,kind:`threshold_ed25519_v1`,publicKey:`ed25519:${tn(F(t.value.registeredPublicKeyB64u))}`,relayerKeyId:e.facts.routerAbNormalSigning.signingWorkerId,keyVersion:da,participants:ce({clientParticipantId:n,relayerParticipantId:r,relayerKeyId:e.facts.routerAbNormalSigning.signingWorkerId,clientShareDerivation:`prf_first_v1`}),timestamp:this.access.authority.activatedAtMs}}async prepareStepUp(e,t){return await this.assertCurrent(),{materialActivation:t.prepared.plan.materialActivation,facts:t.facts,participantIds:t.participantIds,rehydrate:Dk.bind(null,{input:e,access:this.access,identity:t.localIdentity,facts:t.facts,authority:t.authority,rpId:this.lane.auth.rpId,credentialIdB64u:this.lane.auth.credentialIdB64u,publicLocator:t.publicLocator,materialActivation:t.prepared.plan.materialActivation})}}};async function jk(){throw Error(`A fresh owner operation cannot use reusable signing authority.`)}async function Mk(e){let{walletSession:t,custodyEnvelope:n,signal:r}=e;r.throwIfAborted();let i=await K.getWalletAuthMethodV2(t.authMethodId),a=await K.getWalletAuthority(t.authorityId);if(!i||i.kind!==`voiceid`||i.status!==`active`||i.walletId!==t.walletId||i.walletAuthorityId!==t.authorityId||!a||a.state!==`active`||a.walletId!==t.walletId||a.authorityDigestB64u!==t.authorityDigestB64u||a.revocationEpoch!==t.authorityRevocationEpoch||n.walletId!==t.walletId||n.ownership.walletAuthMethodId!==i.walletAuthMethodId||n.factor.kind!==`voiceid`||n.factor.deviceKeyId!==i.deviceKeyId)throw Error(`Wallet Session, device method, and custody do not match.`);return{method:i,authority:a,ref:await U({authority:si({walletId:i.walletId,walletAuthMethodId:i.walletAuthMethodId,deviceKeyId:i.deviceKeyId})})}}async function Nk(e){let{walletSession:t,operationCredential:n,custodyEnvelope:r,near:i,signal:a}=e.unlocked;if(a.aborted)throw Error(`Wallet unlock was cancelled.`);if(i.kind!==`ready`)throw Error(`This wallet has no active NEAR signer.`);let{method:o,authority:s,ref:c}=e.identity,l=i.capability;if(!s.signerActivations.ed25519||!g(s.signerActivations.ed25519.materialActivation,l.materialActivation)||l.applicationBinding.wallet_id!==t.walletId)throw Error(`NEAR capability does not match the Wallet Session authority.`);let u=await e.loadMaterial({nearAccountId:l.nearAccountId,signerSlot:l.applicationBinding.key_creation_signer_slot,expectedRegisteredPublicKeyB64u:P(Uint8Array.from(l.registeredPublicKey))});if(u.kind!==`found`)throw Error(`Unlock with a passkey or Email OTP once to restore NEAR custody on this device.`);if(u.material.binding.walletId!==t.walletId||u.material.binding.nearEd25519SigningKeyId!==l.applicationBinding.near_ed25519_signing_key_id||u.material.binding.signingWorkerId!==l.lifecycle.signingWorkerId||u.material.binding.stateEpoch!==String(l.stateEpoch))throw Error(`Cached NEAR custody belongs to another material activation.`);let d=e.unlocked.factorSecret32.slice(),f=await Po({material:u.material,envelope:Ko(r),ownedFactorSecret:d,activation:{materialActivation:l.materialActivation,lifecycleId:l.lifecycle.lifecycleId,signingRootId:l.applicationBinding.signing_root_id,signingRootVersion:l.lifecycle.rootShareEpoch,signerSetId:l.lifecycle.signerSetId,thresholdSessionId:l.lifecycle.thresholdSessionId,activationTranscriptB64u:P(Uint8Array.from(l.registrationContinuity.activationTranscript)),activationCapabilityBindingB64u:P(Uint8Array.from(l.activeCapabilityBinding))}}).finally(d.fill.bind(d,0));try{if(a.aborted)throw Error(`Wallet unlock was cancelled.`);let r=cs({walletId:t.walletId,nearAccountId:l.nearAccountId,nearEd25519SigningKeyId:l.applicationBinding.near_ed25519_signing_key_id,walletSessionId:n.walletSessionId,authorizationId:t.authorizationId,quotaId:t.quotaId,thresholdSessionId:l.lifecycle.thresholdSessionId,expiresAtMs:t.expiresAtMs,remainingUses:i.remainingUses,runtimePolicyScope:l.runtimePolicyScope,signingRootId:l.applicationBinding.signing_root_id,signingRootVersion:l.lifecycle.rootShareEpoch,routerAbNormalSigning:{kind:Xe,signingWorkerId:l.lifecycle.signingWorkerId},walletSessionToken:n.token,home:n.home,nowMs:Date.now()});if(!r.ok)throw Error(`NEAR Wallet Session is invalid: ${r.reason}`);return{activeClient:f,state:Ls({walletId:t.walletId,nearAccountId:l.nearAccountId,nearEd25519SigningKeyId:Oi(l.applicationBinding.near_ed25519_signing_key_id),signerSlot:l.applicationBinding.key_creation_signer_slot,auth:{kind:`voiceid`,walletAuthMethodId:o.walletAuthMethodId,deviceKeyId:o.deviceKeyId},authority:c,relayerUrl:e.relayerUrl,signingWalletSession:r.value}),capability:l}}catch(e){throw f.dispose(),e}}async function Pk(e,t,n){let r=t.authority.signerActivations.ecdsa;if(!r){if(e.near.kind!==`ready`)throw Error(`This wallet has no active signer.`);return}let i=e.walletSession.capabilitySubjects.filter(Fk);if(i.length!==1||i[0]?.kind!==`sign`||!g(i[0].materialActivation,r.materialActivation))throw Error(`ECDSA material does not belong to this Wallet Session.`);e.signal.throwIfAborted();let a=new ra,o={authority:t.ref,capability:r.materialActivation.capability},s=await a.lookup(o);if(s.kind===`missing`){let e=await a.listActiveWalletCapabilitySubjects(t.method.walletId);if(e.kind!==`resolved`)throw Error(`ECDSA material inventory is unavailable.`);let n=!1;for(let i of e.subjects){if(i.authority.walletAuthMethodId===t.method.walletAuthMethodId)continue;let e=await a.lookup(i);if(e.kind!==`active`||!g(e.manifest.activation.materialActivation,r.materialActivation))continue;let o=await K.getWalletAuthMethodV2(i.authority.walletAuthMethodId);if(!(!o||o.status!==`active`||o.walletAuthorityId!==t.authority.authorityId)){await ko({walletId:t.method.walletId,walletAuthorityId:t.authority.authorityId,sourceWalletAuthMethodId:o.walletAuthMethodId,targetAuthority:t.ref}),n=!0;break}}if(!n)throw Error(`Unlock with a passkey or Email OTP once to restore ECDSA material on this device.`);s=await a.lookup(o)}if(s.kind!==`active`||!g(s.manifest.activation.materialActivation,r.materialActivation))throw Error(`ECDSA material changed during VoiceID unlock.`);if(e.signal.throwIfAborted(),!(await ed({workerCtx:n,authority:t.ref,materialActivation:r.materialActivation})).ok)throw Error(`ECDSA material could not be opened for VoiceID.`);e.signal.throwIfAborted()}function Fk(e){return e.kind===`sign`&&e.keyFamily===`ecdsa_secp256k1`}async function Ik(e,t,n){let r=await Mk(n),i=n.near.kind===`ready`?await Nk({unlocked:n,identity:r,relayerUrl:e.relayerUrl,loadMaterial:e.engine.loadWalletCustodyEd25519Material.bind(e.engine)}):null;try{let a=Lk.bind(null,e,t,n,i,r);return i?await e.engine.withExactEd25519MaterialOwner({materialActivation:i.capability.materialActivation,nearAccountId:i.capability.nearAccountId,task:a}):await a()}catch(e){throw i?.activeClient.dispose(),e}}async function Lk(e,t,n,r,i){let a=n.walletSession.walletId;try{let e=await K.resolveSelectedWalletAuthority(a);if(n.signal.aborted||e.kind!==`resolved`||e.selection.lockGeneration!==t)throw Error(`Wallet lock state changed during unlock.`)}catch(e){throw r?.activeClient.dispose(),e}let o=r?.capability;try{if(await e.engine.clearVolatileWarmSigningMaterial(a),n.signal.aborted)throw Error(`Wallet unlock was cancelled.`);if(await q.writeExactWithOperationCredential({record:n.walletSession,operationCredential:n.operationCredential}),r&&o&&(await e.engine.activateVerifiedNearEd25519YaoMaterial({activeClient:r.activeClient,facts:nc(r.state)}),await e.engine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:a,nearAccountId:o.nearAccountId,nearEd25519SigningKeyId:Oi(o.applicationBinding.near_ed25519_signing_key_id),signerSlot:o.applicationBinding.key_creation_signer_slot,auth:{kind:`voiceid`,walletAuthMethodId:n.walletSession.authMethodId,deviceKeyId:i.method.deviceKeyId},thresholdSessionId:o.lifecycle.thresholdSessionId,runtimePolicyScope:o.runtimePolicyScope,materialActivation:o.materialActivation,expiresAtMs:n.walletSession.expiresAtMs,remainingUses:r.state.remainingUses})),await no(e.transport,{existingEnvelope:n.custodyEnvelope,existingFactorSecret:n.factorSecret32,walletId:a,walletAuthMethodId:n.walletSession.authMethodId,walletSessionId:n.operationCredential.walletSessionId,expiresAtMs:n.walletSession.expiresAtMs}),await Pk(n,i,e.engine.getSignerWorkerContext()),o&&await e.engine.activateAuthenticatedWalletState({walletId:a,nearAccountId:o.nearAccountId,signerSlot:o.applicationBinding.key_creation_signer_slot,nearClient:e.nearClient}),!await za(a,n.walletSession.authMethodId))throw Error(`VoiceID is turned off in this browser.`);if(n.signal.aborted||(await K.markWalletSelectionUnlockedAtGeneration({walletId:a,walletAuthMethodId:n.walletSession.authMethodId,unlockedAtMs:Date.now(),expectedLockGeneration:t}),n.signal.aborted))throw Error(`Wallet unlock was cancelled.`);return r&&e.rememberNearSession(r.state),e.engine.setWalletAuthenticated({kind:`authenticated`,walletId:a,authMethod:`voiceid`}),o?{success:!0,kind:`near_wallet_unlocked`,walletId:a,loggedInNearAccountId:o.nearAccountId,nearAccountId:o.nearAccountId,operationalPublicKey:`ed25519:${tn(Uint8Array.from(o.registeredPublicKey))}`}:{success:!0,kind:`ecdsa_wallet_unlocked`,walletId:a}}catch(t){throw r?.activeClient.dispose(),await e.engine.clearVolatileWarmSigningMaterial(a),await q.clearWallet(a),await e.engine.destroyUnlockedWalletEd25519ExportRootCapabilitiesV1({kind:`wallet_session`,walletSessionId:n.operationCredential.walletSessionId}),e.engine.clearWalletAuthentication(),t}}const Rk=new Map;function zk(e){return typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?null:new Map(Object.entries(e))}function Bk(e,t){let n=e.get(t);if(typeof n==`string`)return n.trim()||void 0}function Vk(e){if(typeof e!=`string`)return null;let t=e.trim().toLowerCase();return t===`none`?`none`:t===`sealed_refresh_v1`?`sealed_refresh_v1`:null}function Hk(e){let t=zk(e);if(!t)return null;let n=Vk(t.get(`mode`));if(!n)return null;if(n===`none`)return{mode:`none`};let r=zk(t.get(`protocol`)),i=r?Bk(r,`algorithm`):void 0,a=r?Bk(r,`groupId`):void 0,o=Bk(t,`currentKeyVersion`);return i!==`shamir3pass-v2`||a!==`rfc2409-group2`||!o?null:{mode:`sealed_refresh_v1`,protocol:{algorithm:et,groupId:Ze},currentKeyVersion:o}}function Uk(e){let t=zk(e);return t&&Hk(zk(t.get(`capabilities`))?.get(`signingSessionSeal`))||{mode:`none`}}function Wk(e){return e.signing.sessionPersistenceMode===`sealed_refresh_v1`?!(e.wallet.mode===`iframe`&&!Kf()):!1}function Gk(e){return[String(e.network.relayer.url||``).trim(),String(e.signing.sessionPersistenceMode||``).trim().toLowerCase(),et,Ze,Kf()?`wallet-host`:`app`,e.wallet.mode].join(`|`)}function Kk(e,t){let n=Number(e);return!Number.isFinite(n)||n<=0?t:Math.max(250,Math.floor(n))}function qk(e,t){let n=Error(e);return n.code=t,n}function Jk(e){if(e.signal?.aborted)throw qk(`Parity check aborted`,`sealed_refresh_parity_aborted`);let t=new AbortController,n=setTimeout(()=>t.abort(`timeout`),e.timeoutMs),r=()=>{try{t.abort(e.signal?.reason)}catch{}};return e.signal?.addEventListener(`abort`,r,{once:!0}),e.task(t.signal).finally(()=>{clearTimeout(n),e.signal?.removeEventListener(`abort`,r)}).catch(e=>{let n=e instanceof Error?e.message:String(e||`Unknown error`);throw t.signal.aborted?qk(`[sealed-refresh-parity] Failed to fetch relayer well-known capabilities: ${n}`,`sealed_refresh_parity_fetch_failed`):e})}async function Yk(e){let t=String(e.relayerUrl||``).trim();if(!t)throw qk(`[sealed-refresh-parity] Missing relayer URL for capability check`,`sealed_refresh_parity_invalid_config`);let n=e.fetchImpl||fetch.bind(globalThis),r=Kk(e.timeoutMs,8e3),i=`${t.replace(/\/+$/,``)}/.well-known/webauthn`;return await Jk({timeoutMs:r,task:async e=>{let t=await n(i,{method:`GET`,headers:{Accept:`application/json`},signal:e});if(!t.ok)throw qk(`[sealed-refresh-parity] Well-known endpoint returned HTTP ${t.status}`,`sealed_refresh_parity_http_error`);let r={};try{r=await t.json()}catch{throw qk(`[sealed-refresh-parity] Well-known response is not valid JSON`,`sealed_refresh_parity_invalid_payload`)}return Uk(r)}})}async function Xk(e){if(!Wk(e.configs))return;let t=Gk(e.configs),n=Rk.get(t);if(n){await n;return}let r=(async()=>{let t=String(e.configs.network.relayer.url||``).trim(),n=e.configs.signing.sessionPersistenceMode,r=await Yk({relayerUrl:t,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs}),i=[];if(r.mode!==n&&i.push(`mode`),r.mode===`sealed_refresh_v1`&&r.protocol.algorithm!==`shamir3pass-v2`&&i.push(`algorithm`),r.mode===`sealed_refresh_v1`&&r.protocol.groupId!==`rfc2409-group2`&&i.push(`groupId`),i.length>0)throw qk(`[sealed-refresh-parity] Client/server mismatch for fields: ${i.join(`, `)}. client={mode:${n},algorithm:${et},groupId:${Ze}} server={mode:${r.mode}${r.mode===`sealed_refresh_v1`?`,algorithm:${r.protocol.algorithm},groupId:${r.protocol.groupId}`:``}}`,`sealed_refresh_parity_mismatch`)})().catch(e=>{throw Rk.delete(t),e});Rk.set(t,r),await r}const Zk={BUILD:{ROOT:`dist`,WORKERS:`dist/workers`,ESM:`dist/esm`,TYPES:`dist/types`},SOURCE:{ROOT:`src`,CORE:`src/core`,STATIC:`src/static`,SIGNING_WORKERS:`src/core/signingEngine/workerManager/workers`,WASM_SIGNER:`../../wasm/near_signer`,ED25519_YAO_CLIENT:`../../crates/router-ab-ed25519-yao-client`,WASM_ECDSA_CLIENT:`../../wasm/router_ab_ecdsa_client`,WASM_EVM_CRYPTO:`../../wasm/evm_crypto`,WASM_TEMPO_SIGNER:`../../wasm/tempo_signer`,WASM_SHAMIR3PASS_RUNTIME:`../../wasm/shamir3pass_runtime`,WASM_EMAIL_OTP_RUNTIME:`../../wasm/email_otp_runtime`,WASM_WALLET_CUSTODY_CEREMONY:`../../wasm/wallet_custody_ceremony`,CRITICAL_DIRS:[`src/core`,`src/react`,`src/static`,`src/utils`,`../wallet-server/src`,`../shared-ts/src`,`../../crates/router-ab-ed25519-yao-client`,`../../wasm/near_signer`,`../../wasm/router_ab_ecdsa_client`,`../../wasm/evm_crypto`,`../../wasm/tempo_signer`,`../../wasm/shamir3pass_runtime`,`../../wasm/email_otp_runtime`,`../../wasm/wallet_custody_ceremony`]},RUNTIME:{SDK_BASE:`/sdk`,WORKERS_BASE:`/sdk/workers`,TOUCH_CONFIRM_WORKER:`/sdk/workers/passkey-confirm.worker.js`,PASSKEY_MPC_SESSION_WORKER:`/sdk/workers/passkey-mpc-session.worker.js`,PASSKEY_MPC_EXPORT_WORKER:`/sdk/workers/passkey-mpc-export.worker.js`,SIGNER_WORKER:`/sdk/workers/near-signer.worker.js`,ECDSA_DERIVATION_CLIENT_WORKER:`/sdk/workers/ecdsa-derivation-client.worker.js`,ECDSA_PRESIGN_CLIENT_WORKER:`/sdk/workers/ecdsa-presign-client.worker.js`,ECDSA_ONLINE_CLIENT_WORKER:`/sdk/workers/ecdsa-online-client.worker.js`,EMAIL_OTP_WORKER:`/sdk/workers/email-otp.worker.js`,WALLET_CUSTODY_CEREMONY_WORKER:`/sdk/workers/wallet-custody-ceremony.worker.js`,DEVICE_LINKING_KEY_WORKER:`/sdk/workers/device-linking-key.worker.js`},WORKERS:{TOUCH_CONFIRM:`passkey-confirm.worker.js`,PASSKEY_MPC_SESSION:`passkey-mpc-session.worker.js`,PASSKEY_MPC_EXPORT:`passkey-mpc-export.worker.js`,SIGNER:`near-signer.worker.js`,ECDSA_DERIVATION_CLIENT:`ecdsa-derivation-client.worker.js`,ECDSA_PRESIGN_CLIENT:`ecdsa-presign-client.worker.js`,ECDSA_ONLINE_CLIENT:`ecdsa-online-client.worker.js`,EMAIL_OTP:`email-otp.worker.js`,WALLET_CUSTODY_CEREMONY:`wallet-custody-ceremony.worker.js`,DEVICE_LINKING_KEY:`device-linking-key.worker.js`,SHAMIR3PASS:`shamir3pass.worker.js`,WASM_SIGNER_JS:`wasm_signer_worker.js`,WASM_SIGNER_WASM:`wasm_signer_worker_bg.wasm`,ED25519_YAO_CLIENT_JS:`router_ab_ed25519_yao_client.js`,ED25519_YAO_CLIENT_WASM:`router_ab_ed25519_yao_client_bg.wasm`,ECDSA_CLIENT_JS:`router_ab_ecdsa_client.js`,ECDSA_CLIENT_WASM:`router_ab_ecdsa_client_bg.wasm`,WASM_EVM_CRYPTO_BG_WASM:`evm_crypto_bg.wasm`,WASM_TEMPO_SIGNER_BG_WASM:`tempo_signer_bg.wasm`,EMAIL_OTP_RUNTIME_JS:`email_otp_runtime.js`,EMAIL_OTP_RUNTIME_WASM:`email_otp_runtime_bg.wasm`,WALLET_CUSTODY_CEREMONY_WASM:`wallet_custody_ceremony_bg.wasm`},TEST_WORKERS:{TOUCH_CONFIRM:`/sdk/workers/passkey-confirm.worker.js`,PASSKEY_MPC_SESSION:`/sdk/workers/passkey-mpc-session.worker.js`,PASSKEY_MPC_EXPORT:`/sdk/workers/passkey-mpc-export.worker.js`,SIGNER:`/sdk/workers/near-signer.worker.js`,ECDSA_DERIVATION_CLIENT:`/sdk/workers/ecdsa-derivation-client.worker.js`,ECDSA_PRESIGN_CLIENT:`/sdk/workers/ecdsa-presign-client.worker.js`,ECDSA_ONLINE_CLIENT:`/sdk/workers/ecdsa-online-client.worker.js`,EMAIL_OTP:`/sdk/workers/email-otp.worker.js`,WALLET_CUSTODY_CEREMONY:`/sdk/workers/wallet-custody-ceremony.worker.js`,DEVICE_LINKING_KEY:`/sdk/workers/device-linking-key.worker.js`,SHAMIR3PASS:`/sdk/workers/shamir3pass.worker.js`,WASM_SIGNER_JS:`/sdk/workers/wasm_signer_worker.js`,WASM_SIGNER_WASM:`/sdk/workers/wasm_signer_worker_bg.wasm`,ED25519_YAO_CLIENT_JS:`/sdk/workers/router_ab_ed25519_yao_client.js`,ED25519_YAO_CLIENT_WASM:`/sdk/workers/router_ab_ed25519_yao_client_bg.wasm`,ECDSA_CLIENT_JS:`/sdk/workers/router_ab_ecdsa_client.js`,ECDSA_CLIENT_WASM:`/sdk/workers/router_ab_ecdsa_client_bg.wasm`,WASM_EVM_CRYPTO_BG_WASM:`/sdk/workers/evm_crypto_bg.wasm`,WASM_TEMPO_SIGNER_BG_WASM:`/sdk/workers/tempo_signer_bg.wasm`,EMAIL_OTP_RUNTIME_JS:`/sdk/workers/email_otp_runtime.js`,EMAIL_OTP_RUNTIME_WASM:`/sdk/workers/email_otp_runtime_bg.wasm`,WALLET_CUSTODY_CEREMONY_WASM:`/sdk/workers/wallet_custody_ceremony_bg.wasm`}},Qk=()=>{let e=navigator.userAgent.toLowerCase(),t=/android|iphone|ipod|blackberry|iemobile|opera mini/i.test(e),n=/ipad|tablet|kindle|playbook|silk/i.test(e),r=navigator.maxTouchPoints>0,i=window.screen.width,a=i<=480,o=i<=1024,s=`orientation`in window;return t||r&&a?`mobile`:n||r&&o&&s?`tablet`:`desktop`},$k=()=>{try{let e=navigator.userAgent;return/safari/i.test(e)&&!/chrome|crios|crmo|chromium|edg|edge|opr|opera|brave/i.test(e)}catch{return!1}},eA=()=>{try{let e=navigator.userAgent,t=navigator.platform||``,n=Number(navigator.maxTouchPoints||0),r=/iPad|iPhone|iPod/.test(e),i=/Macintosh/.test(e)&&n>1,a=/iPad|iPhone|iPod/.test(t);return r||i||a}catch{return!1}},tA=()=>{try{let e=navigator.userActivation;return!!(e&&typeof e.isActive==`boolean`&&e.isActive)}catch{return!1}},nA=()=>{try{return tA()?!1:eA()||rA()||$k()}catch{return!1}},rA=()=>Qk()===`mobile`;function iA(e){try{return Jl(e)===`emailOtp`}catch{return!1}}function aA(e,t){let n=e.userPreferencesManager.getConfirmationConfig(),r=t?.confirmationConfig||{},i=Object.fromEntries(Object.entries(r).filter(([,e])=>e!=null)),a={...n,...i};if(t?.type===Y.AUTHORIZE_KEY_EXPORT)return iu({uiMode:`none`,behavior:a.behavior,autoProceedDelay:a.autoProceedDelay});t&&iA(t)&&(a={...a,uiMode:a.uiMode===`none`?`modal`:a.uiMode,behavior:`requireClick`});let o=window.self!==window.top;if(nA()){let e=a.uiMode===`none`?`drawer`:a.uiMode;a={...a,uiMode:e,behavior:`requireClick`}}return o&&t?.type&&(t.type===Y.REGISTER_ACCOUNT||t.type===Y.LINK_DEVICE)?iu({uiMode:`modal`,behavior:`requireClick`,autoProceedDelay:a.autoProceedDelay}):iu(a)}const oA=new Map;function sA(e){e?.cleanupTimer&&(clearTimeout(e.cleanupTimer),e.cleanupTimer=null)}function cA(e){let t=String(e.requestId||``).trim();if(!t)return;sA(oA.get(t));let n=Number.isFinite(e.ttlMs)&&Number(e.ttlMs)>0?Number(e.ttlMs):12e4,r={readiness:e.readiness,cleanupTimer:null};r.cleanupTimer=setTimeout(()=>{oA.get(t)===r&&oA.delete(t)},n),oA.set(t,r)}function lA(e){let t=String(e||``).trim();if(!t)return;let n=oA.get(t);return oA.delete(t),sA(n),n?.readiness}function uA(e){let t=String(e||``).trim();t&&(sA(oA.get(t)),oA.delete(t))}const dA={CONFIRMATION_COMPLETE:`confirmation.complete`,PASSKEY_PROMPT_STARTED:`auth.passkey.prompt.started`,PASSKEY_PROMPT_SUCCEEDED:`auth.passkey.prompt.succeeded`};function fA(e,t,n){Vl(e,{requestId:t,step:2,phase:dA.CONFIRMATION_COMPLETE,status:`failed`,message:n||Wl.cancelled})}function pA(e){return e.type===Y.SIGN_TRANSACTION||e.type===Y.SIGN_NEP413_MESSAGE?Jl(e)??`webauthn`:`webauthn`}function mA(e){return!kf(e.signingOperationStateKind)||e.signingAuthMode===`emailOtp`}function hA(e){if(!e)throw Error(`NEAR transaction signing lifecycle callback is required`);return e}function gA(){}function _A(){return new Promise(gA)}function vA(){return _A()}function yA(e){let t=pd(e);return t?.kind===`expired`?{kind:`wallet_session_expired`,failure:t}:_A()}function bA(e){return e.then(vA,yA)}function xA(e){return`kind`in e&&e.kind===`wallet_session_expired`}function SA(e){return e.request.type===Y.SIGN_NEP413_MESSAGE||e.request.type===Y.SIGN_TRANSACTION&&e.transactionSummary.type===`delegateAction`?{kind:`signature_only`}:{kind:`transaction_access_key`}}function CA(e){return e.error===`NEAR_ACCOUNT_LOOKUP_FAILED`?e.details||`NEAR account access-key lookup failed.`:e.details?`${Wl.nearRpcFailed}: ${e.details}`:Wl.nearRpcFailed}function wA(e){if(e.readinessMode.kind!==`transaction_access_key`)return;if(e.request.type!==Y.SIGN_TRANSACTION)throw Error(`NEAR transaction readiness requires a transaction confirmation request`);let t=Ul(e.request);if(t.signingKind!==`transaction`)throw Error(`NEAR transaction readiness cannot use a delegate confirmation payload`);let n=t.nearFundingRequest;if(n.signatureUses!==e.usesNeeded)throw Error(`NEAR funding request signature use count does not match confirmation request`);return n}function TA(e){return e?{nearTransactionReadiness:e}:{}}function EA(e){let t=String(e||``).replace(/\D/g,``).slice(0,6);if(!/^\d{6}$/.test(t))throw Error(`Enter the 6-digit Email OTP code to continue`);return t}function DA(e){if(e.signingAuthPlanKind===Of.EmailOtpReauth)throw console.warn(`[SigningEngine][ui-confirm] Email OTP auth plan reached passkey credential lookup`,{stage:e.stage,subjectId:e.subjectId,requestId:e.requestId,signingAuthPlanKind:e.signingAuthPlanKind}),Error(`[SigningEngine] passkey_lookup_for_email_otp`)}function OA(e){throw Error(`Unsupported WebAuthn challenge branch: ${JSON.stringify(e)}`)}function kA(e){e.ctx.operationStepUpPreparation.cancel({requestId:e.requestId,...e.preparation?{handle:e.preparation.handle}:{}})}function AA(e){let t=String(e||``).trim();return!t||t===`AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`?``:t}function jA(e){let t=AA(e.defaultChallengeB64u);if(!e.webauthnChallenge){if(e.requireTypedChallenge)throw Error(`Missing typed WebAuthn challenge for passkey signing flow`);return t}switch(e.webauthnChallenge.kind){case`intent_digest`:return AA(e.webauthnChallenge.challengeB64u)||t;case`threshold_session_policy`:return String(e.webauthnChallenge.digest32B64u||``).trim();case`ecdsa_role_local_bootstrap`:return String(e.webauthnChallenge.digest32B64u||``).trim()}return OA(e.webauthnChallenge)}async function MA(e,t,n,r){let i=rt(e.surfaceMeasurementBinding),{confirmationConfig:a,transactionSummary:o,theme:s,surface:c}=r,l=Xl(e),u=tu({adapters:l,worker:n,request:t,confirmationConfig:a,transactionSummary:o,theme:s,surface:c}),d=Zl(t),f,p=String(Hl(t)||``).trim()||void 0;p===`pending-intent-digest`&&(p=void 0);try{let a=pA(t),s=t.type===Y.SIGN_TRANSACTION?Ul(t):null,c=s?.signingKind===`transaction`?s:null,m=c?hA(r.onSigningOperationInteractionEvent):null,h=c?kf(c.signingOperationStateKind):!1,g=c?mA({signingOperationStateKind:c.signingOperationStateKind,signingAuthMode:a}):!0,_=nu(t),v=t.type===Y.SIGN_TRANSACTION?Ef(t.requestId):void 0,y=t.type===Y.SIGN_TRANSACTION?String(Hl(t)||``).trim()||void 0:t.type===Y.SIGN_NEP413_MESSAGE&&String(await Su({nearAccountId:d,recipient:t.payload.recipient,message:t.payload.message})).trim()||void 0;y===`pending-intent-digest`&&(y=void 0);let b=y;p=y;let x=SA({request:t,transactionSummary:o}),S=wA({request:t,usesNeeded:_,readinessMode:x}),C=S?l.near.fetchNearContext(S):void 0,w=l.security.getRpId(),T=w?{rpId:w}:void 0,E,D=new Promise(e=>{E=e}),O=!1,k=!1,A=lA(t.requestId),j=!!A,M=A?Promise.resolve(A.promise):void 0,ee=M?bA(M):void 0,te=()=>{E?.(),E=void 0};a===`emailOtp`&&m?.({kind:Af.AuthenticationStarted});let ne=g?u.promptUser({securityContext:T,loading:!1,onMounted:()=>{te(),j&&u.updateUI({preparing:!0})}}):Promise.resolve({confirmed:!0});g?ne.finally(te):te();let re,N=e=>{let t=String(e.intentDigest||``).trim(),n=String(e.challengeB64u||``).trim();t&&(y=t,p=t),n&&(b=n)},ie=e=>{N(e),u.updateUI({...e.displayModel?{model:e.displayModel}:{},...e.title?{title:e.title}:{},...e.body?{body:e.body}:{},loading:!1})},ae=v?(async()=>(await D,await v))():void 0;ae&&ae.then(e=>{O||ie(e)}).catch(e=>{O||u.updateUI({loading:!1,errorMessage:String(I(e)?.message||e||`Failed to prepare intent`)})}),M&&M.then(async()=>{j=!1,await D,!O&&u.updateUI({preparing:!1})}).catch(async e=>{if(j=!1,await D,O)return;if(k){u.updateUI({preparing:!1});return}let t=String(I(e)?.message||`NEAR signing session could not be finalized`);u.updateUI({preparing:!1,errorMessage:`NEAR signing session could not be finalized: ${t}`})}),C&&C.then(async e=>{if(re=e,await D,e.kind===`failed`){if(k=!0,O)return;u.updateUI({loading:!1,errorMessage:CA(e)});return}if(k=!1,e.readiness.kind===`funding_required`){if(O)return;u.updateUI({loading:!1,body:Jf(String(e.readiness.request.subject.nearAccountId)),errorMessage:``,confirmText:`Fund account`});return}u.setNonceLeases(e.reservedNonceLeases),O||r.onNearTransactionContextReady?.(e.readiness);let t=e.readiness.transactionContext,n=w?{rpId:w,blockHeight:t.txBlockHeight,blockHash:t.txBlockHash}:void 0;O||u.updateUI({securityContext:n,loading:!1})});let oe=ee?await Promise.race([ne,ee]):await ne;if(O=!0,xA(oe))return kA({ctx:e,requestId:t.requestId,preparation:f}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,walletSessionFailure:oe.failure});let{confirmed:se,error:ce,otpCode:le,emailOtpChallengeId:ue}=oe;if(!se)return fA(n,t.requestId,ce),kA({ctx:e,requestId:t.requestId,preparation:f}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,error:ce});m&&!h&&(m({kind:Af.ReviewApproved}),u.dismissReviewSurface());let de=C?re||await C:void 0,fe;if(C){if(!de||de.kind===`failed`){let n=de||{kind:`failed`,error:`NEAR_CONTEXT_UNAVAILABLE`,details:`NEAR transaction readiness did not resolve`};return console.error(`[SigningFlow] fetchNearContext failed`,n),kA({ctx:e,requestId:t.requestId,preparation:f}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,error:CA(n)})}fe=de.readiness,de.readiness.kind===`context_ready`&&u.setNonceLeases(de.reservedNonceLeases)}if(ae&&N(await ae),M)try{await M}catch(n){let r=String(I(n)?.message||`NEAR signing session could not be finalized`);return kA({ctx:e,requestId:t.requestId,preparation:f}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,error:`NEAR signing session could not be finalized: ${r}`})}if(a!==`warmSession`&&fe?.kind===`funding_required`&&S){u.updateUI({body:Xf(String(fe.request.subject.nearAccountId)),errorMessage:``,loading:!0});let n;try{n=await e.nearImplicitAccountFunding.fund({requestId:t.requestId,request:fe.request})}catch(n){return kA({ctx:e,requestId:t.requestId,preparation:f}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,error:`NEAR account funding failed: ${String(I(n)?.message||n)}`})}fe=n.readiness,u.setNonceLeases(n.reservedNonceLeases)}if(a!==`warmSession`&&fe?.kind===`context_ready`){let n=wA({request:t,usesNeeded:_,readinessMode:x});if(!n)throw Error(`Operation step-up requires exact NEAR operation facts`);f=await e.operationStepUpPreparation.prepare({kind:`near_transaction`,requestId:t.requestId,transactionContext:fe.transactionContext,operationId:n.operation.operationId,operationFingerprint:n.operation.operationFingerprint,displayDigest:String(p||``).trim()})}else a!==`warmSession`&&x.kind===`signature_only`&&(f=await e.operationStepUpPreparation.prepare({kind:`near_signature_only`,requestId:t.requestId,displayDigest:String(p||``).trim()}));if(a===`emailOtp`){m?.({kind:Af.AuthenticationCompleted}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!0,otpCode:EA(le),...ue?{emailOtpChallengeId:ue}:{},...f?{operationStepUpPreparation:f}:{},...TA(fe)});return}if(a===`warmSession`){u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!0,...TA(fe)});return}DA({stage:`transaction_prompt`,subjectId:d,requestId:t.requestId,signingAuthPlanKind:t.payload.signingAuthPlan.kind});let pe=f?.challengeB64u||jA({webauthnChallenge:t.payload.webauthnChallenge,defaultChallengeB64u:String(b||``).trim(),requireTypedChallenge:t.payload.signingAuthPlan.kind===Of.PasskeyReauth&&!!t.payload.webauthnChallenge});if(!pe)throw Error(`Missing WebAuthn challenge digest for signing flow`);m?.({kind:Af.AuthenticationStarted});let me=await yf({credentialStore:e.webauthnCredentialStore,touchIdPrompt:e.touchIdPrompt,onBeforePrompt:i?.beforeCredential,cancellation:i?{kind:`abort_signal`,signal:i.abortController.signal}:{kind:`none`},walletId:t.payload.walletId,challengeB64u:pe});i?.afterCredential(),m?.({kind:Af.AuthenticationCompleted}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!0,credential:me,...f?{operationStepUpPreparation:f}:{},...TA(fe)})}catch(n){kA({ctx:e,requestId:t.requestId,preparation:f});let r=Yl(n),i=String(I(n)?.message||n||``);r&&window.parent?.postMessage({type:`WALLET_UI_CLOSED`},`*`);let a=/multiple passkeys \\(devicenumbers\\) for account/i.test(i);return u.confirmAndCloseModal({requestId:t.requestId,intentDigest:p,confirmed:!1,error:r?Wl.cancelled:a?i:i||Wl.collectCredentialsFailed})}}function NA(e){return Jl(e)??`webauthn`}async function PA(e,t,n,r){let i=rt(e.surfaceMeasurementBinding),{confirmationConfig:a,transactionSummary:o,theme:s,surface:c}=r,l=Xl(e),u=tu({adapters:l,worker:n,request:t,confirmationConfig:a,transactionSummary:o,theme:s,surface:c}),d=eu(t),f=d.kind===`near_wallet`?d.nearAccountId:d.walletId,p=d.kind===`near_wallet`?d.nearAccountId:``,m=Ef(t.requestId);try{let r=NA(t),o=String(Hl(t)||``).trim()||void 0,s=String(t.payload.challengeB64u||``).trim(),c=a.kind===`interactive`,h=l.security.getRpId(),g=h?{rpId:h}:void 0;c&&Vl(n,{requestId:t.requestId,step:2,phase:`intent-confirmation-required`,status:`running`,message:`Awaiting confirmation click`});let _,v=new Promise(e=>{_=e}),y=()=>{_?.(),_=void 0},b=u.promptUser({securityContext:g,loading:!1,onMounted:()=>{y()}});b.finally(y);let x=!1,S=!1,C=e=>{o=String(e.intentDigest||``).trim()||o,s=String(e.challengeB64u||``).trim()||s,u.updateUI({...e.displayModel?{model:e.displayModel}:{},...e.title?{title:e.title}:{},...e.body?{body:e.body}:{},loading:!1}),S=!0},w=m?(async()=>(await v,await m))():void 0;w&&w.then(e=>{x||S||C(e)}).catch(e=>{x||u.updateUI({loading:!1,errorMessage:String(I(e)?.message||e||`Failed to prepare intent`)})});let{confirmed:T,error:E,otpCode:D,emailOtpChallengeId:O}=await b;if(x=!0,!T)return c&&fA(n,t.requestId,E),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:o,confirmed:!1,error:E});if(w){let e=await w;S||C(e)}if(r===`emailOtp`)return c&&Vl(n,{requestId:t.requestId,step:2,phase:dA.CONFIRMATION_COMPLETE,status:`succeeded`,message:`Email OTP submitted`}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:o,confirmed:!0,otpCode:EA(D),...O?{emailOtpChallengeId:O}:{}});if(r===`warmSession`)return c&&Vl(n,{requestId:t.requestId,step:2,phase:dA.CONFIRMATION_COMPLETE,status:`succeeded`,message:`Confirmation complete`}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:o,confirmed:!0});DA({stage:`intent_digest_prompt`,subjectId:f,requestId:t.requestId,signingAuthPlanKind:t.payload.signingAuthPlan.kind});let k=jA({webauthnChallenge:t.payload.webauthnChallenge,defaultChallengeB64u:String(s||``).trim(),requireTypedChallenge:t.payload.signingAuthPlan.kind===Of.PasskeyReauth});if(!k)throw Error(`Missing WebAuthn challenge digest for intent signing flow`);Vl(n,{requestId:t.requestId,step:3,phase:dA.PASSKEY_PROMPT_STARTED,status:`running`,message:`Authenticating with passkey...`});let A=d.kind===`near_wallet`?await bf({credentialStore:e.webauthnCredentialStore,touchIdPrompt:e.touchIdPrompt,onBeforePrompt:i?.beforeCredential,cancellation:i?{kind:`abort_signal`,signal:i.abortController.signal}:{kind:`none`},nearAccountId:p,challengeB64u:k}):await yf({credentialStore:e.webauthnCredentialStore,touchIdPrompt:e.touchIdPrompt,onBeforePrompt:i?.beforeCredential,cancellation:i?{kind:`abort_signal`,signal:i.abortController.signal}:{kind:`none`},walletId:d.walletId,challengeB64u:k});return i?.afterCredential(),Vl(n,{requestId:t.requestId,step:4,phase:dA.PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,message:`Authentication complete`}),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:o,confirmed:!0,credential:A})}catch(e){Tf(t.requestId),Vl(n,{requestId:t.requestId,step:4,phase:dA.PASSKEY_PROMPT_SUCCEEDED,status:`failed`,message:String(I(e)?.message||e||Wl.collectCredentialsFailed)});let r=Yl(e),i=String(I(e)?.message||e||``);return r&&window.parent?.postMessage({type:`WALLET_UI_CLOSED`},`*`),u.confirmAndCloseModal({requestId:t.requestId,intentDigest:String(Hl(t)||``).trim()||void 0,confirmed:!1,error:r?Wl.cancelled:i||Wl.collectCredentialsFailed})}}async function FA(e,t,n,r){let i=Ql(n,{channelToken:t.channelToken,onDecision:r?.onDecision}),a=t.data,o,s,c;try{ql(a),$l(a),o=aA(e,a),c=he(e.getTheme?.())??`dark`;let t=Hl(a);s=Gl({...a.summary,...t?{intentDigest:t}:{}})}catch(e){console.error(`[UserConfirm][Host] validateAndParseRequest failed`,e),ru(i,{requestId:a.requestId,confirmed:!1,error:L(e)||`Invalid secure confirm request`});return}try{let t={confirmationConfig:o,transactionSummary:s,theme:c,surface:r?.signingSurface??{kind:`mount_new`}};switch(a.type){case Y.AUTHORIZE_KEY_EXPORT:case Y.SHOW_SECURE_PRIVATE_KEY_UI:{let{handleLocalOnlyFlow:n}=await import(`./localOnly-DFrtrfdO.js`);await n(e,a,i,t);break}case Y.REGISTER_ACCOUNT:case Y.LINK_DEVICE:{let{handleRegistrationFlow:n}=await import(`./registration-XNyt1YRK.js`).then(e=>e.n);await n(e,a,i,t);break}case Y.SIGN_TRANSACTION:case Y.SIGN_NEP413_MESSAGE:await MA(e,a,i,{...t,...r?.onSigningOperationInteractionEvent?{onSigningOperationInteractionEvent:r.onSigningOperationInteractionEvent}:{},...r?.onNearTransactionContextReady?{onNearTransactionContextReady:r.onNearTransactionContextReady}:{}});break;case Y.SIGN_INTENT_DIGEST:await PA(e,a,i,t);break;default:IA(a)}}catch(e){console.error(`[UserConfirm][Host] handler failed`,e),ru(i,{requestId:a.requestId,intentDigest:Hl(a),confirmed:!1,error:L(e)||`Secure confirmation failed`})}}function IA(e){throw Error(`Unsupported secure confirmation request`)}function LA(e){let t={signingKind:`transaction`,walletId:e.params.walletId,txSigningRequests:e.txSigningRequests,intentDigest:e.intentDigest,displayModel:e.displayModel,rpcCall:e.params.rpcCall,nearPublicKeyStr:e.params.nearPublicKeyStr,nearFundingRequest:e.params.nearFundingRequest,signingOperationStateKind:e.params.signingOperationStateKind};switch(e.params.signingAuthPlan.kind){case Of.WarmSession:return{...t,signingAuthPlan:e.params.signingAuthPlan};case Of.ActiveWalletAuthority:return{...t,signingAuthPlan:e.params.signingAuthPlan};case Of.PasskeyReauth:return{...t,signingAuthPlan:e.params.signingAuthPlan,...e.params.webauthnChallenge?{webauthnChallenge:e.params.webauthnChallenge}:{}};case Of.EmailOtpReauth:if(!e.params.emailOtpPrompt)throw Error(`Email OTP NEAR confirmation requires a prompt`);return{...t,signingAuthPlan:e.params.signingAuthPlan,emailOtpPrompt:e.params.emailOtpPrompt};default:return RA(e.params.signingAuthPlan)}}function RA(e){throw Error(`Unsupported transaction signing auth params: ${String(e)}`)}function zA(e){let t={signingKind:`delegate`,walletId:e.params.walletId,txSigningRequests:e.txSigningRequests,intentDigest:e.intentDigest,displayModel:e.displayModel,rpcCall:e.params.rpcCall,...e.params.nearPublicKeyStr?{nearPublicKeyStr:e.params.nearPublicKeyStr}:{}};switch(e.params.signingAuthPlan.kind){case Of.WarmSession:return{...t,signingAuthPlan:e.params.signingAuthPlan};case Of.ActiveWalletAuthority:return{...t,signingAuthPlan:e.params.signingAuthPlan};case Of.PasskeyReauth:return{...t,signingAuthPlan:e.params.signingAuthPlan,...e.params.webauthnChallenge?{webauthnChallenge:e.params.webauthnChallenge}:{}};case Of.EmailOtpReauth:{let n=e.params.signingAuthPlan.emailOtpPrompt;if(!n)throw Error(`Email OTP delegate confirmation requires a prompt`);return{...t,signingAuthPlan:e.params.signingAuthPlan,emailOtpPrompt:n}}default:return RA(e.params.signingAuthPlan)}}function BA(e){let t=String(e||``).trim();return!t||t===`pending-intent-digest`?``:t}function VA(e){return String(e||``).trim()||wf}function HA(e){if(!e)throw Error(`[SigningConfirmation] passkey intent signing requires webauthnChallenge`);return e}function UA(e){return e.signingAuthPlan.kind===Of.PasskeyReauth?{signingSubject:e.signingSubject,challengeB64u:e.challengeB64u,...e.displayModel?{displayModel:e.displayModel}:{},webauthnChallenge:HA(e.webauthnChallenge),signingAuthPlan:e.signingAuthPlan}:{signingSubject:e.signingSubject,challengeB64u:e.challengeB64u,...e.displayModel?{displayModel:e.displayModel}:{},signingAuthPlan:e.signingAuthPlan,...e.webauthnChallenge?{webauthnChallenge:e.webauthnChallenge}:{},...e.emailOtpPrompt?{emailOtpPrompt:e.emailOtpPrompt}:{}}}function WA(e){try{return pf({txSigningRequests:e.txSigningRequests,intentDigest:e.intentDigest||``,signerAccount:e.signerAccountId,title:e.title,subtitle:e.body})}catch{return{chain:`near`,...e.intentDigest?{intentDigest:e.intentDigest}:{},signerAccount:e.signerAccountId,...e.title==null?{}:{title:e.title},...e.body==null?{}:{subtitle:e.body},operations:[]}}}async function GA(e){let{sessionId:t}=e,n=KA(e.ctx),r,i;switch(e.kind){case`transaction`:{let n=e.txSigningRequests,a=n.map(e=>({receiverId:e.receiverId,actions:e.actions.map(xu)})),o={receiverId:n[0]?.receiverId,totalAmount:qA(n),type:`transaction`,...e.title==null?{}:{title:e.title},...e.body==null?{}:{body:e.body}};r=await Cu(a);let s={...o,intentDigest:r},c=WA({txSigningRequests:n,intentDigest:r,signerAccountId:e.rpcCall.nearAccountId,title:s.title,body:s.body});i={requestId:t,type:Y.SIGN_TRANSACTION,summary:s,payload:LA({params:e,txSigningRequests:n,intentDigest:r,displayModel:c}),confirmationConfig:e.confirmationConfigOverride,intentDigest:r};break}case`delegate`:{let n=[{receiverId:e.delegate.receiverId,actions:e.delegate.actions}];r=await Cu(n.map(e=>({receiverId:e.receiverId,actions:e.actions.map(xu)})));let a={intentDigest:r,receiverId:n[0]?.receiverId,totalAmount:qA(n),type:`delegateAction`,...e.title==null?{}:{title:e.title},...e.body==null?{}:{body:e.body},delegate:{senderId:e.delegate.senderId,receiverId:e.delegate.receiverId,nonce:String(e.delegate.nonce),maxBlockHeight:String(e.delegate.maxBlockHeight)}},o=WA({txSigningRequests:n,intentDigest:r,signerAccountId:e.nearAccountId,title:a.title,body:a.body});i={requestId:t,type:Y.SIGN_TRANSACTION,summary:a,payload:zA({params:e,txSigningRequests:n,intentDigest:r,displayModel:o}),confirmationConfig:e.confirmationConfigOverride,intentDigest:r};break}case`nep413`:{r=`${e.nearAccountId}:${e.recipient}:${e.message}`;let n=gf({signerAccount:e.nearAccountId,recipient:e.recipient,message:e.message,intentDigest:r,title:e.title,subtitle:e.body}),a={intentDigest:r,method:`NEP-413`,receiverId:e.recipient,...e.title==null?{}:{title:e.title},...e.body==null?{}:{body:e.body}};i={requestId:t,type:Y.SIGN_NEP413_MESSAGE,summary:a,payload:{walletId:e.walletId,nearAccountId:e.nearAccountId,...e.nearPublicKeyStr?{nearPublicKeyStr:e.nearPublicKeyStr}:{},message:e.message,recipient:e.recipient,displayModel:n,...e.webauthnChallenge?{webauthnChallenge:e.webauthnChallenge}:{},signingAuthPlan:e.signingAuthPlan,...e.emailOtpPrompt?{emailOtpPrompt:e.emailOtpPrompt}:{}},confirmationConfig:e.confirmationConfigOverride,intentDigest:r};break}case`intentDigest`:{let n=BA(e.intentDigest);r=n;let a=VA(e.challengeB64u),o=e.signingSubject,s=e.displayModel,c={...n?{intentDigest:n}:{},...e.title==null?{}:{title:e.title},...e.body==null?{}:{body:e.body}};i={requestId:t,type:Y.SIGN_INTENT_DIGEST,summary:c,payload:UA({signingSubject:o,challengeB64u:a,displayModel:s,webauthnChallenge:e.webauthnChallenge,signingAuthPlan:e.signingAuthPlan,...e.emailOtpPrompt?{emailOtpPrompt:e.emailOtpPrompt}:{}}),confirmationConfig:e.confirmationConfigOverride,...n?{intentDigest:n}:{}};break}default:throw Error(`Unsupported signing confirmation kind`)}e.confirmationReadiness&&cA({requestId:t,readiness:e.confirmationReadiness});let a=await n(i,{onProgress:e.onProgress,...e.kind===`transaction`?{onSigningOperationInteractionEvent:e.onSigningOperationInteractionEvent}:{},...e.chain===`near`&&e.kind===`transaction`&&e.onNearTransactionContextReady?{onNearTransactionContextReady:e.onNearTransactionContextReady}:{}}).finally(()=>{uA(t)});if(!a?.confirmed)throw a?.walletSessionFailure?new md({failure:a.walletSessionFailure,message:`Wallet Session expired while signing confirmation was open`}):Error(a?.error||`User rejected signing request`);if(e.kind===`intentDigest`)return{sessionId:t,intentDigest:a.intentDigest||r,credential:a.credential,otpCode:a.otpCode,emailOtpChallengeId:a.emailOtpChallengeId};if(e.kind===`delegate`||e.kind===`nep413`)return{sessionId:t,intentDigest:a.intentDigest||r,credential:a.credential,operationStepUpPreparation:a.operationStepUpPreparation,otpCode:a.otpCode,emailOtpChallengeId:a.emailOtpChallengeId};if(!a.nearTransactionReadiness)throw Error(`Missing explicit NEAR transaction readiness from confirmation flow`);return{sessionId:t,readiness:a.nearTransactionReadiness,intentDigest:a.intentDigest||r,credential:a.credential,operationStepUpPreparation:a.operationStepUpPreparation,otpCode:a.otpCode,emailOtpChallengeId:a.emailOtpChallengeId}}function KA(e){return e.touchConfirm.requestUserConfirmation.bind(e.touchConfirm)}function qA(e){try{let t=BigInt(0);for(let n of e)for(let e of n.actions)switch(e.action_type){case on.Transfer:t+=BigInt(e.deposit||`0`);break;case on.FunctionCall:t+=BigInt(e.deposit||`0`);break;case on.Stake:t+=BigInt(e.stake||`0`);break;default:break}return t>BigInt(0)?t.toString():void 0}catch{return}}async function JA({ctx:e,surface:t,walletId:n,nearAccountId:r,signerSlot:i,confirmerText:a,confirmationConfig:o,challengeB64u:s,registrationOptions:c}){let l=YA({walletId:n,nearAccountId:r,signerSlot:i,confirmerText:a,confirmationConfig:o,challengeB64u:s,registrationOptions:c});$l(l);let u=await ZA({ctx:e,surface:t,request:l,confirmationConfig:aA(e,l),transactionSummary:XA(l),theme:he(e.getTheme?.())??`dark`});return $A({requestId:l.requestId,decision:u})}function YA({walletId:e,nearAccountId:t,signerSlot:n,confirmerText:r,confirmationConfig:i,challengeB64u:a,registrationOptions:o}){let s=ve(`register`,32,`registration credential confirmation IDs`),c=r?.title,l=r?.body,u=String(e||``).trim(),d=String(t||``).trim();if(!u)throw Error(`Registration credential confirmation requires walletId`);return o?{requestId:s,type:Y.REGISTER_ACCOUNT,summary:{walletId:u,signerSlot:n,...c==null?{}:{title:c},...l==null?{}:{body:l}},payload:{walletId:u,walletAddAuthMethodRegistration:o},confirmationConfig:i,intentDigest:`register:${u}:${o.challengeId}`}:{requestId:s,type:Y.REGISTER_ACCOUNT,summary:{walletId:u,...d?{nearAccountId:d}:{},signerSlot:n,...c==null?{}:{title:c},...l==null?{}:{body:l}},payload:{walletId:u,...d?{nearAccountId:d}:{},signerSlot:n,...a?{webauthnChallenge:{kind:`intent_digest`,challengeB64u:a}}:{}},confirmationConfig:i,intentDigest:`register:${u}:${n}`}}function XA(e){let t=Kl(e.summary),n=Hl(e);return{...t,...n?{intentDigest:n}:{}}}async function ZA({ctx:e,surface:t,request:n,confirmationConfig:r,transactionSummary:i,theme:a}){let o,s,c=!1,l=new Promise((e,t)=>{o=e,s=t}),u=tp(e,n,{postMessage:e=>{let t=QA(e,n.requestId);if(t.ok){o(t.value);return}s(Error(t.message))}},{confirmationConfig:r,transactionSummary:i,theme:a,surface:t}).then(()=>{c||s(Error(`Registration confirmation completed without a decision`))},e=>{s(Error(L(e)||`Registration confirmation failed`))}),d=await l;return c=!0,await u,d}function QA(e,t){if(!A(e))return{ok:!1,message:`Registration confirmation returned a malformed response`};let n=e;if(n.type!==Ff.USER_PASSKEY_CONFIRM_RESPONSE)return{ok:!1,message:`Registration confirmation returned an unexpected response type`};if((re(n.requestId)?n.requestId.trim():``)!==t)return{ok:!1,message:`Registration confirmation response requestId mismatch`};if(!A(n.data))return{ok:!1,message:`Registration confirmation returned missing decision data`};let r=n.data,i=re(r.requestId)?r.requestId.trim():``;return i===t?O(r.confirmed)?{ok:!0,value:{requestId:i,confirmed:r.confirmed,...re(r.intentDigest)?{intentDigest:r.intentDigest}:{},...r.credential?{credential:r.credential}:{},...r.transactionContext?{transactionContext:r.transactionContext}:{},...r.registrationDiagnostics?{registrationDiagnostics:r.registrationDiagnostics}:{},...re(r.error)?{error:r.error}:{}}}:{ok:!1,message:`Registration confirmation returned invalid decision state`}:{ok:!1,message:`Registration confirmation decision requestId mismatch`}}function $A({requestId:e,decision:t}){if(!t.confirmed)throw Error(t.error||`User rejected registration request`);if(!t.credential)throw Error(`Missing credential from registration confirmation`);return rf({confirmed:t.confirmed,requestId:e,intentDigest:t.intentDigest||``,credential:t.credential,transactionContext:t.transactionContext,registrationDiagnostics:t.registrationDiagnostics,error:t.error})}function ej(e){return Math.max(0,Math.round(performance.now()-e))}function tj(e){throw Error(`Unexpected UI confirmation state: ${String(e)}`)}function nj(e){return typeof e==`object`&&!!e}function rj(e){if(!nj(e)||e.type!==Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD)return null;let t=typeof e.requestId==`string`?e.requestId.trim():``,n=typeof e.channelToken==`string`?e.channelToken.trim():``;if(!t||!n||!nj(e.data)||e.data.kind!==`pending_request`||`request`in e.data)return null;let r=typeof e.data.requestId==`string`?e.data.requestId.trim():``,i=typeof e.data.requestToken==`string`?e.data.requestToken.trim():``;return!r||r!==t||!i?null:{type:Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD,requestId:t,channelToken:n,data:{kind:`pending_request`,requestId:t,requestToken:i}}}function ij(e){if(!nj(e))return null;let t=typeof e.requestId==`string`?e.requestId.trim():``,n=typeof e.step==`number`?e.step:NaN,r=typeof e.phase==`string`?e.phase:``,i=e.status;return!t||!Number.isFinite(n)||!r||i!==`running`&&i!==`succeeded`&&i!==`failed`?null:{requestId:t,step:n,phase:r,status:i,...typeof e.message==`string`?{message:e.message}:{},...`data`in e?{data:e.data}:{}}}var aj=class{worker=null;initializationPromise=null;messageId=0;config;workerBaseOrigin;context;pendingWorkerRequests=new Map;userConfirmProgressListeners=new Map;pendingConfirmRequests=new Map;boundHandleWorkerMessage=this.handleWorkerMessage.bind(this);boundHandleWorkerError=this.handleWorkerError.bind(this);registrationPreparationModalState={kind:`closed`,generation:0};transactionPreparationModalState={kind:`closed`,generation:0};constructor(e,t){this.config={workerUrl:Zk.RUNTIME.TOUCH_CONFIRM_WORKER,workerTimeout:6e4,debug:!1,...e},this.context={...t}}getContext(){return this.context}async requestUserConfirmation(e,t){let n=typeof e?.requestId==`string`?e.requestId.trim():``;if(!n)throw Error(`Invalid secure confirmation request: missing requestId`);if(this.pendingConfirmRequests.has(n))throw Error(`Duplicate secure confirmation request id: ${n}`);let r=this.generateMessageId();this.pendingConfirmRequests.set(n,{kind:`awaiting_decision`,context:{...this.context},request:e,requestToken:r,...t?.onSigningOperationInteractionEvent?{onSigningOperationInteractionEvent:t.onSigningOperationInteractionEvent}:{},...t?.onNearTransactionContextReady?{onNearTransactionContextReady:t.onNearTransactionContextReady}:{}});try{let e=performance.now();await this.ensureWorkerReady(!1);let i=ej(e);t?.onProgress&&this.userConfirmProgressListeners.set(n,t.onProgress);let a=performance.now(),o=await this.sendMessage({type:`SECURE_CONFIRM_REQUEST`,id:r,payload:{requestId:n}}),s=ej(a),c=performance.now();if(!o?.success)throw Error(String(o?.error||`Secure confirmation request failed`));let l=this.pendingConfirmRequests.get(n);if(!l||l.kind!==`decided`)throw Error(`Secure confirmation failed: missing host decision`);let u=l.decision,d=ej(c);return u.registrationDiagnostics?.kind===`registration_confirmation_diagnostics_v1`?{...u,registrationDiagnostics:{...u.registrationDiagnostics,workerReadyMs:i,workerRequestRoundTripMs:s,workerResponseValidationMs:d}}:u}finally{this.userConfirmProgressListeners.delete(n),this.pendingConfirmRequests.delete(n)}}async orchestrateSigningConfirmation(e){return GA(e)}async openTransactionPreparationModal(e){if(!String(e.walletLabel||``).trim())throw Error(`Transaction preparation modal requires a wallet label`);this.closeTransactionPreparationModal();let t=this.context.userPreferencesManager.getConfirmationConfig(),n=Object.fromEntries(Object.entries(e.confirmationConfigOverride||{}).filter(([,e])=>e!=null)),r=iu({...t,...n});if(r.kind===`silent`)return;let i=String(this.context.touchIdPrompt.getRpId()||``).trim(),a=this.transactionPreparationModalState.generation+1;this.transactionPreparationModalState={kind:`opening`,generation:a};let o=await Yf({ctx:this.getContext(),summary:{title:`Review transaction`},...e.chain===`near`?{txSigningRequests:e.txSigningRequests}:{},model:e.model,securityContext:i?{rpId:i}:void 0,loading:!1,theme:this.context.getTheme?.()??`dark`,uiMode:r.uiMode}),s=this.transactionPreparationModalState;if(s.kind!==`opening`||s.generation!==a){o.close(!1);return}this.transactionPreparationModalState={kind:`open`,generation:a,handle:o},o.onCancel?.(this.handleTransactionPreparationCancel.bind(this,a,o))}handleTransactionPreparationCancel(e,t){let n=this.transactionPreparationModalState;n.kind!==`open`||n.generation!==e||n.handle!==t||(this.transactionPreparationModalState={kind:`cancelled`,generation:e},t.close(!1))}closeTransactionPreparationModal(){let e=this.transactionPreparationModalState;this.transactionPreparationModalState={kind:`closed`,generation:e.generation},e.kind===`open`&&e.handle.close(!1)}takeTransactionConfirmationSurface(){let e=this.transactionPreparationModalState;switch(e.kind){case`closed`:return{kind:`mount_new`};case`opening`:throw Error(`Transaction confirmation started before its preparation modal opened`);case`cancelled`:return this.transactionPreparationModalState={kind:`closed`,generation:e.generation},{kind:`preparation_cancelled`};case`open`:return this.transactionPreparationModalState={kind:`closed`,generation:e.generation},{kind:`reuse_mounted`,handle:e.handle};default:return tj(e)}}async requestRegistrationCredentialConfirmation(e){let t=this.takeRegistrationConfirmationSurface();try{return await JA({ctx:this.getContext(),surface:t,walletId:e.walletId,nearAccountId:e.nearAccountId,signerSlot:e.signerSlot,confirmerText:e.confirmerText,confirmationConfig:e.confirmationConfigOverride,challengeB64u:e.challengeB64u,registrationOptions:e.registrationOptions})}catch(e){throw t.kind===`reuse_mounted`&&t.handle.close(!1),e}}takeRegistrationConfirmationSurface(){let e=this.registrationPreparationModalState;switch(e.kind){case`closed`:return{kind:`mount_new`};case`opening`:throw Error(`Registration confirmation started before its preparation modal opened`);case`open`:return this.registrationPreparationModalState={kind:`closed`,generation:e.generation},{kind:`reuse_mounted`,handle:e.handle};default:return tj(e)}}async openRegistrationPreparationModal(e){let t=String(e.walletLabel||``).trim();if(!t)throw Error(`Registration preparation modal requires a wallet label`);if(!Number.isInteger(e.signerSlot)||e.signerSlot<1)throw Error(`Registration preparation modal requires a positive signer slot`);let n=String(this.context.touchIdPrompt.getRpId()||``).trim();if(!n)throw Error(`Registration preparation modal requires an RP ID`);this.closeRegistrationPreparationModal();let r=this.registrationPreparationModalState.generation+1;this.registrationPreparationModalState={kind:`opening`,generation:r};let i=await Yf({ctx:this.getContext(),summary:{title:`Create your passkey`,body:`Preparing secure registration…`},securityContext:{rpId:n,passkeyRegistration:{kind:`passkey_registration_confirm_display_v1`,intendedUserName:t,accountId:t,rpId:n,signerSlot:e.signerSlot}},loading:!0,theme:this.context.getTheme?.()??`dark`,uiMode:`modal`}),a=this.registrationPreparationModalState;if(a.kind!==`opening`||a.generation!==r){i.close(!1);return}this.registrationPreparationModalState={kind:`open`,generation:r,handle:i}}closeRegistrationPreparationModal(){let e=this.registrationPreparationModalState;this.registrationPreparationModalState={kind:`closed`,generation:e.generation},e.kind===`open`&&e.handle.close(!1)}setWorkerBaseOrigin(e){this.workerBaseOrigin=e}async ensureWorkerReady(e=!1){if(this.initializationPromise?await this.initializationPromise:this.worker||await this.initialize(),!this.worker)throw Error(`UserConfirm worker failed to initialize`);if(e)try{if(!(await this.sendMessage({type:`PING`,id:this.generateMessageId()},3e3)).success)throw Error(`UserConfirm worker failed health check`)}catch(e){throw console.error(`[UserConfirmWorker] health check failed:`,e),Error(`UserConfirm worker failed health check`)}}async initialize(){if(this.initializationPromise)return this.initializationPromise;if(!this.worker)return this.initializationPromise=this.createUserConfirmWorker().catch(e=>{throw console.error(`[UserConfirmWorker] initialization failed:`,e),console.error(`[UserConfirmWorker] error details:`,{message:e.message,stack:e.stack,name:e.name}),this.initializationPromise=null,e}),await this.initializationPromise}async createUserConfirmWorker(){try{if(this.worker){let e=this.worker;this.detachWorkerRouter(e),e.terminate(),this.worker=null,this.rejectPendingWorkerRequestsForWorker(e,Error(`UserConfirm worker was restarted`))}let e=rp(this.config.workerUrl||Zk.RUNTIME.TOUCH_CONFIRM_WORKER,{worker:`touchConfirm`,baseOrigin:this.workerBaseOrigin});this.config.debug&&console.debug(`[UserConfirmWorker] Worker URL:`,e);let t=new Worker(e,{type:`module`,name:`Web3AuthnSecureConfirmWorker`});this.attachWorkerRouter(t),this.worker=t,await this.testWebWorkerCommunication()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`UserConfirm worker initialization failed: ${t}`)}}attachWorkerRouter(e){e.addEventListener(`message`,this.boundHandleWorkerMessage),e.addEventListener(`error`,this.boundHandleWorkerError)}detachWorkerRouter(e){e.removeEventListener(`message`,this.boundHandleWorkerMessage),e.removeEventListener(`error`,this.boundHandleWorkerError)}isFromActiveWorker(e){return e.currentTarget===this.worker&&e.target===this.worker}normalizePromptEnvelope(e){let t=rj(e);if(!t)return null;let n=this.pendingConfirmRequests.get(t.requestId);return!n||n.kind!==`awaiting_decision`||n.requestToken!==t.data.requestToken?null:{type:t.type,requestId:t.requestId,channelToken:t.channelToken,data:n.request}}capturePendingConfirmationDecision(e,t){let n=e.request.requestId.trim();if(!n||t.requestId.trim()!==n)return;let r=this.pendingConfirmRequests.get(n);r!==e||r.kind!==`awaiting_decision`||this.pendingConfirmRequests.set(n,{kind:`decided`,request:r.request,requestToken:r.requestToken,decision:t})}postPromptEnvelopeError(e,t,n,r){e.postMessage({type:Ff.USER_PASSKEY_CONFIRM_RESPONSE,requestId:t,channelToken:n,data:{requestId:t,confirmed:!1,error:r}})}dispatchUserConfirmProgress(e){let t=ij(e.data),n=typeof e.requestId==`string`&&e.requestId.trim()?e.requestId.trim():typeof t?.requestId==`string`?t.requestId.trim():``;if(!n||!t)return;let r=this.userConfirmProgressListeners.get(n);if(r)try{r(t)}catch(e){console.error(`[UserConfirmWorker] progress listener failed:`,e)}}handleWorkerMessage(e){if(!this.isFromActiveWorker(e))return;let t=e.data;if(nj(t)&&t.type===Ff.USER_PASSKEY_CONFIRM_PROGRESS){this.dispatchUserConfirmProgress(t);return}let n=this.normalizePromptEnvelope(t);if(n){let t=this.pendingConfirmRequests.get(n.requestId);if(!t||t.kind!==`awaiting_decision`)return;let r=t.context,i=e.currentTarget;FA(r,n,i,{signingSurface:n.data.type===Y.SIGN_TRANSACTION||n.data.type===Y.SIGN_NEP413_MESSAGE||n.data.type===Y.SIGN_INTENT_DIGEST?this.takeTransactionConfirmationSurface():{kind:`mount_new`},onDecision:this.capturePendingConfirmationDecision.bind(this,t),...t.onSigningOperationInteractionEvent?{onSigningOperationInteractionEvent:t.onSigningOperationInteractionEvent}:{},...t.onNearTransactionContextReady?{onNearTransactionContextReady:t.onNearTransactionContextReady}:{}}).catch(e=>{console.error(`[UserConfirmWorker] failed to handle confirmation prompt:`,e),this.postPromptEnvelopeError(i,n.requestId,n.channelToken,`Secure confirmation failed`)});return}if(nj(t)&&t.type===Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD){console.error(`[UserConfirmWorker] rejected malformed prompt envelope`);return}let r=bu(t);if(!r)return;let i=r.id||``;if(!i)return;let a=e.currentTarget;this.resolvePendingWorkerRequest(a,i,r)}handleWorkerError(e){if(!this.isFromActiveWorker(e))return;let t=e,n=String(t?.message||`UserConfirm worker encountered an unknown error`),r=Error(`UserConfirm worker failed: ${n}`);console.error(`[UserConfirmWorker] error:`,t);let i=e.currentTarget;i===this.worker&&this.worker&&(this.detachWorkerRouter(this.worker),this.worker.terminate(),this.worker=null,this.initializationPromise=null),this.rejectPendingWorkerRequestsForWorker(i,r)}resolvePendingWorkerRequest(e,t,n){let r=this.pendingWorkerRequests.get(t);!r||r.worker!==e||(clearTimeout(r.timeoutId),r.settle?.(),this.pendingWorkerRequests.delete(t),r.resolve(n))}rejectPendingWorkerRequest(e,t){let n=this.pendingWorkerRequests.get(e);n&&(clearTimeout(n.timeoutId),n.settle?.(),this.pendingWorkerRequests.delete(e),n.reject(t))}rejectPendingWorkerRequestsForWorker(e,t){for(let n of this.pendingWorkerRequests.values())n.worker===e&&(this.pendingWorkerRequests.delete(n.id),clearTimeout(n.timeoutId),n.settle?.(),n.reject(t))}async sendMessage(e,t,n){return new Promise((r,i)=>{let a=this.worker;if(!a){i(Error(`UserConfirm worker not available`));return}let o=()=>Error(`UserConfirm worker request aborted for message type: ${e.type}`);if(n?.aborted){i(o());return}let s=typeof e.id==`string`&&e.id.trim().length?e.id.trim():this.generateMessageId();if(this.pendingWorkerRequests.has(s)){i(Error(`Duplicate UserConfirm worker request id: ${s}`));return}let c=t??this.config.workerTimeout??6e4,l=setTimeout(()=>{this.rejectPendingWorkerRequest(s,Error(`UserConfirm worker communication timeout (${c}ms) for message type: ${e.type}`))},c),u;if(n){let e=()=>{this.rejectPendingWorkerRequest(s,o())};n.addEventListener(`abort`,e,{once:!0}),u=()=>{n.removeEventListener(`abort`,e)}}this.pendingWorkerRequests.set(s,{id:s,messageType:e.type,worker:a,timeoutId:l,settle:u,resolve:r,reject:i});try{a.postMessage({...e,id:s})}catch(e){let t=e instanceof Error?e:Error(String(e));this.rejectPendingWorkerRequest(s,t)}})}generateMessageId(){return`sc_${Date.now()}_${++this.messageId}`}async testWebWorkerCommunication(){try{let e=await this.sendMessage({type:`PING`,id:this.generateMessageId()},15e3);if(!e.success)throw Error(`UserConfirm worker PING failed: ${e.error}`);return}catch(e){let t=e instanceof Error?e.message:String(e);throw console.warn(`[UserConfirmWorker] testWebWorkerCommunication failed:`,t),this.worker&&=(this.detachWorkerRouter(this.worker),this.worker.terminate(),null),e}}};function oj(e,t){return new aj(e,t)}function sj(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Invalid export confirmation: ${t} must be an object`);return e}function cj(e,t){if(typeof e!=`string`)throw Error(`Invalid export confirmation: ${t} must be a string`);return e}function lj(e,t){let n=cj(e,t);if(!n.trim()||n!==n.trim())throw Error(`Invalid export confirmation: ${t} must be a nonempty identity`);return n}function uj(e,t){return e===void 0?void 0:cj(e,t)}function dj(e,t){if(e===void 0||typeof e==`boolean`)return e;throw Error(`Invalid export confirmation: ${t} must be a boolean`)}function fj(e){let t=sj(e,`subject`);switch(t.kind){case`near_wallet`:if(t.walletId!==void 0)throw Error(`Invalid NEAR export subject`);return{kind:`near_wallet`,nearAccountId:lj(t.nearAccountId,`nearAccountId`)};case`evm_wallet`:if(t.nearAccountId!==void 0)throw Error(`Invalid EVM export subject`);return{kind:`evm_wallet`,walletId:lj(t.walletId,`walletId`)};default:throw Error(`Invalid export confirmation: unsupported subject`)}}function pj(e){let t=sj(e,`summary`),n=t.operation;if(n!==`Export Private Key`&&n!==`Export Recovery Key`)throw Error(`Invalid export confirmation: unsupported operation`);return{operation:n,accountId:lj(t.accountId,`summary.accountId`),publicKey:cj(t.publicKey,`summary.publicKey`),warning:cj(t.warning,`summary.warning`)}}function mj(e){let t=sj(e,`key`),n=t.scheme;if(n!==`ed25519`&&n!==`secp256k1`)throw Error(`Invalid export confirmation: unsupported key scheme`);return{scheme:n,label:cj(t.label,`key.label`),publicKey:cj(t.publicKey,`key.publicKey`),privateKey:cj(t.privateKey,`key.privateKey`),address:uj(t.address,`key.address`)}}function hj(e){if(e!==void 0){if(!Array.isArray(e))throw Error(`Invalid export confirmation: keys must be an array`);return e.map(mj)}}function gj(e){return cj(e,`guidance step`)}function _j(e){if(e===void 0)return;let t=sj(e,`guidance`);if(t.steps!==void 0&&!Array.isArray(t.steps))throw Error(`Invalid export confirmation: guidance steps must be an array`);return{title:cj(t.title,`guidance.title`),body:uj(t.body,`guidance.body`),steps:t.steps?.map(gj)}}function vj(e){if(e===void 0)return;let{uiMode:t,behavior:n,autoProceedDelay:r}=sj(e,`confirmationConfig`);if(t!==void 0&&t!==`none`&&t!==`modal`&&t!==`drawer`)throw Error(`Invalid export confirmation: unsupported UI mode`);if(n!==void 0&&n!==`skipClick`&&n!==`requireClick`)throw Error(`Invalid export confirmation: unsupported behavior`);if(r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)))throw Error(`Invalid export confirmation: invalid autoProceedDelay`);return{uiMode:t,behavior:n,autoProceedDelay:r}}function yj(e){let t=sj(e,`request`),n=sj(t.payload,`payload`);if(n.prfOutput!==void 0||n.prf_output!==void 0||n.wrapKeySeed!==void 0||n.wrapKeySalt!==void 0||n.prfKey!==void 0)throw Error(`Invalid export confirmation: forbidden signing secret`);let r=lj(t.requestId,`requestId`),i=pj(t.summary),a=fj(n.subject),o=cj(n.publicKey,`publicKey`),s=uj(t.intentDigest,`intentDigest`),c=vj(t.confirmationConfig);if(n.onLifecycle!==void 0)throw Error(`Invalid export confirmation: callbacks belong to the host`);switch(t.type){case Y.AUTHORIZE_KEY_EXPORT:return{type:Y.AUTHORIZE_KEY_EXPORT,requestId:r,summary:i,intentDigest:s,confirmationConfig:c,payload:{subject:a,publicKey:o,credentialIdB64u:lj(n.credentialIdB64u,`credentialIdB64u`),challengeB64u:uj(n.challengeB64u,`challengeB64u`)}};case Y.SHOW_SECURE_PRIVATE_KEY_UI:{let{variant:e,theme:t}=n;if(e!==void 0&&e!==`drawer`&&e!==`modal`)throw Error(`Invalid export confirmation: unsupported variant`);if(t!==void 0&&t!==`dark`&&t!==`light`)throw Error(`Invalid export confirmation: unsupported theme`);return{type:Y.SHOW_SECURE_PRIVATE_KEY_UI,requestId:r,summary:i,intentDigest:s,confirmationConfig:c,payload:{subject:a,publicKey:o,viewerSessionId:uj(n.viewerSessionId,`viewerSessionId`),privateKey:uj(n.privateKey,`privateKey`),keys:hj(n.keys),guidance:_j(n.guidance),variant:e,theme:t,loading:dj(n.loading,`loading`),errorMessage:uj(n.errorMessage,`errorMessage`)}}}default:throw Error(`Invalid export confirmation: unsupported request type`)}}const bj=6e4;function xj(e){return typeof e==`object`&&!!e}function Sj(e){if(!xj(e))return null;let t=e.kind;if(typeof e.accountId!=`string`)return null;let n=Array.isArray(e.exportedSchemes)?e.exportedSchemes:null;if(!n)return null;let r=n.filter(e=>e===`ed25519`||e===`secp256k1`);return r.length===n.length?t===`completed`?`error`in e?null:{kind:t,accountId:e.accountId,exportedSchemes:r}:t!==`cancelled`&&t!==`failed`||r.length!==0||typeof e.error!=`string`?null:{kind:t,accountId:e.accountId,exportedSchemes:[],error:e.error}:null}var Cj=class{worker=null;initializationPromise=null;workerBaseOrigin;messageId=0;pendingRequests=new Map;viewerLifecycleBySessionId=new Map;boundHandleWorkerMessage=this.handleWorkerMessage.bind(this);boundHandleWorkerError=this.handleWorkerError.bind(this);constructor(e){this.context=e}setWorkerBaseOrigin(e){this.workerBaseOrigin=e}async exportPrivateKeysWithUi(e,t){await this.ensureWorkerReady();let n=`viewerSessionId`in e?String(e.viewerSessionId||``).trim():``;n&&t?.onViewerLifecycle&&this.viewerLifecycleBySessionId.set(n,t.onViewerLifecycle);try{let t=await this.sendMessage({type:`EXPORT_PRIVATE_KEYS_WITH_UI`,id:this.generateMessageId(),payload:e});if(!t.success)throw Error(String(t.error||`Export private keys request failed`));let n=Sj(t.data);if(!n)throw Error(`Export private keys request failed: invalid worker response payload`);return n}finally{n&&this.viewerLifecycleBySessionId.delete(n)}}async ensureWorkerReady(){if(!this.worker&&(this.initializationPromise||=this.createWorker().catch(e=>{throw this.initializationPromise=null,e}),await this.initializationPromise,!this.worker))throw Error(`Passkey MPC export worker failed to initialize`)}async createWorker(){let e=rp(Zk.RUNTIME.PASSKEY_MPC_EXPORT_WORKER,{worker:`passkeyMpcExport`,baseOrigin:this.workerBaseOrigin}),t=new Worker(e,{type:`module`,name:`PasskeyMpcExportWorker`});t.addEventListener(`message`,this.boundHandleWorkerMessage),t.addEventListener(`error`,this.boundHandleWorkerError),this.worker=t}normalizePromptEnvelope(e){if(!xj(e)||e.type!==Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD||!xj(e.data)||e.data.kind!==`export_request`)return null;let t;try{t=yj(e.data.request)}catch{return null}let n=typeof e.requestId==`string`?e.requestId.trim():``,r=typeof t.requestId==`string`?t.requestId.trim():``,i=typeof e.channelToken==`string`?e.channelToken.trim():``;return!n||n!==r||!i?null:{type:Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD,requestId:n,channelToken:i,data:this.restoreViewerLifecycle(t)}}restoreViewerLifecycle(e){if(e.type!==Y.SHOW_SECURE_PRIVATE_KEY_UI)return e;let t=e.payload.viewerSessionId;if(!t)return e;let n=this.viewerLifecycleBySessionId.get(t);return n?{type:e.type,requestId:e.requestId,summary:e.summary,intentDigest:e.intentDigest,confirmationConfig:e.confirmationConfig,payload:{...e.payload,onLifecycle:n}}:e}postPromptEnvelopeError(e,t,n){e.postMessage({type:Ff.USER_PASSKEY_CONFIRM_RESPONSE,requestId:t,channelToken:n,data:{requestId:t,confirmed:!1,error:`Secure confirmation failed`}})}handleWorkerMessage(e){if(e.currentTarget!==this.worker||e.target!==this.worker)return;let t=this.normalizePromptEnvelope(e.data);if(t){let n=e.currentTarget;FA(this.context,t,n).catch(e=>{console.error(`[PasskeyMpcExportWorker] failed to handle export prompt:`,e),this.postPromptEnvelopeError(n,t.requestId,t.channelToken||``)});return}if(xj(e.data)&&e.data.type===Ff.PROMPT_USER_CONFIRM_IN_JS_MAIN_THREAD){console.error(`[PasskeyMpcExportWorker] rejected malformed prompt envelope`);return}let n=bu(e.data);if(!n)return;let r=n.id||``;if(!r)return;let i=this.pendingRequests.get(r);i&&(clearTimeout(i.timeoutId),this.pendingRequests.delete(r),i.resolve(n))}handleWorkerError(e){if(e.currentTarget!==this.worker||e.target!==this.worker)return;let t=e,n=Error(`Passkey MPC export worker failed: ${String(t.message||`unknown worker error`)}`),r=this.worker;r&&(r.removeEventListener(`message`,this.boundHandleWorkerMessage),r.removeEventListener(`error`,this.boundHandleWorkerError),r.terminate()),this.worker=null,this.initializationPromise=null;for(let e of this.pendingRequests.values())clearTimeout(e.timeoutId),e.reject(n);this.pendingRequests.clear()}sendMessage(e){return new Promise((t,n)=>{let r=this.worker;if(!r){n(Error(`Passkey MPC export worker not available`));return}let i=typeof e.id==`string`&&e.id.trim()?e.id.trim():this.generateMessageId();if(this.pendingRequests.has(i)){n(Error(`Duplicate Passkey MPC export request id: ${i}`));return}let a=setTimeout(()=>{let e=this.pendingRequests.get(i);e&&(this.pendingRequests.delete(i),e.reject(Error(`Passkey MPC export request timed out (${bj}ms)`)))},bj);this.pendingRequests.set(i,{id:i,timeoutId:a,resolve:t,reject:n});try{r.postMessage({...e,id:i})}catch(e){clearTimeout(a),this.pendingRequests.delete(i),n(e instanceof Error?e:Error(String(e)))}})}generateMessageId(){return`mpc_export_${Date.now()}_${++this.messageId}`}};function wj(e){return new Cj(e)}function Tj(e){if(e.purpose.curve===`ecdsa`)return e.purpose.thresholdSessionId;if(e.thresholdSessionId===void 0)throw Error(`Ed25519 warm material operation requires its protocol session id`);return e.thresholdSessionId}function Ej(e){return e.curve===`ecdsa`?{thresholdSessionId:e.thresholdSessionId,chainTarget:e.chainTarget}:null}function $(e){return String(e??``).trim()||null}function Dj(e){return Array.isArray(e)?e.map(e=>Math.floor(Number(e))).filter(e=>Number.isFinite(e)&&e>0):[]}function Oj(e){try{return Ci(e)}catch{return null}}function kj(e){try{return ci(e)}catch{return null}}function Aj(e){switch(e){case`login`:case`registration`:case`manual-bootstrap`:case`email_otp`:return e;default:return null}}function jj(e){let t=Aj(e);return t&&t!==`email_otp`?t:null}function Mj(e){return e&&typeof e==`object`?e:null}function Nj(e){return Mj(e.thresholdSessionIds)||{}}function Pj(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:null}function Fj(e){try{return pi(e)}catch{return null}}function Ij(e){let t=$(e.rawSigningRootId),n=$(e.rawSigningRootVersion),r=null,i=null;if(e.runtimePolicyScope)try{let t=Pe(e.runtimePolicyScope);r=$(t.signingRootId),i=$(t.signingRootVersion)}catch{}if(t&&r&&t!==r||n&&i&&n!==i)return null;let a=t||r,o=n||i;return a&&o?{signingRootId:a,signingRootVersion:o}:null}function Lj(e){return!!($(e.signingRootId)||$(e.signingRootVersion))}function Rj(e){return!!($(e.subjectId)||$(e.userId))}function zj(e){let t=Nj(e);return{authMethod:e.authMethod,curve:e.curve,storeKey:e.storeKey,walletId:e.walletId||null,thresholdSessionIds:t,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses,updatedAtMs:e.updatedAtMs,hasEcdsaRestore:!!e.ecdsaRestore}}function Bj(e,t){return{kind:`rejected`,rejection:{kind:`rejected_sealed_recovery_record`,storeKey:$(e.storeKey),walletId:$(e.walletId),reason:t,safeSummary:zj(e)}}}function Vj(e,t={}){let n=Nj(e),r=Mj(e.ecdsaRestore),i=$(e.storeKey),a=$(e.walletId),o=$(e.sealedSecretB64u),s=Math.floor(Number(e.issuedAtMs)||0),c=Math.floor(Number(e.expiresAtMs)||0),l=Math.floor(Number(e.remainingUses)||0),u=Math.floor(Number(e.updatedAtMs)||0);if(e.authMethod!==`passkey`&&e.authMethod!==`email_otp`||e.curve!==`ecdsa`)return Bj(e,`unsupported_record`);if(!i||!a||!o)return Bj(e,`missing_identity`);if(c<=0||u<=0||s<=0)return Bj(e,`missing_restore_metadata`);if(Rj(e))return Bj(e,`invalid_identity`);if(!t.allowExpired&&c<=Date.now())return Bj(e,`expired`);if(!t.allowExhausted&&e.authMethod!==`passkey`&&l<=0)return Bj(e,`exhausted`);let d=$(n.ecdsa),f=r,p=we(f?.runtimePolicyScope),m=Ij({runtimePolicyScope:p,rawSigningRootId:f?.signingRootId,rawSigningRootVersion:f?.signingRootVersion}),h=$(e.relayerUrl),g=e.authMethod===`passkey`?$(f?.rpId):null,_=e.authMethod===`passkey`?jj(f?.source):null,v=e.authMethod===`email_otp`&&Aj(f?.source)===`email_otp`?`email_otp`:null,y=$(f?.credentialIdB64u),b=$(f?.providerSubjectId),x=$(f?.emailHashHex),S=$(f?.relayerKeyId),C=$(f?.keyHandle),w=$(f?.ecdsaThresholdKeyId),T=Pj(f?.ethereumAddress),E=$(f?.thresholdEcdsaPublicKeyB64u),D=Dj(f?.participantIds),O=Oj(f?.routerAbEcdsaDerivationNormalSigning),k=kj(f?.publicCapability),A=null;try{A=Li(f?.roleLocalMaterialRef)}catch{A=null}let j=$(f?.clientVerifyingShareB64u),M=e.authMethod===`passkey`?j:null;if(f?.sessionKind!=null||Lj(e))return Bj(e,`invalid_identity`);if(!d||!m)return Bj(e,`missing_identity`);if(!f?.chainTarget)return Bj(e,`wrong_chain_target`);let ee;try{ee=xn(f.chainTarget)}catch{return Bj(e,`wrong_chain_target`)}if(!h||e.authMethod===`passkey`&&!_||e.authMethod===`email_otp`&&!v||e.authMethod===`passkey`&&!g||e.authMethod===`passkey`&&!y||e.authMethod===`email_otp`&&(!b||!x)||!w||!S||!C||!T||!E||!p||!O||!k||!D.length||!A||e.authMethod===`passkey`&&!M)return Bj(e,`missing_restore_metadata`);let te=e.authMethod===`passkey`?Fj({walletId:a,rpId:g,credentialIdB64u:y}):null,ne=gi(f.authority),re=hi(f.emailOtpAuthority),N=e.authMethod===`email_otp`&&ne&&re&&re.walletId===a&&re.factor.provider===f.provider&&re.factor.providerUserId===b&&re.verifier.emailHashHex===x?re:null;return e.authMethod===`passkey`&&!te||e.authMethod===`email_otp`&&!N?Bj(e,`invalid_identity`):{kind:`accepted`,record:e.authMethod===`passkey`?{storeKey:i,walletId:a,authMethod:`passkey`,curve:`ecdsa`,thresholdSessionId:d,sealedSecretB64u:o,issuedAtMs:s,expiresAtMs:c,remainingUses:l,updatedAtMs:u,...$(e.keyVersion)?{keyVersion:$(e.keyVersion)}:{},...$(e.groupId)?{groupId:$(e.groupId)}:{},chainTarget:ee,source:_,authority:te,signingRootId:m.signingRootId,signingRootVersion:m.signingRootVersion,keyHandle:C,ecdsaThresholdKeyId:w,ethereumAddress:T,thresholdEcdsaPublicKeyB64u:E,participantIds:D,relayerUrl:h,relayerKeyId:S,runtimePolicyScope:p,routerAbEcdsaDerivationNormalSigning:O,publicCapability:k,clientVerifyingShareB64u:M,roleLocalMaterialRef:A}:{storeKey:i,walletId:a,authMethod:`email_otp`,curve:`ecdsa`,thresholdSessionId:d,sealedSecretB64u:o,issuedAtMs:s,expiresAtMs:c,remainingUses:l,updatedAtMs:u,...$(e.keyVersion)?{keyVersion:$(e.keyVersion)}:{},...$(e.groupId)?{groupId:$(e.groupId)}:{},chainTarget:ee,source:`email_otp`,authority:ne,emailOtpAuthority:N,signingRootId:m.signingRootId,signingRootVersion:m.signingRootVersion,keyHandle:C,ecdsaThresholdKeyId:w,ethereumAddress:T,thresholdEcdsaPublicKeyB64u:E,participantIds:D,relayerUrl:h,relayerKeyId:S,runtimePolicyScope:p,routerAbEcdsaDerivationNormalSigning:O,publicCapability:k,...j?{clientVerifyingShareB64u:j}:{},roleLocalMaterialRef:A}}}function Hj(e,t){return String(e??``).trim()===String(t??``).trim()}function Uj(e,t){return String(e??``).trim().toLowerCase()===String(t??``).trim().toLowerCase()}function Wj(e,t){return e.length===t.length?e.every((e,n)=>Number(e)===Number(t[n])):!1}function Gj(e,t){let n=[],r=t.signer;return Hj(e.walletId,r.walletId)||n.push(`wallet_id`),wn(e.chainTarget,r.chainTarget)||n.push(`chain_target`),Hj(e.keyHandle,r.keyHandle)||n.push(`key_handle`),Hj(e.ecdsaThresholdKeyId,r.key.ecdsaThresholdKeyId)||n.push(`ecdsa_threshold_key_id`),Hj(e.signingRootId,r.key.signingRootId)||n.push(`signing_root_id`),Hj(e.signingRootVersion,r.key.signingRootVersion)||n.push(`signing_root_version`),Uj(e.ethereumAddress,r.key.thresholdOwnerAddress)||n.push(`threshold_owner_address`),Wj(e.participantIds,r.key.participantIds)||n.push(`participant_ids`),e.authMethod!==t.auth.kind&&n.push(`auth_method`),e.authMethod===`passkey`?t.auth.kind===`passkey`?(Hj(e.authority.verifier.rpId,t.auth.rpId)||n.push(`rp_id`),Hj(e.authority.factor.credentialIdB64u,t.auth.credentialIdB64u)||n.push(`credential_id`),n):(n.push(`passkey_auth_branch`),n):t.auth.kind===`email_otp`?(Hj(e.emailOtpAuthority.factor.providerUserId,t.auth.providerSubjectId)||n.push(`provider_subject_id`),n):(n.push(`email_otp_auth_branch`),n)}function Kj(e){console.warn(`[SigningSessionRestore] ECDSA restore identity mismatch`,JSON.stringify({reasons:e.reasons,record:{authMethod:e.record.authMethod,walletId:e.record.walletId,source:e.record.source,chainTarget:H(e.record.chainTarget),keyHandle:e.record.keyHandle,ecdsaThresholdKeyId:e.record.ecdsaThresholdKeyId,signingRootId:e.record.signingRootId,signingRootVersion:e.record.signingRootVersion,ethereumAddress:e.record.ethereumAddress,participantIds:e.record.participantIds},lane:{authMethod:e.lane.auth.kind,walletId:e.lane.signer.walletId,chainTarget:H(e.lane.signer.chainTarget),keyHandle:e.lane.signer.keyHandle,ecdsaThresholdKeyId:e.lane.signer.key.ecdsaThresholdKeyId,signingRootId:e.lane.signer.key.signingRootId,signingRootVersion:e.lane.signer.key.signingRootVersion,thresholdOwnerAddress:e.lane.signer.key.thresholdOwnerAddress,participantIds:e.lane.signer.key.participantIds}},null,2))}function qj(e,t){if(t.authMethod!==e.authMethod||!wn(t.chainTarget,e.chainTarget)||t.thresholdSessionId!==e.thresholdSessionId)return null;let n=e.materialRestoreIdentity.lane,r=Gj(t,n);return r.length>0?(Kj({record:t,lane:n,reasons:r}),null):!Hj(t.ecdsaThresholdKeyId,e.materialRestoreIdentity.ecdsaThresholdKeyId)||!Hj(t.walletId,n.signer.walletId)||!Hj(t.keyHandle,n.signer.keyHandle)||!g(t.roleLocalMaterialRef.materialActivation,n.signer.materialActivation)?null:{record:t,purpose:{walletId:e.walletId,authMethod:e.authMethod,curve:`ecdsa`,chainTarget:e.chainTarget,materialActivation:t.roleLocalMaterialRef.materialActivation,thresholdSessionId:t.thresholdSessionId,reason:e.reason}}}function Jj(e,t){let n=Vj(t,{allowExpired:!1,allowExhausted:!1});if(n.kind===`rejected`)return{kind:`rejected`,rejection:n.rejection};let r=qj(e,n.record);return r?{kind:`matched`,workItem:r}:{kind:`not_applicable`}}function Yj(e){return wn(e.record.chainTarget,e.requestedChainTarget)?[{record:e.record,purpose:{walletId:e.walletId,authMethod:e.record.authMethod,curve:`ecdsa`,chainTarget:e.requestedChainTarget,materialActivation:e.record.roleLocalMaterialRef.materialActivation,thresholdSessionId:e.record.thresholdSessionId,reason:e.reason}}]:[]}function Xj(e){let t=Vj(e.record);if(t.kind===`rejected`)return[{kind:`rejected`,rejection:t.rejection}];let n=Yj({walletId:e.walletId,record:t.record,reason:e.reason,requestedChainTarget:e.requestedChainTarget});return n.length?n.map(e=>({kind:`matched`,workItem:e})):[{kind:`not_applicable`}]}function Zj(e){return e.kind===`matched`}function Qj(e,t){let n=H(e.chainTarget),r=`materialRestoreIdentity`in e?e.materialRestoreIdentity.lane.signer.materialActivation:e.materialActivation;return[e.walletId,e.authMethod,e.curve,n,e.reason,tf(r),e.thresholdSessionId,t.thresholdSessionId,t.updatedAtMs,`restored`].join(`|`)}function $j(e,t){let n=H(e.chainTarget);return[e.walletId,e.authMethod,e.curve,n,tf(e.materialActivation),e.thresholdSessionId,t.updatedAtMs].join(`|`)}function eM(e){return{kind:`completed`,attempted:e.attempted,restored:e.restored,deferred:e.deferred}}function tM(e){return e.map(({record:e,purpose:t})=>({authMethod:t.authMethod,curve:t.curve,chain:H(t.chainTarget),thresholdSessionId:t.thresholdSessionId,recordThresholdSessionId:e.thresholdSessionId,updatedAtMs:e.updatedAtMs}))}function nM(){let e=new Set;return{hasSuccessfulRestore:(t,n)=>e.has(Qj(t,n)),rememberSuccessfulRestore:(t,n)=>{e.add(Qj(t,n))},clear:()=>{e.clear()}}}function rM(){let e=new Set,t=new Map;return{hasCompleted:t=>e.has(String(t||``).trim()),rememberCompleted:t=>{let n=String(t||``).trim();n&&e.add(n)},getInFlight:e=>{let n=String(e||``).trim();return n?t.get(n):void 0},setInFlight:(e,n)=>{let r=String(e||``).trim();r&&t.set(r,n)},clearInFlight:e=>{let n=String(e||``).trim();n&&t.delete(n)},clear:()=>{e.clear(),t.clear()}}}async function iM(e,t){let n=String(e.walletId||``).trim();if(!n)return eM({attempted:0,restored:0,deferred:0});let r={...e,walletId:n},i;try{i=await t.listExactSealedSessionsForWallet({walletId:n,authMethod:r.authMethod,curve:`ecdsa`,chainTarget:r.chainTarget})}catch(e){return t.onListError?.({walletId:n,target:H(r.chainTarget),reason:r.reason,error:e}),eM({attempted:0,restored:0,deferred:0})}let a=i.map(e=>Jj(r,e));for(let e of a)e.kind===`rejected`&&t.onRejectedRecord?.({walletId:n,rejection:e.rejection});let o=a.filter(Zj).map(e=>e.workItem);if(!o.length)return eM({attempted:0,restored:0,deferred:0});if(o.length>1)return{kind:`duplicate_records`,attempted:0,restored:0,deferred:0,duplicateCount:o.length,duplicateRecordSummaries:tM(o)};let s=0,c=0,l=0;return await Promise.all(o.map(async({record:e,purpose:i})=>{if(t.cache?.hasSuccessfulRestore(r,e))return;s+=1;let a=await t.restoreSealedRecordForWallet({walletId:n,record:e,purpose:i});a===`restored`&&(c+=1,t.cache?.rememberSuccessfulRestore(r,e)),a===`ready`&&t.cache?.rememberSuccessfulRestore(r,e),a===`deferred`&&(l+=1)})),eM({attempted:s,restored:c,deferred:l})}async function aM(e,t){let n=String(e.walletId||``).trim(),r=Math.max(0,Math.floor(e.maxRecords??10)),i={listed:0,discovered:0,truncated:0};if(!n||r<=0)return i;let a;try{a=(await Promise.all(e.ecdsaChainTargets.map(r=>t.listExactSealedSessionsForWallet({walletId:n,authMethod:e.authMethod,curve:`ecdsa`,chainTarget:r})))).flat()}catch(e){return t.onListError?.({walletId:n,error:e}),i}let o=new Set,s=a.flatMap(t=>e.ecdsaChainTargets.flatMap(e=>Xj({walletId:n,record:t,reason:`session_status`,requestedChainTarget:e}))).filter(e=>e.kind===`rejected`?(t.onRejectedRecord?.({walletId:n,rejection:e.rejection}),!1):!0).filter(Zj).map(e=>e.workItem).filter(e=>{let t=$j(e.purpose,e.record);return o.has(t)?!1:(o.add(t),!0)}),c=s.slice(0,r);return{listed:a.length,discovered:c.length,truncated:Math.max(0,s.length-c.length)}}function oM(e){if(e.ok)return!1;switch(e.code){case`expired`:case`exhausted`:return!1;case`not_found`:case`invalid_args`:case`invalid_response`:return!0;default:return!1}}async function sM(e){let t=await e.resolveCurrentEcdsaCapabilityRuntime({walletId:V(e.record.walletId),chainTarget:e.record.chainTarget});return t.kind===`resolved`&&g(t.runtime.materialActivation,e.record.roleLocalMaterialRef.materialActivation)?{kind:`current`}:{kind:`superseded`,status:{ok:!1,code:`superseded`,message:`Passkey ECDSA sealed recovery was superseded (${t.kind===`blocked`?t.reason:`material_activation_mismatch`})`}}}async function cM(e){if(!wn(e.record.chainTarget,e.purpose.chainTarget))return null;let t=String(e.purpose.thresholdSessionId||``).trim();if(!t||!e.groupId)return null;let n=await sM({record:e.record,resolveCurrentEcdsaCapabilityRuntime:e.resolveCurrentEcdsaCapabilityRuntime});if(n.kind===`superseded`)return n.status;let r=await e.rehydrateWarmSessionMaterial({thresholdSessionId:t,sealedSecretB64u:e.record.sealedSecretB64u,signingSessionSealKeyVersion:Bi(e.record.keyVersion),expiresAtMs:e.record.expiresAtMs,remainingUses:e.record.remainingUses,transport:{...e.transport,groupId:e.groupId}});if(!r.ok){let t=await sM({record:e.record,resolveCurrentEcdsaCapabilityRuntime:e.resolveCurrentEcdsaCapabilityRuntime});return t.kind===`superseded`?t.status:(oM(r)&&await e.deletePersistedRecord().catch(()=>void 0),await e.recordSessionMaterialRestored(r),r)}let i=await e.readWarmSessionStatusFromWorker(t);if(!i)return{ok:!1,code:`worker_error`,message:`Warm-session status read failed after rehydrate`};let a=await sM({record:e.record,resolveCurrentEcdsaCapabilityRuntime:e.resolveCurrentEcdsaCapabilityRuntime});return a.kind===`superseded`?a.status:(i.ok?await e.updatePersistedPolicy({expiresAtMs:i.expiresAtMs,remainingUses:i.remainingUses,updatedAtMs:Date.now()}).catch(()=>void 0):oM(i)&&await e.deletePersistedRecord().catch(()=>void 0),await e.recordSessionMaterialRestored(i),i)}const lM=new Map;function uM(e){return Math.max(0,Math.round(performance.now()-e))}function dM(e){e.diagnostics?.recordDuration(e.bucket,uM(e.startedAt))}function fM(e){!e.diagnostics||!e.resultDiagnostics||(e.diagnostics.recordDuration(`sealed_record_apply_runtime_setup`,e.resultDiagnostics.runtimeSetupMs),e.diagnostics.recordDuration(`sealed_record_apply_client_seal`,e.resultDiagnostics.clientSealMs),e.diagnostics.recordDuration(`sealed_record_apply_server_route`,e.resultDiagnostics.serverSealRouteMs),e.diagnostics.recordDuration(`sealed_record_apply_client_unseal`,e.resultDiagnostics.clientUnsealMs),e.diagnostics.recordDuration(`sealed_record_apply_policy_update`,e.resultDiagnostics.policyUpdateMs))}function pM(e){if(e.transport.curve===`ecdsa`){let t=String(e.transport.walletId).trim(),n=String(e.transport.ecdsaRestore.authority.walletId).trim();if(!t||!n||t!==n)throw Error(`Passkey ECDSA seal transport wallet does not match restore metadata`);return{walletId:t,ecdsaRestore:e.transport.ecdsaRestore}}let t=Pe(Fe(e.transport.ed25519Restore.runtimePolicyScope));return{walletId:e.transport.walletId,signingRootId:t.signingRootId,...t.signingRootVersion?{signingRootVersion:t.signingRootVersion}:{},ed25519Restore:e.transport.ed25519Restore}}function mM(e){return e.transport.curve===`ed25519`?{authMethod:`passkey`,curve:`ed25519`}:{authMethod:`passkey`,curve:`ecdsa`,chainTarget:e.transport.chainTarget}}function hM(e){if(e.transport.curve===`ecdsa`){let t=e.transport.ecdsaRestore?.roleLocalMaterialRef;if(!t)throw Error(`Passkey ECDSA persistence requires exact restore metadata`);return[`persist`,`passkey`,`ecdsa`,H(e.transport.chainTarget),t.materialActivation.activationId,t.materialActivation.capability,t.materialActivation.materialOwner,t.materialActivation.keyBinding,t.materialActivation.lifecycleBinding,t.materialActivation.signingWorker,t.durableMaterialRef,t.bindingDigest].join(`|`)}let t=Wd({authMethod:`passkey`,materialActivation:e.transport.ed25519Restore.materialActivation});return[`persist`,t.kind,t.authMethod,tf(t.materialActivation)].join(`|`)}function gM(e){return e.transport.curve===`ed25519`}function _M(e){if(!gM(e)){let t=String(e.metadata.walletId||``).trim();if(!t||!e.metadata.ecdsaRestore)throw Error(`[SigningSessionSealedStore] missing Passkey ECDSA seal metadata`);let n={...e.existing?.thresholdSessionIds,ecdsa:e.thresholdSessionId};return{thresholdSessionId:e.thresholdSessionId,sealedSecretB64u:e.sealedSecretB64u,curve:`ecdsa`,authMethod:`passkey`,thresholdSessionIds:n,walletId:t,relayerUrl:e.relayerUrl,keyVersion:e.keyVersion,groupId:e.groupId,ecdsaRestore:e.metadata.ecdsaRestore,...e.metadata.ed25519Restore?{ed25519Restore:e.metadata.ed25519Restore}:{},issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses,updatedAtMs:e.updatedAtMs}}let t=String(e.metadata.walletId||``).trim();if(!t||!e.metadata.ed25519Restore)throw Error(`[SigningSessionSealedStore] missing Passkey Ed25519 seal metadata`);let n={...e.existing?.thresholdSessionIds,ed25519:e.thresholdSessionId};return{thresholdSessionId:e.thresholdSessionId,sealedSecretB64u:e.sealedSecretB64u,curve:`ed25519`,authMethod:`passkey`,thresholdSessionIds:n,walletId:t,...e.metadata.signingRootId?{signingRootId:e.metadata.signingRootId}:{},...e.metadata.signingRootVersion?{signingRootVersion:e.metadata.signingRootVersion}:{},relayerUrl:e.relayerUrl,keyVersion:e.keyVersion,groupId:e.groupId,...e.metadata.ecdsaRestore?{ecdsaRestore:e.metadata.ecdsaRestore}:{},ed25519Restore:e.metadata.ed25519Restore,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses,updatedAtMs:e.updatedAtMs}}function vM(e){return e.transport.curve===`ed25519`}async function yM(e){let t=ns(e);if(!t)throw Error(`[SigningSessionSealedStore] invalid sealed session record write input`);await qs(t)}function bM(e,t){return e.source===t.source&&wn(e.chainTarget,t.chainTarget)&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.ethereumAddress===t.ethereumAddress&&e.relayerKeyId===t.relayerKeyId&&e.clientVerifyingShareB64u===t.clientVerifyingShareB64u&&e.thresholdEcdsaPublicKeyB64u===t.thresholdEcdsaPublicKeyB64u&&g(e.roleLocalMaterialRef.materialActivation,t.roleLocalMaterialRef.materialActivation)&&e.roleLocalMaterialRef.durableMaterialRef===t.roleLocalMaterialRef.durableMaterialRef&&e.roleLocalMaterialRef.bindingDigest===t.roleLocalMaterialRef.bindingDigest&&e.participantIds.length===t.participantIds.length&&e.participantIds.every((e,n)=>e===t.participantIds[n])&&e.authority.kind===t.authority.kind&&e.authority.walletId===t.authority.walletId&&e.authority.authorityDigest===t.authority.authorityDigest&&e.authority.walletAuthMethodId===t.authority.walletAuthMethodId&&ti(e.publicCapability,t.publicCapability)&&ui(e.routerAbEcdsaDerivationNormalSigning,t.routerAbEcdsaDerivationNormalSigning)}function xM(e){if(e.existing.curve!==e.transport.curve)return!1;let t=String(e.transport.walletId).trim();if(!t||t!==e.existing.walletId)return!1;if(e.existing.curve===`ed25519`&&e.transport.curve===`ed25519`)return g(e.existing.ed25519Restore.materialActivation,e.transport.ed25519Restore.materialActivation);if(e.existing.curve!==`ecdsa`||e.transport.curve!==`ecdsa`||!wn(e.existing.ecdsaRestore.chainTarget,e.transport.chainTarget))return!1;let n=e.metadata.ecdsaRestore;return n?bM(e.existing.ecdsaRestore,n):!0}function SM(e){return e.curve===`ecdsa`?{walletId:e.walletId,ecdsaRestore:e.ecdsaRestore,...e.ed25519Restore?{ed25519Restore:e.ed25519Restore}:{}}:{walletId:e.walletId,...e.signingRootId?{signingRootId:e.signingRootId}:{},...e.signingRootVersion?{signingRootVersion:e.signingRootVersion}:{},...e.ecdsaRestore?{ecdsaRestore:e.ecdsaRestore}:{},ed25519Restore:e.ed25519Restore}}function CM(e,t){return e.curve,{...e,authMethod:`passkey`,groupId:t}}async function wM(e){return e.transport.curve===`ed25519`?await Bo(Wd({authMethod:`passkey`,materialActivation:e.transport.ed25519Restore.materialActivation})):await Ro(e.thresholdSessionId,e.purpose)}var TM=class{constructor(e){this.deps=e}async persistSigningSessionSealForThresholdSession(e){if(this.deps.signingSessionPersistenceMode!==`sealed_refresh_v1`)return{ok:!1,code:`not_enabled`,message:`Passkey signing-session seal persistence requires signingSessionPersistenceMode="sealed_refresh_v1"`};let t=String(e.thresholdSessionId||``).trim();if(!t)return{ok:!1,code:`invalid_args`,message:`Missing threshold sessionId`};let n=String(e.transport.relayerUrl||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Passkey seal persistence requires relayerUrl`};let r=pM({transport:e.transport}),i=mM({transport:e.transport});if(!i)return{ok:!1,code:`invalid_args`,message:`Passkey seal persistence requires one exact record purpose`};let a=hM({transport:e.transport}),o=lM.get(a);if(o)return await o;let s;s=(e.transport.curve,this.persistExactRecord({thresholdSessionId:t,transport:e.transport,metadata:r,purpose:i,relayerUrl:n,diagnostics:e.diagnostics,completedSeal:e.completedSeal}));let c=s.finally(()=>{lM.delete(a)});return lM.set(a,c),await c}async recordPolicyResult(e,t,n){let r=await this.readRecordForPurpose(e,t);if(r){if(n.ok){await this.writePolicy(r,n.expiresAtMs,Math.max(0,n.remainingUses));return}if(n.code===`exhausted`){await this.writePolicy(r,r.expiresAtMs,0);return}n.code===`expired`&&await this.writePolicy(r,Math.min(r.expiresAtMs,Date.now()),Math.max(0,r.remainingUses))}}async updatePersistedPolicy(e){let t=await this.readRecordForPurpose(e.purpose,e.thresholdSessionId);!t||t.curve!==`ecdsa`||t.thresholdSessionIds.ecdsa!==e.thresholdSessionId||await this.writePolicy(t,e.expiresAtMs,e.remainingUses)}async persistExactRecord(e){let t=performance.now(),n;try{n=await wM(e)}catch(n){return dM({diagnostics:e.diagnostics,bucket:`sealed_record_existing_read`,startedAt:t}),{ok:!1,code:`local_persist_failed`,message:n instanceof Error?`Failed to read the existing sealed session: ${n.message}`:`Failed to read the existing sealed session`}}if(dM({diagnostics:e.diagnostics,bucket:`sealed_record_existing_read`,startedAt:t}),n){if(!xM({existing:n,transport:e.transport,metadata:e.metadata}))return{ok:!1,code:`binding_mismatch`,message:`Existing sealed session names different material`};let t=performance.now(),r;try{r=await this.deps.readWarmSessionStatus({thresholdSessionId:e.thresholdSessionId})}catch(e){return{ok:!1,code:`worker_error`,message:e instanceof Error?`Failed to read warm-session policy: ${e.message}`:`Failed to read warm-session policy`}}dM({diagnostics:e.diagnostics,bucket:`sealed_record_policy_read`,startedAt:t});let i=SM(n),a=r.ok?r.expiresAtMs:r.code===`expired`?Math.min(n.expiresAtMs,Date.now()):n.expiresAtMs,o=r.ok?r.remainingUses:r.code===`exhausted`?0:n.remainingUses;if(!r.ok&&r.code!==`expired`&&r.code!==`exhausted`)return r;let s=performance.now();return await yM((vM(e),_M({thresholdSessionId:e.thresholdSessionId,transport:e.transport,metadata:i,sealedSecretB64u:n.sealedSecretB64u,relayerUrl:n.relayerUrl,keyVersion:n.keyVersion,groupId:n.groupId,issuedAtMs:n.issuedAtMs,expiresAtMs:a,remainingUses:o,updatedAtMs:Date.now(),existing:n}))),dM({diagnostics:e.diagnostics,bucket:`sealed_record_register`,startedAt:s}),{ok:!0,sealedSecretB64u:n.sealedSecretB64u,keyVersion:n.keyVersion,remainingUses:o,expiresAtMs:a}}if(e.transport.curve===`ecdsa`&&!e.metadata.ecdsaRestore)return{ok:!1,code:`missing_restore_metadata`,message:`Passkey ECDSA seal persistence requires exact restore metadata`};if(e.transport.curve===`ecdsa`&&e.metadata.ecdsaRestore&&!wn(e.transport.chainTarget,e.metadata.ecdsaRestore.chainTarget))return{ok:!1,code:`binding_mismatch`,message:`Passkey ECDSA seal transport and restore metadata name different material`};if(e.transport.curve===`ed25519`&&!e.metadata.ed25519Restore)return{ok:!1,code:`missing_restore_metadata`,message:`Passkey Ed25519 seal persistence requires exact restore metadata`};if(String(e.transport.groupId||`rfc2409-group2`).trim()!==`rfc2409-group2`)return{ok:!1,code:`invalid_args`,message:`Unsupported groupId for Passkey signing-session seal persistence`};let r=Ze,i=performance.now(),a=e.completedSeal??await this.deps.sealAndPersistWarmSessionMaterial({thresholdSessionId:e.thresholdSessionId,transport:CM(e.transport,r)});if(dM({diagnostics:e.diagnostics,bucket:`sealed_record_apply_server_seal`,startedAt:i}),fM({diagnostics:e.diagnostics,resultDiagnostics:a.ok?a.diagnostics:void 0}),!a.ok)return a;let o=String(a.keyVersion||``).trim();if(!o)return{ok:!1,code:`invalid_key_version`,message:`Signing-session seal response did not include a key version`};let s=Date.now(),c=performance.now();await yM((vM(e),_M({thresholdSessionId:e.thresholdSessionId,transport:e.transport,metadata:e.metadata,sealedSecretB64u:a.sealedSecretB64u,relayerUrl:e.relayerUrl,keyVersion:o,groupId:r,issuedAtMs:s,expiresAtMs:a.expiresAtMs,remainingUses:a.remainingUses,updatedAtMs:s}))),dM({diagnostics:e.diagnostics,bucket:`sealed_record_register`,startedAt:c});let l=performance.now(),u;try{u=await wM(e)}catch{u=null}return dM({diagnostics:e.diagnostics,bucket:`sealed_record_verify_read`,startedAt:l}),u?a:{ok:!1,code:`local_persist_failed`,message:`Failed to persist sealed signing-session record locally`}}async readRecordForPurpose(e,t){return e.curve===`ed25519`?await Bo(Wd({authMethod:`passkey`,materialActivation:e.materialActivation})):await Ro(t,{authMethod:`passkey`,curve:`ecdsa`,chainTarget:e.chainTarget})}async writePolicy(e,t,n){if(e.curve===`ed25519`){await Js({locator:Wd({authMethod:`passkey`,materialActivation:e.ed25519Restore.materialActivation}),expiresAtMs:Math.max(1,Math.floor(t)),remainingUses:Math.max(0,Math.floor(n)),updatedAtMs:Date.now()});return}await Mo({thresholdSessionId:e.thresholdSessionIds.ecdsa,filter:{authMethod:`passkey`,curve:`ecdsa`,chainTarget:e.ecdsaRestore.chainTarget},expiresAtMs:Math.max(1,Math.floor(t)),remainingUses:Math.max(0,Math.floor(n)),updatedAtMs:Date.now()})}};const EM=new Map,DM=new Map;function OM(e){return[`rehydrate`,`passkey`,`ecdsa`,H(e.chainTarget),tf(e.materialActivation),String(e.thresholdSessionId||``).trim()].join(`|`)}function kM(e,t){if(!e)return`deferred`;if(e.ok)return t;if(e.code===`exhausted`)return`ready`;if(e.code===`expired`)return`deferred`;throw Error(`[PasskeyMpcSession] sealed-session restore failed (${e.code}): ${e.message}`)}async function AM(e){return{chainTarget:e.chainTarget,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,source:e.source,authority:await U({authority:e.authority}),roleLocalMaterialRef:e.roleLocalMaterialRef,rpId:e.authority.verifier.rpId,credentialIdB64u:e.authority.factor.credentialIdB64u,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,ethereumAddress:e.ethereumAddress,relayerKeyId:e.relayerKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,participantIds:[...e.participantIds],...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,publicCapability:e.publicCapability}}function jM(e){return e.session.capabilitySubjects.some(t=>t.kind===`sign`&&t.keyFamily===`ecdsa_secp256k1`&&g(t.materialActivation,e.materialActivation))}async function MM(e){let t=V(e.walletId),n;try{n=await K.resolveSelectedWalletAuthority(String(t))}catch{return null}if(n.kind!==`resolved`)return null;let{selection:r,authMethod:i,authority:a}=n;if(r.lockState!==`unlocked`||r.walletId!==t||r.walletAuthMethodId!==i.walletAuthMethodId||i.kind!==`passkey`||i.status!==`active`||i.walletId!==t||i.walletAuthorityId!==a.authorityId||i.walletAuthMethodId!==e.factorAuthority.bindingId||i.rpId!==e.factorAuthority.verifier.rpId||i.credentialIdB64u!==e.factorAuthority.factor.credentialIdB64u||a.state!==`active`||a.walletId!==t)return null;let o;try{o=await q.readExactWithOperationCredential({walletId:t,authorityId:a.authorityId,authMethodId:i.walletAuthMethodId})}catch{return null}return o.kind!==`found`||o.record.walletId!==t||o.record.authorityId!==a.authorityId||o.record.authMethodId!==i.walletAuthMethodId||o.record.authorityDigestB64u!==a.authorityDigestB64u||o.record.authorityRevocationEpoch!==a.revocationEpoch||o.record.expiresAtMs<=e.nowMs||!jM({session:o.record,materialActivation:e.materialActivation})?null:o.operationCredential}async function NM(e){let t=is({durableRecord:{authMethod:`passkey`,curve:`ecdsa`,thresholdSessionId:e.thresholdSessionId,chainTarget:e.chainTarget},deleteReason:`invalid_persisted_record`,preserveResolvedIdentity:!1}),n=[`delete`,`passkey`,`ecdsa`,H(e.chainTarget),e.thresholdSessionId].join(`|`),r=DM.get(n);if(r)return await r;let i=Io(t).finally(()=>{DM.delete(n)});DM.set(n,i),await i}async function PM(e){return await hs({walletId:e.walletId,filter:{authMethod:`passkey`,curve:`ecdsa`,chainTarget:e.chainTarget}})}function FM(e){console.warn(`[PasskeyMpcSession] signing-session restore list failed`,{walletId:e.walletId,target:e.target,reason:e.reason,error:e.error instanceof Error?e.error.message:String(e.error||`unknown error`)})}function IM(e){console.warn(`[PasskeyMpcSession] signing-session restore rejected record`,e)}function LM(e){return typeof e==`object`&&!!e}function RM(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:0}function zM(e){return Number.isSafeInteger(e)&&Number(e)>=0}function BM(e){return Number.isSafeInteger(e)&&Number(e)>0}function VM(e){return!LM(e)||typeof e.ok!=`boolean`?null:e.ok?!zM(e.remainingUses)||!BM(e.expiresAtMs)?null:{ok:!0,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}:{ok:!1,code:typeof e.code==`string`?e.code:`worker_error`,message:typeof e.message==`string`?e.message:`Warm-session status read failed`}}function HM(e){if(!LM(e)||!Array.isArray(e.results))return null;let t=[];for(let n of e.results){if(!LM(n)||typeof n.thresholdSessionId!=`string`||!n.thresholdSessionId.trim())return null;let e=VM(n.result);if(!e)return null;t.push({thresholdSessionId:n.thresholdSessionId,result:e})}return{results:t}}function UM(e){return!LM(e)||typeof e.ok!=`boolean`?null:e.ok?typeof e.prfFirstB64u!=`string`||!e.prfFirstB64u.trim()||!zM(e.remainingUses)||!BM(e.expiresAtMs)?null:{ok:!0,prfFirstB64u:e.prfFirstB64u,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}:{ok:!1,code:typeof e.code==`string`?e.code:`worker_error`,message:typeof e.message==`string`?e.message:`Warm-session claim failed`}}function WM(e){if(!LM(e)||typeof e.ok!=`boolean`)return null;if(!e.ok)return{ok:!1,code:typeof e.code==`string`?e.code:`worker_error`,message:typeof e.message==`string`?e.message:`Signing-session seal and persist failed`};if(typeof e.sealedSecretB64u!=`string`||!e.sealedSecretB64u.trim()||typeof e.keyVersion!=`string`||!e.keyVersion.trim()||!zM(e.remainingUses)||!BM(e.expiresAtMs))return null;let t=LM(e.diagnostics)?{runtimeSetupMs:RM(e.diagnostics.runtimeSetupMs),clientSealMs:RM(e.diagnostics.clientSealMs),serverSealRouteMs:RM(e.diagnostics.serverSealRouteMs),clientUnsealMs:RM(e.diagnostics.clientUnsealMs),policyUpdateMs:RM(e.diagnostics.policyUpdateMs)}:void 0;return{ok:!0,sealedSecretB64u:e.sealedSecretB64u,keyVersion:e.keyVersion.trim(),remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs,...t?{diagnostics:t}:{}}}function GM(e){if(e.authMethod===`email_otp`||e.curve===`linked_device`)throw Error(`Passkey MPC durable owner requires an owner signing-lane transport`);return e}function KM(e){return Math.max(0,Math.round(performance.now()-e))}function qM(e){e.diagnostics?.recordDuration(e.bucket,KM(e.startedAt))}var JM=class{worker=null;initializationPromise=null;workerBaseOrigin;messageId=0;pendingRequests=new Map;boundHandleWorkerMessage=this.handleWorkerMessage.bind(this);boundHandleWorkerError=this.handleWorkerError.bind(this);durableState;constructor(e){this.deps=e,this.durableState=new TM({signingSessionPersistenceMode:e.signingSessionPersistenceMode,sealAndPersistWarmSessionMaterial:this.sealAndPersistWarmSessionMaterial.bind(this),readWarmSessionStatus:this.readWarmSessionStatus.bind(this)})}setWorkerBaseOrigin(e){this.workerBaseOrigin=e}async prewarmShamir3Pass(){try{await this.sendMessage({type:`PREWARM_SHAMIR3PASS`,id:this.generateMessageId(),payload:{}},15e3)}catch{}}async prepareSigningSessionHydration(e){let t=await this.sendMessage({type:`PREPARE_SESSION_CLIENT_SEAL`,id:this.generateMessageId(),payload:e});if(!t.success)throw Error(t.error||`Client seal preparation failed`)}async discardSigningSessionHydration(e){let t=await this.sendMessage({type:`DISCARD_SESSION_CLIENT_SEAL`,id:this.generateMessageId(),payload:e});if(!t.success)throw Error(t.error||`Client seal cleanup failed`)}async readPreparedSigningSessionHydration(e){let t=await this.sendMessage({type:`READ_SESSION_CLIENT_SEAL`,id:this.generateMessageId(),payload:e});if(!t.success||!LM(t.data)||t.data.ok!==!0||typeof t.data.ciphertext!=`string`||!t.data.ciphertext.trim())throw Error(t.success?`Prepared client seal is invalid`:t.error||`Client seal read failed`);return{ciphertext:t.data.ciphertext}}putWarmSessionMaterial=async e=>{let{diagnostics:t,preparedServerSeal:n,...r}=e;if(n&&!e.transport)throw Error(`Prepared server seal requires exact persistence transport`);let i=performance.now();await this.ensureWorkerReady(),qM({diagnostics:t,bucket:`worker_ready`,startedAt:i});let a=performance.now(),o=await this.sendMessage({type:`WARM_SESSION_MATERIAL_PUT`,id:this.generateMessageId(),payload:r});if(!o.success)throw Error(String(o.error||`Failed to cache warm-session material`));let s=VM(o.data);if(!s)throw Error(`Warm-session cache returned an invalid response`);if(!s.ok)throw Error(`Warm-session cache failed (${s.code}): ${s.message}`);if(qM({diagnostics:t,bucket:`worker_put`,startedAt:a}),this.deps.signingSessionPersistenceMode!==`sealed_refresh_v1`)return;let c;if(n&&e.transport){let t=await this.sendMessage({type:`COMPLETE_SESSION_CLIENT_SEAL`,id:this.generateMessageId(),payload:{preparationId:n.preparationId,thresholdSessionId:e.thresholdSessionId,transport:GM(e.transport),serverSeal:{ok:!0,ciphertext:n.ciphertext,keyVersion:n.keyVersion,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses}}}),r=t.success?WM(t.data):null;if(!r){let e=t.success?`Prepared signing-session seal returned an invalid response`:t.error||`Prepared signing-session seal failed`;throw Error(e)}if(!r.ok)throw Error(`Prepared signing-session seal failed (${r.code}): ${r.message}`);c=r}let l=performance.now(),u=e.transport?await this.durableState.persistSigningSessionSealForThresholdSession({thresholdSessionId:e.thresholdSessionId,transport:GM(e.transport),...t?{diagnostics:t}:{},...c?{completedSeal:c}:{}}):null;if(qM({diagnostics:t,bucket:`sealed_record_persist`,startedAt:l}),u&&!u.ok)throw Error(`Warm-session cache could not persist sealed refresh material (${u.code}): ${u.message}`)};getWarmSessionStatus=async e=>await this.readWarmSessionStatus(e);discoverPersistedSessionsForWallet=async e=>this.deps.signingSessionPersistenceMode===`sealed_refresh_v1`?await aM({...e,authMethod:`passkey`},{listExactSealedSessionsForWallet:async e=>await hs({walletId:e.walletId,filter:e.curve===`ecdsa`?{authMethod:`passkey`,curve:`ecdsa`,chainTarget:e.chainTarget}:{authMethod:`passkey`,curve:`ed25519`}}),onListError:({walletId:e,error:t})=>{console.warn(`[PasskeyMpcSession] persisted-session discovery list failed`,{walletId:e,error:t instanceof Error?t.message:String(t||`unknown error`)})},onRejectedRecord:({walletId:e,rejection:t})=>{console.warn(`[PasskeyMpcSession] persisted-session discovery rejected record`,{walletId:e,rejection:t})}}):{listed:0,discovered:0,truncated:0};restorePersistedSessionForSigning=async e=>this.deps.signingSessionPersistenceMode===`sealed_refresh_v1`?await iM({...e,authMethod:`passkey`},{listExactSealedSessionsForWallet:PM,restoreSealedRecordForWallet:this.restorePasskeySealedRecordForWallet,onListError:FM,onRejectedRecord:IM}):{kind:`completed`,attempted:0,restored:0,deferred:0};restorePasskeySealedRecordForWallet=async e=>{let{record:t,purpose:n}=e;if(n.authMethod!==`passkey`||t.authMethod!==`passkey`)return`deferred`;let r=String(n.thresholdSessionId||``).trim(),i=n.chainTarget;if(!r||t.curve!==`ecdsa`||!wn(t.chainTarget,i)||!g(t.roleLocalMaterialRef.materialActivation,n.materialActivation))return`deferred`;let a=OM({thresholdSessionId:r,chainTarget:i,materialActivation:n.materialActivation}),o=EM.get(a);if(o)return kM(await o,`ready`);let s=Hd({queueByKey:this.deps.thresholdEcdsaSigningQueueByKey,queueKey:Yd({materialActivation:t.roleLocalMaterialRef.materialActivation}),walletId:V(e.walletId),enabled:!0,task:async()=>await this.restorePasskeyEcdsaRecord({walletId:e.walletId,record:t,purpose:{...n,authMethod:`passkey`}})}).finally(()=>{EM.delete(a)});return EM.set(a,s),kM(await s,`restored`)};async restorePasskeyEcdsaRecord(e){let t=e.purpose.thresholdSessionId,n=e.purpose.chainTarget,r=await ps({thresholdSessionId:t,authMethod:`passkey`,curve:`ecdsa`,chainTarget:n});if(!r)return null;try{let r=await MM({walletId:e.walletId,factorAuthority:e.record.authority,materialActivation:e.purpose.materialActivation,nowMs:Date.now()});if(!r)return null;let i=await AM(e.record),a=r.token,o=String(i.authority.walletId).trim();if(!o||o!==String(e.walletId).trim())return null;let s=String(e.record.groupId||``).trim();if(!s)return null;let c={curve:`ecdsa`,authMethod:`passkey`,walletId:o,chainTarget:n,relayerUrl:e.record.relayerUrl,signingSessionSealKeyVersion:Bi(e.record.keyVersion),groupId:s,walletSessionToken:a,ecdsaRestore:i};return await cM({record:e.record,purpose:e.purpose,transport:c,groupId:s,rehydrateWarmSessionMaterial:this.rehydrateWarmSessionMaterial.bind(this),deletePersistedRecord:async()=>await NM({thresholdSessionId:t,chainTarget:n}),recordSessionMaterialRestored:async e=>await this.recordWarmSessionPolicyResult({curve:`ecdsa`,thresholdSessionId:t,chainTarget:n},t,e),readWarmSessionStatusFromWorker:async e=>await this.readWarmSessionStatus({thresholdSessionId:e}),resolveCurrentEcdsaCapabilityRuntime:this.deps.resolveCurrentEcdsaCapabilityRuntime,updatePersistedPolicy:async e=>await this.durableState.updatePersistedPolicy({thresholdSessionId:t,purpose:{curve:`ecdsa`,thresholdSessionId:t,chainTarget:n},...e})})}finally{await os(r)}}getWarmSessionStatuses=async e=>{let t=Array.from(new Set(e.thresholdSessionIds.map(e=>String(e||``).trim()).filter(Boolean)));if(!t.length)return{results:[]};let n=await this.sendMessage({type:`WARM_SESSION_STATUS_BATCH_READ`,id:this.generateMessageId(),payload:{thresholdSessionIds:t}});if(n.success){let e=HM(n.data);if(e)return e}return{results:t.map(e=>({thresholdSessionId:e,result:{ok:!1,code:`worker_error`,message:String(n.success?`Warm-session batch status read failed`:n.error)}}))}};claimWarmSessionMaterial=async e=>{let t=Tj(e),n=await this.sendMessage({type:`WARM_SESSION_MATERIAL_CLAIM`,id:this.generateMessageId(),payload:{thresholdSessionId:t,...typeof e.uses==`number`?{uses:e.uses}:{},...typeof e.consume==`boolean`?{consume:e.consume}:{},curve:e.purpose.curve}});if(!n.success)return{ok:!1,code:`worker_error`,message:n.error};let r=UM(n.data);return r?(await this.recordWarmSessionPolicyResult(e.purpose,t,r),r):{ok:!1,code:`worker_error`,message:`Warm-session claim failed`}};consumeWarmSessionUses=async e=>{let t=Tj(e),n=await this.sendMessage({type:`WARM_SESSION_MATERIAL_CONSUME`,id:this.generateMessageId(),payload:{thresholdSessionId:t,...typeof e.uses==`number`?{uses:e.uses}:{},curve:e.purpose.curve}});if(!n.success)return{ok:!1,code:`worker_error`,message:n.error};let r=VM(n.data);return r?(await this.recordWarmSessionPolicyResult(e.purpose,t,r),r):{ok:!1,code:`worker_error`,message:`Warm-session consume failed`}};clearVolatileWarmSessionMaterial=async e=>{let t=Sh(e);if(t?.scope.kind!==`session`||!this.worker&&!this.initializationPromise)return;let n=await this.sendMessage({type:`WARM_SESSION_VOLATILE_MATERIAL_CLEAR`,id:this.generateMessageId(),payload:t});if(!n.success)throw Error(String(n.error||`Failed to clear volatile warm-session material`))};clearAllVolatileWarmSessionMaterial=async e=>{let t=Sh(e);if(t?.scope.kind!==`all`||!this.worker&&!this.initializationPromise)return;let n=await this.sendMessage({type:`WARM_SESSION_VOLATILE_MATERIAL_CLEAR_ALL`,id:this.generateMessageId(),payload:t});if(!n.success)throw Error(String(n.error||`Failed to clear all volatile warm-session material entries`))};async sealAndPersistWarmSessionMaterial(e){if(this.deps.signingSessionPersistenceMode!==`sealed_refresh_v1`)return{ok:!1,code:`not_enabled`,message:`Passkey MPC session sealing requires sealed refresh mode`};let t=await this.sendMessage({type:`WARM_SESSION_SEAL_AND_PERSIST`,id:this.generateMessageId(),payload:e});if(t.success){let e=WM(t.data);if(e)return e}return{ok:!1,code:`worker_error`,message:String(t.success?`Signing-session seal and persist failed`:t.error)}}persistSigningSessionSealForThresholdSession=async e=>await this.durableState.persistSigningSessionSealForThresholdSession(e);recordWarmSessionPolicyResult=async(e,t,n)=>await this.durableState.recordPolicyResult(e,t,n);async rehydrateWarmSessionMaterial(e){if(this.deps.signingSessionPersistenceMode!==`sealed_refresh_v1`)return{ok:!1,code:`not_enabled`,message:`Passkey MPC session rehydration requires sealed refresh mode`};let t=await this.sendMessage({type:`WARM_SESSION_REHYDRATE`,id:this.generateMessageId(),payload:e});if(t.success){let e=VM(t.data);if(e)return e}return{ok:!1,code:`worker_error`,message:String(t.success?`Warm-session rehydrate failed`:t.error)}}async readWarmSessionStatus(e){let t=await this.sendMessage({type:`WARM_SESSION_STATUS_READ`,id:this.generateMessageId(),payload:e});if(t.success){let e=VM(t.data);if(e)return e}return{ok:!1,code:`worker_error`,message:String(t.success?`Warm-session status read failed`:t.error)}}async ensureWorkerReady(){if(!this.worker&&(this.initializationPromise||=this.createWorker().catch(e=>{throw this.initializationPromise=null,e}),await this.initializationPromise,!this.worker))throw Error(`Passkey MPC session worker failed to initialize`)}async createWorker(){let e=rp(Zk.RUNTIME.PASSKEY_MPC_SESSION_WORKER,{worker:`passkeyMpcSession`,baseOrigin:this.workerBaseOrigin}),t=new Worker(e,{type:`module`,name:`PasskeyMpcSessionWorker`});t.addEventListener(`message`,this.boundHandleWorkerMessage),t.addEventListener(`error`,this.boundHandleWorkerError),this.worker=t}async sendMessage(e,t=6e4){await this.ensureWorkerReady();let n=this.worker;if(!n)throw Error(`Passkey MPC session worker not available`);let r=String(e.id||this.generateMessageId());if(this.pendingRequests.has(r))throw Error(`Duplicate Passkey MPC session worker request id: ${r}`);return await new Promise((i,a)=>{let o=setTimeout(()=>{this.rejectPendingRequest(r,Error(`Passkey MPC session worker communication timeout (${t}ms) for ${e.type}`))},t);this.pendingRequests.set(r,{id:r,timeoutId:o,resolve:i,reject:a});try{n.postMessage({...e,id:r})}catch(e){this.rejectPendingRequest(r,e instanceof Error?e:Error(String(e)))}})}handleWorkerMessage(e){if(e.currentTarget!==this.worker||e.target!==this.worker)return;let t=bu(e.data);if(!t)return;let n=t.id||``;if(!n)return;let r=this.pendingRequests.get(n);r&&(clearTimeout(r.timeoutId),this.pendingRequests.delete(n),r.resolve(t))}handleWorkerError(e){if(e.currentTarget!==this.worker||e.target!==this.worker)return;let t=this.worker;this.worker=null,this.initializationPromise=null,t?.removeEventListener(`message`,this.boundHandleWorkerMessage),t?.removeEventListener(`error`,this.boundHandleWorkerError),t?.terminate();let n=e,r=Error(`Passkey MPC session worker failed: ${String(n.message||`unknown error`)}`);for(let e of this.pendingRequests.values())clearTimeout(e.timeoutId),e.reject(r);this.pendingRequests.clear()}rejectPendingRequest(e,t){let n=this.pendingRequests.get(e);n&&(clearTimeout(n.timeoutId),this.pendingRequests.delete(e),n.reject(t))}generateMessageId(){return`passkey_mpc_session_${Date.now()}_${++this.messageId}`}};function YM(e){return new JM(e)}var XM=class{resolveOperationStepUpCredential;nearKeyMaterialStore;touchIdPrompt;touchConfirm;passkeyMpcSession;nearClient;userPreferencesManager;nonceCoordinator;relayerUrl;chains;nearExplorerUrl;tempoExplorerUrl;evmExplorerUrl;getTheme;workerTransport;constructor(e){this.resolveOperationStepUpCredential=e.resolveOperationStepUpCredential,this.nearKeyMaterialStore=e.nearKeyMaterialStore,this.touchIdPrompt=e.touchIdPrompt,this.touchConfirm=e.touchConfirm,this.passkeyMpcSession=e.passkeyMpcSession,this.nearClient=e.nearClient,this.userPreferencesManager=e.userPreferencesManager,this.nonceCoordinator=e.nonceCoordinator,this.relayerUrl=e.relayerUrl,this.chains=e.chains,this.nearExplorerUrl=e.nearExplorerUrl,this.tempoExplorerUrl=e.tempoExplorerUrl,this.evmExplorerUrl=e.evmExplorerUrl,this.getTheme=e.getTheme,this.workerTransport=e.workerTransport}setWorkerBaseOrigin(e){this.workerTransport.setWorkerBaseOrigin(e)}getContext(){return{resolveOperationStepUpCredential:this.resolveOperationStepUpCredential,requestWorkerOperation:this.requestWorkerOperation.bind(this),nearKeyMaterialStore:this.nearKeyMaterialStore,touchIdPrompt:this.touchIdPrompt,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,nearClient:this.nearClient,userPreferencesManager:this.userPreferencesManager,nonceCoordinator:this.nonceCoordinator,chains:this.chains,getTheme:this.getTheme,rpIdOverride:this.touchIdPrompt.getRpId(),nearExplorerUrl:this.nearExplorerUrl,tempoExplorerUrl:this.tempoExplorerUrl,evmExplorerUrl:this.evmExplorerUrl,relayerUrl:this.relayerUrl}}async clearEcdsaClientWorkerState(e){await this.workerTransport.clearEcdsaClientWorkerState(e)}async prewarmEcdsaRegistrationCrypto(){return await this.workerTransport.prewarmEcdsaRegistrationCrypto()}prewarmNearSigner(){this.workerTransport.prewarmNearSigner()}async prewarmEmailOtpYao(e){return await this.workerTransport.prewarmEmailOtpYao(e)}requestWorkerOperation(e){return this.workerTransport.requestOperation(e)}};const ZM={TIMEOUTS:{DEFAULT:6e4,TRANSACTION:6e4,REGISTRATION:6e4},WORKER:{URL:Zk.RUNTIME.SIGNER_WORKER,TYPE:`module`,NAME:`Web3AuthnSignerWorker`},ECDSA_DERIVATION_CLIENT_WORKER:{URL:Zk.RUNTIME.ECDSA_DERIVATION_CLIENT_WORKER,TYPE:`module`,NAME:`Web3AuthnEcdsaDerivationClientWorker`},ECDSA_PRESIGN_CLIENT_WORKER:{URL:Zk.RUNTIME.ECDSA_PRESIGN_CLIENT_WORKER,TYPE:`module`,NAME:`Web3AuthnEcdsaPresignClientWorker`},ECDSA_ONLINE_CLIENT_WORKER:{URL:Zk.RUNTIME.ECDSA_ONLINE_CLIENT_WORKER,TYPE:`module`,NAME:`Web3AuthnEcdsaOnlineClientWorker`},RETRY:{MAX_ATTEMPTS:3,BACKOFF_MS:1e3}};function QM(e){switch(e){case`evmCrypto`:return`/sdk/workers/evm-crypto.worker.js`;case`tempoSigner`:return`/sdk/workers/tempo-signer.worker.js`}}function $M(e){let t=typeof window<`u`?window:{};switch(e){case`evmCrypto`:return typeof t.__SEAMS_EVM_CRYPTO_WORKER_URL__==`string`?t.__SEAMS_EVM_CRYPTO_WORKER_URL__:void 0;case`tempoSigner`:return typeof t.__SEAMS_TEMPO_SIGNER_WORKER_URL__==`string`?t.__SEAMS_TEMPO_SIGNER_WORKER_URL__:void 0}}function eN(e,t){let n=t?.baseOrigin||np()||(typeof window<`u`?window.location.origin:``)||`https://invalid.local`,r=$M(e)||QM(e);return/^https?:\/\//i.test(r)?r:new URL(r,n).toString()}function tN(e){let t=e?.baseOrigin||np()||(typeof window<`u`?window.location.origin:``)||`https://invalid.local`,n=(typeof window<`u`&&typeof window.__SEAMS_EMAIL_OTP_WORKER_URL__==`string`?String(window.__SEAMS_EMAIL_OTP_WORKER_URL__):``)||`/sdk/workers/email-otp.worker.js`;return/^https?:\/\//i.test(n)?n:new URL(n,t).toString()}function nN(e){let t=e?.baseOrigin||np()||(typeof window<`u`?window.location.origin:``)||`https://invalid.local`,n=(typeof window<`u`&&typeof window.__SEAMS_WALLET_CUSTODY_CEREMONY_WORKER_URL__==`string`?String(window.__SEAMS_WALLET_CUSTODY_CEREMONY_WORKER_URL__):``)||`/sdk/workers/wallet-custody-ceremony.worker.js`;return/^https?:\/\//i.test(n)?n:new URL(n,t).toString()}const rN={AttachDerivationToPresign:`attach_ecdsa_derivation_to_presign_v1`,AttachLinkedHolderToPresign:`attach_linked_holder_to_ecdsa_presign_v1`,AttachPresignToOnline:`attach_ecdsa_presign_to_online_v1`};`A`.repeat(43);function iN(e){return Math.max(0,Math.round(performance.now()-e))}function aN(e){throw Error(`Unsupported Email OTP Yao prewarm result: ${String(e)}`)}function oN(e){throw Error(`Unsupported Email OTP Yao prewarm request: ${String(e)}`)}function sN(e,t,n){console.warn(`[WorkerTransport] operation timed out; resetting worker`,{kind:e,type:String(t),timeoutMs:n})}function cN(e){return ve(e,32,`signer worker request IDs`)}function lN(e){return e?.type===Pu.WORKER_READY||e?.ready===!0}function uN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.progress===!0}function dN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.ok===!0&&`result`in e}function fN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.ok===!1&&typeof e.error==`string`}function pN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.ok===!0&&`result`in e}function mN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.ok===!1&&typeof e.error==`string`}function hN(e){return!!e&&typeof e==`object`&&typeof e.id==`string`&&e.progress===!0&&`payload`in e}const gN=new class{workerBaseOrigin;workers=new Map;pendingByKind=new Map;messageHandlers=new Map;errorHandlers=new Map;presignAuthorityKind=null;presignOnlineConnected=!1;ecdsaRegistrationCryptoPrewarmPromise=null;emailOtpYaoPrewarmPromise=null;setWorkerBaseOrigin(e){if(this.workerBaseOrigin!==e){this.workerBaseOrigin=e,this.emailOtpYaoPrewarmPromise=null;for(let e of Array.from(this.workers.keys()))this.resetWorker(e)}}prewarmNearSigner(){this.getOrCreateWorker(`nearSigner`)}async clearEcdsaClientWorkerState(e){switch(e.kind){case`all`:this.resetWorker(`ecdsaPresignClient`);return;case`wallet`:if(cd(e.walletId),!this.workers.has(`ecdsaPresignClient`))return;await this.requestOperation({kind:`ecdsaPresignClient`,request:{type:zu.ClearWallet,timeoutMs:2e4,payload:{walletId:e.walletId}}});return}}async prewarmEcdsaRegistrationCrypto(){let e=this.ecdsaRegistrationCryptoPrewarmPromise;if(e)return await e;let t=this.requestEcdsaRegistrationCryptoPrewarm();this.ecdsaRegistrationCryptoPrewarmPromise=t;let n=await t;return n.kind===`failed`&&this.ecdsaRegistrationCryptoPrewarmPromise===t&&(this.ecdsaRegistrationCryptoPrewarmPromise=null),n}async requestEcdsaRegistrationCryptoPrewarm(){let e=performance.now();try{return await this.requestDerivationOperation({type:Iu.PrewarmEcdsaRegistrationCrypto,payload:{}}),{kind:`succeeded`,wasmInitMs:iN(e)}}catch{return{kind:`failed`,wasmInitMs:iN(e)}}}async prewarmEmailOtpYao(e={kind:`requested`}){switch(e.kind){case`not_requested`:return{kind:`not_requested`,elapsedMs:0,workerPrewarmMs:0,yaoWasmInitMs:0};case`requested`:break;default:return oN(e)}let t=this.emailOtpYaoPrewarmPromise;if(t)return await t;let n=this.requestEmailOtpYaoPrewarm();this.emailOtpYaoPrewarmPromise=n;let r=await n;return r.kind===`failed`&&this.emailOtpYaoPrewarmPromise===n&&(this.emailOtpYaoPrewarmPromise=null),r}async requestEmailOtpYaoPrewarm(){let e=performance.now();try{let t=await this.requestOperation({kind:`emailOtp`,request:{type:`prewarmEmailOtpRegistrationCrypto`,payload:{}}}),n=iN(e);switch(t.kind){case`succeeded`:return{kind:`succeeded`,elapsedMs:n,workerPrewarmMs:n,yaoWasmInitMs:t.elapsedMs};case`failed`:return{kind:`failed`,elapsedMs:n,workerPrewarmMs:n,yaoWasmInitMs:t.elapsedMs,failureStage:t.failureStage};default:return aN(t)}}catch{let t=iN(e);return{kind:`failed`,elapsedMs:t,workerPrewarmMs:t,yaoWasmInitMs:0,failureStage:`worker_ready`}}}async requestOperation(e){return e.kind===`nearSigner`?await this.requestNearOperation(e.request):e.kind===`ecdsaDerivationClient`?e.request.type===Iu.DisposeLinkedDeviceEcdsaHolderMaterials&&!this.workers.has(`ecdsaDerivationClient`)?{type:Lu.DisposeLinkedDeviceEcdsaHolderMaterialsSuccess,payload:e.request.payload}:await this.requestDerivationOperation(e.request):e.kind===`ecdsaPresignClient`?(this.connectPresignAuthorityChannel(e.request),await this.requestRpcOperation(`ecdsaPresignClient`,e.request)):e.kind===`ecdsaOnlineClient`?(this.connectPresignOnlineChannel(),await this.requestRpcOperation(`ecdsaOnlineClient`,e.request)):e.kind===`evmCrypto`?await this.requestRpcOperation(`evmCrypto`,e.request):e.kind===`tempoSigner`?await this.requestRpcOperation(`tempoSigner`,e.request):e.kind===`walletCustodyCeremony`?await this.requestRpcOperation(`walletCustodyCeremony`,e.request):e.request.type===`clearEmailOtpWarmSessionMaterial`&&!this.workers.has(`emailOtp`)?{ok:!0,cleared:!0}:await this.requestRpcOperation(e.kind,e.request)}async requestNearOperation({type:e,payload:t,onEvent:n,timeoutMs:r=ZM.TIMEOUTS.DEFAULT,transfer:i}){let a=this.getOrCreateWorker(`nearSigner`),o=cN(`nearSigner`);return await new Promise((s,c)=>{let l=setTimeout(()=>{this.rejectRequest(`nearSigner`,o,new Nu({message:`Worker operation timed out after ${r}ms`,code:`TIMEOUT`,workerKind:`nearSigner`})),sN(`nearSigner`,e,r),this.resetWorker(`nearSigner`);try{let e=Math.round(r/1e3);window.postMessage({type:`MODAL_TIMEOUT`,payload:`Timed out after ${e}s, try again`},`*`)}catch{}},r);this.getPendingMap(`nearSigner`).set(o,{resolve:e=>s(e),reject:c,onEvent:n?e=>n(e):void 0,timeoutId:l});try{a.postMessage({id:o,type:e,payload:t},i||[])}catch(e){this.rejectRequest(`nearSigner`,o,new Nu({message:`[nearSigner] failed to postMessage: ${L(e)}`,code:`WORKER_POSTMESSAGE_ERROR`,workerKind:`nearSigner`}))}})}async requestDerivationOperation({type:e,payload:t,timeoutMs:n=ZM.TIMEOUTS.DEFAULT,transfer:r}){let i=this.getOrCreateWorker(`ecdsaDerivationClient`),a=cN(`ecdsaDerivationClient`);return await new Promise((o,s)=>{let c=setTimeout(()=>{this.rejectRequest(`ecdsaDerivationClient`,a,new Nu({message:`Worker operation timed out after ${n}ms`,code:`TIMEOUT`,workerKind:`ecdsaDerivationClient`})),sN(`ecdsaDerivationClient`,e,n),this.resetWorker(`ecdsaDerivationClient`)},n);this.getPendingMap(`ecdsaDerivationClient`).set(a,{resolve:e=>o(e),reject:s,timeoutId:c});try{i.postMessage({id:a,type:e,payload:t},r||[])}catch(e){this.rejectRequest(`ecdsaDerivationClient`,a,new Nu({message:`[ecdsaDerivationClient] failed to postMessage: ${L(e)}`,code:`WORKER_POSTMESSAGE_ERROR`,workerKind:`ecdsaDerivationClient`}))}})}async requestRpcOperation(e,t){let n=this.getOrCreateWorker(e),r=cN(e),i=Math.floor(Number(t.timeoutMs)),a=Number.isFinite(i)&&i>0?i:2e4;return await new Promise((i,o)=>{let s=setTimeout(()=>{this.rejectRequest(e,r,new Nu({message:`Worker operation timed out after ${a}ms`,code:`TIMEOUT`,workerKind:e})),sN(e,t.type,a),this.resetWorker(e)},a);this.getPendingMap(e).set(r,{resolve:e=>i(e),reject:o,onEvent:t.onEvent,timeoutId:s});try{n.postMessage({id:r,type:t.type,payload:t.payload},t.transfer||[])}catch(t){this.rejectRequest(e,r,new Nu({message:`[${e}] failed to postMessage: ${L(t)}`,code:`WORKER_POSTMESSAGE_ERROR`,workerKind:e}))}})}getOrCreateWorker(e){let t=this.workers.get(e);if(t)return t;let n=this.createWorker(e),r=t=>{this.handleWorkerMessage(e,t)},i=t=>{this.handleWorkerError(e,t)};return n.addEventListener(`message`,r),n.addEventListener(`error`,i),this.workers.set(e,n),this.messageHandlers.set(e,r),this.errorHandlers.set(e,i),n}connectPresignAuthorityChannel(e){if(e.type!==zu.ListAvailable&&e.type!==zu.SessionInit)return;let t=this.getOrCreateWorker(`ecdsaPresignClient`),n=this.parsePresignAuthorityKind(e.payload);switch(n){case`role_local_derivation_handle`:this.connectDerivationPresignChannel(t,n);return;case`linked_holder_signing_material`:this.connectDerivationPresignChannel(t,n);return;default:}}parsePresignAuthorityKind(e){if(!A(e)||!A(e.authority))throw Error(`ECDSA presign init authority is required`);switch(e.authority.kind){case`role_local_derivation_handle`:case`linked_holder_signing_material`:return e.authority.kind;default:throw Error(`ECDSA presign init authority kind is invalid`)}}createLinkedHolderPresignAuthorityPortV1(){let e=this.getOrCreateWorker(`ecdsaPresignClient`);fd();let t=new MessageChannel;return e.postMessage({kind:rN.AttachLinkedHolderToPresign,port:t.port1},[t.port1]),t.port2}connectDerivationPresignChannel(e,t){if(this.presignAuthorityKind===t)return;this.presignAuthorityKind!==null&&fd();let n=this.getOrCreateWorker(`ecdsaDerivationClient`),r=new MessageChannel,i=t===`role_local_derivation_handle`?rN.AttachDerivationToPresign:rN.AttachLinkedHolderToPresign;n.postMessage({kind:i,port:r.port1},[r.port1]),e.postMessage({kind:i,port:r.port2},[r.port2]),this.presignAuthorityKind=t}connectPresignOnlineChannel(){if(this.presignOnlineConnected)return;let e=this.getOrCreateWorker(`ecdsaPresignClient`),t=this.getOrCreateWorker(`ecdsaOnlineClient`),n=new MessageChannel;e.postMessage({kind:rN.AttachPresignToOnline,port:n.port1},[n.port1]),t.postMessage({kind:rN.AttachPresignToOnline,port:n.port2},[n.port2]),this.presignOnlineConnected=!0}createWorker(e){try{if(e===`nearSigner`){let e=rp(ZM.WORKER.URL,{worker:`signer`,baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:ZM.WORKER.TYPE,name:ZM.WORKER.NAME})}if(e===`ecdsaDerivationClient`){let e=rp(ZM.ECDSA_DERIVATION_CLIENT_WORKER.URL,{worker:`ecdsaDerivationClient`,baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:ZM.ECDSA_DERIVATION_CLIENT_WORKER.TYPE,name:ZM.ECDSA_DERIVATION_CLIENT_WORKER.NAME})}if(e===`ecdsaPresignClient`){let e=rp(ZM.ECDSA_PRESIGN_CLIENT_WORKER.URL,{worker:`ecdsaPresignClient`,baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:ZM.ECDSA_PRESIGN_CLIENT_WORKER.TYPE,name:ZM.ECDSA_PRESIGN_CLIENT_WORKER.NAME})}if(e===`ecdsaOnlineClient`){let e=rp(ZM.ECDSA_ONLINE_CLIENT_WORKER.URL,{worker:`ecdsaOnlineClient`,baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:ZM.ECDSA_ONLINE_CLIENT_WORKER.TYPE,name:ZM.ECDSA_ONLINE_CLIENT_WORKER.NAME})}if(e===`emailOtp`){let e=tN({baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:`module`,name:`email-otp-worker`})}if(e===`walletCustodyCeremony`){let e=nN({baseOrigin:this.workerBaseOrigin});return new Worker(e,{type:`module`,name:`wallet-custody-ceremony-worker`})}let t=eN(e,{baseOrigin:this.workerBaseOrigin});return new Worker(t,{type:`module`,name:`${e}-worker`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to create ${e} worker: ${n}`)}}handleWorkerMessage(e,t){let n=t.data;if(lN(n))return;if(e===`nearSigner`){this.handleNearWorkerMessage(n);return}if(e===`ecdsaDerivationClient`){this.handleEcdsaDerivationWorkerMessage(n);return}if(hN(n)){let t=this.getPendingMap(e).get(n.id);if(!t)return;t.onEvent?.(n.payload);return}if(pN(n)){this.resolveRequest(e,n.id,n.result);return}if(mN(n)){this.rejectRequest(e,n.id,new Nu({message:n.error||`[${e}] worker error`,code:n.code,coreCode:n.coreCode,workerKind:e}));return}let r=A(n)&&typeof n.id==`string`?n.id:void 0;if(r&&this.getPendingMap(e).has(r)){this.rejectRequest(e,r,new Nu({message:`Malformed worker response frame for request ${r}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:e}));return}this.getPendingMap(e).size!==0&&(this.rejectAllPending(e,new Nu({message:`Unknown worker response frame: ${JSON.stringify(n)}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:e})),this.resetWorker(e))}handleNearWorkerMessage(e){if(uN(e)){let t=this.getPendingMap(`nearSigner`).get(e.id);if(!t)return;t.onEvent?.(e.payload);return}if(dN(e)){this.resolveNearResponse(e.id,e.result);return}if(fN(e)){this.rejectRequest(`nearSigner`,e.id,new Nu({message:e.error,code:e.code,coreCode:e.coreCode,workerKind:`nearSigner`}));return}let t=A(e)&&typeof e.id==`string`?e.id:void 0;if(t&&this.getPendingMap(`nearSigner`).has(t)){this.rejectRequest(`nearSigner`,t,new Nu({message:`Malformed worker response frame for request ${t}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:`nearSigner`}));return}this.getPendingMap(`nearSigner`).size!==0&&(this.rejectAllPending(`nearSigner`,new Nu({message:`Unknown worker response frame: ${JSON.stringify(e)}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:`nearSigner`})),this.resetWorker(`nearSigner`))}handleEcdsaDerivationWorkerMessage(e){if(pN(e)){this.resolveRequest(`ecdsaDerivationClient`,e.id,e.result);return}if(mN(e)){this.rejectRequest(`ecdsaDerivationClient`,e.id,new Nu({message:e.error||`[ecdsaDerivationClient] worker error`,code:e.code,coreCode:e.coreCode,workerKind:`ecdsaDerivationClient`}));return}let t=A(e)&&typeof e.id==`string`?e.id:void 0;if(t&&this.getPendingMap(`ecdsaDerivationClient`).has(t)){this.rejectRequest(`ecdsaDerivationClient`,t,new Nu({message:`Malformed worker response frame for request ${t}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:`ecdsaDerivationClient`}));return}this.getPendingMap(`ecdsaDerivationClient`).size!==0&&(this.rejectAllPending(`ecdsaDerivationClient`,new Nu({message:`Unknown worker response frame: ${JSON.stringify(e)}`,code:`WORKER_PROTOCOL_ERROR`,workerKind:`ecdsaDerivationClient`})),this.resetWorker(`ecdsaDerivationClient`))}resolveNearResponse(e,t){this.getPendingMap(`nearSigner`).get(e)&&this.resolveRequest(`nearSigner`,e,t)}handleWorkerError(e,t){let n=new Nu({message:`[${e}] worker runtime error: ${t.message||`unknown error`}`,code:`WORKER_RUNTIME_ERROR`,workerKind:e});this.rejectAllPending(e,n),this.resetWorker(e)}getPendingMap(e){let t=this.pendingByKind.get(e);if(t)return t;let n=new Map;return this.pendingByKind.set(e,n),n}resolveRequest(e,t,n){let r=this.getPendingMap(e).get(t);r&&(this.clearRequest(e,t),r.resolve(n))}rejectRequest(e,t,n){let r=this.getPendingMap(e).get(t);r&&(this.clearRequest(e,t),r.reject(n))}rejectAllPending(e,t){let n=Array.from(this.getPendingMap(e).keys());for(let r of n)this.rejectRequest(e,r,t)}clearRequest(e,t){let n=this.getPendingMap(e).get(t);n&&(n.timeoutId&&clearTimeout(n.timeoutId),this.getPendingMap(e).delete(t))}resetWorker(e){e===`ecdsaDerivationClient`?(this.presignAuthorityKind=null,this.resetWorker(`ecdsaPresignClient`)):e===`ecdsaPresignClient`?(this.presignAuthorityKind=null,this.presignOnlineConnected=!1,this.resetWorker(`ecdsaOnlineClient`),this.terminateWorkerOnly(`ecdsaDerivationClient`)):e===`ecdsaOnlineClient`&&(this.presignOnlineConnected=!1),(e===`ecdsaDerivationClient`||e===`ecdsaPresignClient`||e===`ecdsaOnlineClient`)&&fd(),this.terminateWorkerOnly(e)}terminateWorkerOnly(e){let t=this.workers.get(e);if(!t)return;this.rejectAllPending(e,Error(`${e} worker was reset`));let n=this.messageHandlers.get(e),r=this.errorHandlers.get(e);n&&t.removeEventListener(`message`,n),r&&t.removeEventListener(`error`,r),t.terminate(),this.workers.delete(e),this.messageHandlers.delete(e),this.errorHandlers.delete(e),e===`walletCustodyCeremony`&&eo()}};function _N(){return gN}function vN(e){let t=String(e.metadata?.walletId||``).trim();if(!t)return null;try{return V(t)}catch{return null}}function yN(e){let t=[],n=new Set;for(let r of e){let e=vN(r);if(!e)continue;let i=String(e);n.has(i)||(n.add(i),t.push(e))}return t}async function bN(e){let t=yN(await e.store.listAccountSignersByProfile({profileId:e.profileId,status:`active`}).catch(()=>[]));return t.length===1?t[0]:null}var xN=class{confirmationConfigChangeListeners=new Set;currentWalletChangeListeners=new Set;currentWalletId=null;lifecycle={kind:`active`,revision:0};writeQueue=Promise.resolve();confirmationConfig=Rt;unsubscribeFromIndexedDB;constructor(e){this.deps=e,this.subscribeToIndexedDBChanges()}onConfirmationConfigChange(e){return this.confirmationConfigChangeListeners.add(e),()=>{this.confirmationConfigChangeListeners.delete(e)}}onCurrentWalletChange(e){return this.currentWalletChangeListeners.add(e),()=>{this.currentWalletChangeListeners.delete(e)}}notifyConfirmationConfigChange(e){if(this.confirmationConfigChangeListeners.size!==0)for(let t of this.confirmationConfigChangeListeners)try{t(e)}catch{}}notifyCurrentWalletChange(e){if(this.currentWalletChangeListeners.size!==0)for(let t of this.currentWalletChangeListeners)try{t(e)}catch{}}sanitizeConfirmationConfig(e){if(!e)return{};let{uiMode:t,behavior:n,autoProceedDelay:r}=e,i={};return t!=null&&(i.uiMode=t),n!=null&&(i.behavior=n),r!=null&&(i.autoProceedDelay=r),i}mergeConfirmationConfig(e,t){let n={...e,...t};return{uiMode:n.uiMode??Rt.uiMode,behavior:n.behavior??Rt.behavior,autoProceedDelay:n.autoProceedDelay??Rt.autoProceedDelay}}async initFromIndexedDB(){await this.loadUserSettings().catch(e=>{console.warn(`[SigningEngine]: Failed to initialize user settings:`,e)})}subscribeToIndexedDBChanges(){this.unsubscribeFromIndexedDB=this.deps.store.onChange(e=>{this.handleIndexedDBEvent(e).catch(e=>{console.warn(`[SigningEngine]: Error handling IndexedDB event:`,e)})})}async handleIndexedDBEvent(e){switch(e.type){case`preferences-updated`:case`user-updated`:this.currentWalletId&&String(e.accountId)===String(this.currentWalletId)&&await this.reloadUserSettings();break;case`user-deleted`:this.currentWalletId&&String(e.accountId)===String(this.currentWalletId)&&(this.invalidateReads(),this.currentWalletId=null,this.confirmationConfig=Rt,this.notifyCurrentWalletChange(null),this.notifyConfirmationConfigChange(this.confirmationConfig));break}}destroy(){this.lifecycle={kind:`disposed`},this.unsubscribeFromIndexedDB&&=(this.unsubscribeFromIndexedDB(),void 0),this.confirmationConfigChangeListeners.clear(),this.currentWalletChangeListeners.clear()}getCurrentWalletId(){return this.currentWalletId}getConfirmationConfig(){return this.confirmationConfig}setCurrentWallet(e){this.invalidateReads();let t=this.currentWalletId;this.currentWalletId=e,t!==e&&(this.confirmationConfig=Rt,this.notifyCurrentWalletChange(e),this.notifyConfirmationConfigChange(this.confirmationConfig)),this.deps.store.isDisabled()||this.loadSettingsForWallet(e).catch(()=>void 0)}projectCurrentWallet(e){let t=this.currentWalletId;this.setCurrentWallet(e),t&&String(t)===String(e)&&this.notifyCurrentWalletChange(e)}assertActive(){if(this.lifecycle.kind===`disposed`)throw Error(`Wallet preferences are disposed`)}invalidateReads(){if(this.lifecycle.kind===`disposed`)throw Error(`Wallet preferences are disposed`);return++this.lifecycle.revision}async loadSettingsForWallet(e){if(this.deps.store.isDisabled())return;let t=this.invalidateReads(),n=await this.deps.store.getWalletPreferences(e);this.lifecycle.kind!==`active`||this.lifecycle.revision!==t||this.currentWalletId!==e||(this.confirmationConfig=this.mergeConfirmationConfig(Rt,this.sanitizeConfirmationConfig(n.confirmationConfig)),this.notifyConfirmationConfigChange(this.confirmationConfig))}async reloadUserSettings(){let e=this.getCurrentWalletId();e&&await this.loadSettingsForWallet(e)}setConfirmationBehavior(e){return this.setConfirmationConfig({behavior:e})}setConfirmationConfig(e){this.invalidateReads();let t=this.currentWalletId,n=this.sanitizeConfirmationConfig(e),r=this.writeQueue.then(this.commitConfirmationConfig.bind(this,t,n));return this.writeQueue=r.then(SN,SN),r}async commitConfirmationConfig(e,t){this.assertActive();let n=this.confirmationConfig;if(e!==null){if(this.deps.store.isDisabled())throw Error(`Wallet preference storage is unavailable`);let t=await this.deps.store.getWalletPreferences(e);n=this.mergeConfirmationConfig(Rt,this.sanitizeConfirmationConfig(t.confirmationConfig))}let r=this.mergeConfirmationConfig(n,t);if(e!==null&&(this.assertActive(),await this.deps.store.updateWalletPreferences({walletId:e,preferences:{confirmationConfig:r}})===null))throw Error(`Wallet preference target does not exist`);this.lifecycle.kind===`active`&&this.currentWalletId===e&&(this.invalidateReads(),this.confirmationConfig=r,this.notifyConfirmationConfigChange(r))}async loadUserSettings(){if(this.deps.store.isDisabled())return;let e=this.invalidateReads(),t=await Vc(this.deps.store).catch(()=>null);if(!t){console.debug(`[SigningEngine]: No last user found, using default settings`);return}let n=await bN({store:this.deps.store,profileId:t.profileId});if(!n){console.debug(`[SigningEngine]: Last profile has no wallet-bound signer metadata`);return}this.lifecycle.kind!==`active`||this.lifecycle.revision!==e||(this.currentWalletId=n,this.confirmationConfig=Rt,this.notifyCurrentWalletChange(n),this.notifyConfirmationConfigChange(this.confirmationConfig),await this.loadSettingsForWallet(n))}};function SN(){}function CN(e){let t=e.seamsWebConfigs.wallet,n=new Uf(t.mode===`direct`?t.rpId:t.iframe.rpIdOverride),r=new xN({store:e.stores.userPreferencesStore}),i=e.seamsWebConfigs.network.chains,a=Ou({evmNonceBackend:xf({chains:i}),nearClient:e.nearClient,nonceLaneCoordinationStore:e.stores.nonceLaneCoordinationStore}),o=Ge(i,`near`),s=Ge(i,`tempo`),c=Ge(i,`evm`),l=YM({signingSessionPersistenceMode:e.seamsWebConfigs.signing.sessionPersistenceMode,thresholdEcdsaSigningQueueByKey:e.thresholdEcdsaSigningQueueByKey,resolveCurrentEcdsaCapabilityRuntime:e.resolveActiveEcdsaCapabilityRuntime}),u=oj({},{touchIdPrompt:n,nearClient:e.nearClient,webauthnCredentialStore:e.stores.webauthnCredentialStore,passkeyAuthenticatorStore:e.stores.passkeyAuthenticatorStore,userPreferencesManager:r,nonceCoordinator:a,operationStepUpPreparation:uf,nearImplicitAccountFunding:hf,relayerUrl:e.seamsWebConfigs.network.relayer.url,chains:i,rpIdOverride:n.getRpId(),nearExplorerUrl:o,tempoExplorerUrl:s,evmExplorerUrl:c,getTheme:e.getTheme,getAppearance:e.getAppearance,loadEcdsaRoleLocalReadyRecord:e.loadEcdsaRoleLocalReadyRecord,surfaceMeasurementBinding:{kind:`disabled`}});return{touchIdPrompt:n,userPreferencesManager:r,nonceCoordinator:a,touchConfirm:u,passkeyMpcExport:wj(u.getContext()),passkeyMpcSession:l,signerWorkerManager:new XM({resolveOperationStepUpCredential:e.resolveOperationStepUpCredential,nearKeyMaterialStore:e.stores.nearKeyMaterialStore,touchIdPrompt:n,touchConfirm:u,passkeyMpcSession:l,nearClient:e.nearClient,userPreferencesManager:r,nonceCoordinator:a,relayerUrl:e.seamsWebConfigs.network.relayer.url,workerTransport:_N(),chains:i,nearExplorerUrl:o,tempoExplorerUrl:s,evmExplorerUrl:c,getTheme:e.getTheme})}}function wN(e){return{availableLanes:{activeWalletAuthorityEcdsaRuntimeReadPorts:Tg,ed25519YaoPublicCapabilityLanes:e.ed25519YaoPublicCapabilityLanes,isEd25519YaoPublicCapabilityActive:e.isEd25519YaoPublicCapabilityActive,readActiveWalletSessionAuthorization:e.readActiveWalletSessionAuthorization,listEcdsaSigningCapabilitiesForWallet:e.listEcdsaSigningCapabilitiesForWallet},signingSessionSeal:e.seamsWebConfigs.signing.sessionSeal.mode===`sealed_refresh_v1`?{groupId:Ze}:void 0,getConfiguredEcdsaChainTargets:()=>Tn(e.seamsWebConfigs.network.chains),discovery:{emailOtp:t=>e.emailOtpSessions.discoverPersistedSessionsForWallet(t),passkey:t=>e.passkeyMpcSession.discoverPersistedSessionsForWallet(t)}}}function TN(e){let{capability:t}=e;if(!t.auth||!e.hasWalletSessionAuthorization)return t.capability===`ed25519`?`authorization_required`:`auth_missing`;if(e.emailOtpSingleUseConsumed)return`prf_missing`;let n=t.prfClaim;if(t.capability===`ed25519`){let e=al({remainingUses:t.runtime.remainingUses,expiresAtMs:t.runtime.expiresAtMs});return e===`expired`||e===`exhausted`?`authorization_required`:n?.state===`unavailable`?`prf_unavailable`:n?.state===`warm`?`ready`:`prf_missing`}let r=al({remainingUses:t.runtime.remainingUses,expiresAtMs:t.runtime.expiresAtMs});return r===`expired`||r===`exhausted`?`authorization_required`:n?n.state===`unavailable`?`prf_unavailable`:n.state===`warm`?`ready`:`prf_missing`:`prf_missing`}function EN(e){let{capability:t}=e,n=t.runtime,r=t.auth,i=t.prfClaim,a=String(n?.thresholdSessionId||``).trim();if(!n){if(t.state!==`missing`&&t.state!==`invalid`)throw Error(`[WarmSessionStore] invalid ${e.label} capability: missing runtime must be missing or invalid`);if(r)throw Error(`[WarmSessionStore] invalid ${e.label} capability: missing runtime cannot have auth`);if(i)throw Error(`[WarmSessionStore] invalid ${e.label} capability: missing runtime cannot have warm-session status`);return}if(String(n.walletId)!==String(e.walletId))throw Error(`[WarmSessionStore] invalid ${e.label} capability: runtime wallet does not match envelope wallet`);if(!a)throw Error(`[WarmSessionStore] invalid ${e.label} capability: runtime is missing thresholdSessionId`);if(r){if(String(r.session.walletId)!==String(n.walletId))throw Error(`[WarmSessionStore] invalid ${e.label} capability: authorization wallet does not match runtime`);if(r.selectedAuthMethod.kind!==n.factor.kind)throw Error(`[WarmSessionStore] invalid ${e.label} capability: authorization factor does not match runtime`)}if(i){if(String(i.thresholdSessionId||``).trim()!==a)throw Error(`[WarmSessionStore] invalid ${e.label} capability: warm-session status thresholdSessionId does not match record thresholdSessionId`);switch(i.state){case`warm`:if(i.remainingUses<=0||i.expiresAtMs<=0)throw Error(`[WarmSessionStore] invalid ${e.label} capability: warm warm-session status requires positive remainingUses and expiresAtMs`);break;case`unavailable`:if(!String(i.code||``).trim())throw Error(`[WarmSessionStore] invalid ${e.label} capability: unavailable warm-session status requires a code`);break;case`missing`:case`expired`:case`exhausted`:break;default:throw Error(`[WarmSessionStore] unsupported warm-session claim state`)}}let o=TN({capability:t,hasWalletSessionAuthorization:!!r,emailOtpSingleUseConsumed:!1});if(t.state!==o)throw Error(`[WarmSessionStore] invalid ${e.label} capability: state=${t.state} does not match derived state=${o}`)}function DN(e){let{capability:t}=e,n=t.runtime,r=t.manifest.durableMaterial.roleLocalPublicFacts;if(String(n.walletId)!==String(e.walletId))throw Error(`[WarmSessionStore] invalid ${e.label} capability: runtime wallet does not match envelope wallet`);if(String(t.key.walletId)!==String(e.walletId))throw Error(`[WarmSessionStore] invalid ${e.label} capability: key wallet does not match envelope wallet`);if(String(t.key.thresholdOwnerAddress).toLowerCase()!==String(r.ethereumAddress).toLowerCase())throw Error(`[WarmSessionStore] invalid ${e.label} capability: key owner address does not match manifest public facts`);if(t.state===`authorization_required`){if(t.lane)throw Error(`[WarmSessionStore] invalid ${e.label} capability: authorization_required cannot carry a lane`);return}if(!t.lane)throw Error(`[WarmSessionStore] invalid ${e.label} capability: authorized ECDSA capability requires a lane`);if(!wn(t.lane.identity.signer.chainTarget,n.chainTarget))throw Error(`[WarmSessionStore] invalid ${e.label} capability: lane chain target does not match runtime chain target`);if(String(t.lane.materialActivation.activationId)!==String(n.materialActivation.activationId))throw Error(`[WarmSessionStore] invalid ${e.label} capability: lane material activation does not match runtime`);if(Xt(t.lane.auth)!==n.authBinding.kind)throw Error(`[WarmSessionStore] invalid ${e.label} capability: lane authMethod does not match sealed auth binding`);if(t.emailOtpAuthContext&&n.authBinding.kind!==`email_otp`)throw Error(`[WarmSessionStore] invalid ${e.label} capability: non-email_otp binding cannot carry email-otp auth context`)}function ON(e){let{capability:t}=e;if(t.state!==`missing`){if(t.capability===`ecdsa`){if(t.state===`invalid`)return;DN({walletId:e.walletId,label:e.label,capability:t});return}EN(e)}}function kN(e){return ON({walletId:e.walletId,label:`ed25519`,capability:e.capabilities.ed25519}),ON({walletId:e.walletId,label:`ecdsa.evm`,capability:e.capabilities.ecdsa.evm}),ON({walletId:e.walletId,label:`ecdsa.tempo`,capability:e.capabilities.ecdsa.tempo}),e}function AN(e){switch(e.kind){case`voiceid`:return{kind:`voiceid`,walletAuthMethodId:e.voiceIdAuthority.bindingId,deviceKeyId:e.voiceIdAuthority.factor.deviceKeyId};case`passkey`:return{kind:`passkey`,rpId:wa(e.rpId),credentialIdB64u:e.credentialIdB64u};case`email_otp`:return{kind:`email_otp`,providerSubjectId:e.providerSubjectId};default:throw Error(`[WarmSessionStore] unsupported ECDSA runtime auth binding`)}}async function jN(e){if(!e.resolve||e.resolution.kind!==`resolved`)return null;try{return await e.resolve({walletId:e.walletId,chainTarget:e.resolution.runtime.chainTarget,materialActivation:e.resolution.manifest.activation.materialActivation},e.statusReads)}catch{return null}}function MN(e){return e.kind===`resolved`?Gh({thresholdSessionId:e.runtime.sealedRecord.thresholdSessionId,remainingUses:e.runtime.remainingUses,expiresAtMs:e.runtime.expiresAtMs}):null}function NN(e){async function t(t,n){let r=e.resolveActiveEd25519WalletSessionAuthorization;if(!r)return null;try{return await r(t,n)}catch{return null}}function n(e){if(e.resolution.kind===`missing`)return{capability:`ed25519`,runtime:null,auth:null,prfClaim:null,state:`missing`};if(e.resolution.kind===`conflict`||e.resolution.kind===`corrupt`)return{capability:`ed25519`,runtime:null,auth:null,prfClaim:null,invalidReason:e.resolution.kind===`conflict`?`exact_record_conflict`:`corrupt`,state:`invalid`};let t=e.resolution.runtime,n=Bh({runtime:t,auth:e.auth,prfClaim:e.prfClaim});if(n===`authorization_required`)return{capability:`ed25519`,runtime:t,auth:null,prfClaim:e.prfClaim,state:n};if(n===`missing`||n===`invalid`)throw Error(`[WarmSessionStore] Ed25519 capability state=${n} with resolved material`);if(!e.auth)throw Error(`[WarmSessionStore] Ed25519 capability state=${n} requires active authorization`);return{capability:`ed25519`,runtime:t,auth:e.auth,prfClaim:e.prfClaim,state:n}}function r(e){if(e.resolution.kind===`blocked`){let t=e.resolution.reason;return t===`missing_capability`||t===`missing_material`?{capability:`ecdsa`,manifest:null,runtime:null,key:null,lane:null,auth:null,prfClaim:null,state:`missing`}:{capability:`ecdsa`,manifest:null,runtime:null,key:null,lane:null,auth:null,prfClaim:null,invalidReason:t,state:`invalid`}}let{manifest:t,runtime:n}=e.resolution,r=t.durableMaterial.roleLocalPublicFacts,i=Pa({walletId:n.walletId,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:String(r.signingRootId),signingRootVersion:String(r.signingRootVersion),participantIds:[...n.participantIds],thresholdOwnerAddress:String(r.ethereumAddress)}),a=n.authBinding,o=Vh({runtime:n,auth:e.authorization,prfClaim:e.prfClaim,emailOtpAuthContext:null});if(o===`authorization_required`)return{capability:`ecdsa`,manifest:t,runtime:n,key:i,lane:null,auth:null,prfClaim:e.prfClaim,emailOtpAuthContext:null,state:o};if(!e.authorization)throw Error(`[WarmSessionStore] ECDSA capability without authorization must be authorization_required`);if(o===`missing`||o===`invalid`)throw Error(`[WarmSessionStore] ECDSA capability state=${o} with resolved material`);let s=Sl({key:i,materialActivation:n.materialActivation,keyHandle:n.keyHandle,walletId:n.walletId,auth:AN(a),authorization:e.authorization,chainTarget:n.chainTarget});if(o===`ready`||o===`material_pending`){if(!e.prfClaim||e.prfClaim.state!==`warm`)throw Error(`[WarmSessionStore] ECDSA capability state=${o} requires a warm PRF claim`);return{capability:`ecdsa`,manifest:t,runtime:n,key:i,lane:s,auth:e.authorization,prfClaim:e.prfClaim,state:o}}return o===`auth_missing`?{capability:`ecdsa`,manifest:t,runtime:n,key:i,lane:s,auth:null,prfClaim:e.prfClaim,state:o}:{capability:`ecdsa`,manifest:t,runtime:n,key:i,lane:s,auth:e.authorization,prfClaim:e.prfClaim,state:o}}async function i(i){let a=V(i),o=new Ja,[s,c,l,u]=await Promise.all([Ns(a),t(a,o),e.resolveActiveEcdsaCapabilityRuntimeForChain({walletId:a,chain:`evm`}),e.resolveActiveEcdsaCapabilityRuntimeForChain({walletId:a,chain:`tempo`})]),[d,f]=await Promise.all([jN({resolve:e.resolveActiveEcdsaWalletSessionAuthorization,walletId:a,resolution:l,statusReads:o}),jN({resolve:e.resolveActiveEcdsaWalletSessionAuthorization,walletId:a,resolution:u,statusReads:o})]);return kN({walletId:a,capabilities:{ed25519:n({resolution:s,auth:c,prfClaim:s.kind===`resolved`?await e.statusReader.readEd25519WarmSessionClaim(s.runtime):null}),ecdsa:{evm:r({resolution:l,prfClaim:MN(l),authorization:d}),tempo:r({resolution:u,prfClaim:MN(u),authorization:f})}},updatedAtMs:Date.now()})}async function a(t){let n=await e.resolveActiveEcdsaCapabilityRuntime({walletId:t.lane.signer.walletId,chainTarget:t.lane.signer.chainTarget});return r({resolution:n,prfClaim:MN(n),authorization:t.authorization})}function o(){return e.signingSessionSeal.seal===`configured`?{groupId:String(e.signingSessionSeal.groupId||``).trim()}:{groupId:``}}async function s(t){let n=await e.resolveActiveEcdsaCapabilityRuntime({walletId:t.lane.signer.walletId,chainTarget:t.lane.signer.chainTarget});if(n.kind!==`resolved`)return null;let r=o();return Uh({runtime:n.runtime,auth:t.authorization,groupId:r.groupId})}return{getWarmSession:i,getEcdsaCapabilityForLane:a,resolveEcdsaSealTransportForLane:s}}function PN(e){switch(e.factor.kind){case z.passkey:return{authMethod:z.passkey};case z.emailOtp:return{authMethod:z.emailOtp,retention:`session`};default:throw e.factor,Error(`[WarmSessionStore] unsupported Ed25519 runtime factor`)}}async function FN(e){return Hs({runtime:e.runtime,authorization:e.authorization})}function IN(e){let t=Ih(e.touchConfirm);async function n(e){let t=String(e.thresholdSessionId);return await r({authMethod:e.factor.kind,thresholdSessionId:t,materialActivation:e.sealedRecord.ed25519Restore.materialActivation})}async function r(n){if(n.authMethod===z.emailOtp){let t=await e.getEmailOtpWarmSessionStatus({kind:`ed25519_yao`,thresholdSessionId:n.thresholdSessionId,materialActivation:n.materialActivation}).catch(()=>({ok:!1,code:`worker_error`,message:`worker_error`}));return zh({thresholdSessionId:n.thresholdSessionId,status:t})}return await Rh(t,n.thresholdSessionId)}async function i(e){let t=e.runtime,r=String(t.thresholdSessionId),i=PN(t);if(!e.authorization||!await FN({runtime:t,authorization:e.authorization}))return{sessionId:r,status:`unavailable`,statusCode:`auth_missing`,...i};if(e.authorization.status.expiresAtMs<=e.nowMs||t.expiresAtMs<=e.nowMs)return{sessionId:r,status:`expired`,expiresAtMs:Math.min(e.authorization.status.expiresAtMs,t.expiresAtMs),...i};if(t.remainingUses<=0)return{sessionId:r,status:`exhausted`,remainingUses:0,expiresAtMs:t.expiresAtMs,...i};let a=Hh({sessionId:r,claim:await n(t),authMethod:i.authMethod,retention:i.retention??null});return a.status===`not_found`?{sessionId:r,status:`active`,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs,...i}:a}return{getEd25519SigningSessionStatus:i,readEd25519WarmSessionClaim:n}}function LN(){return{ok:!1,code:`not_found`,message:`Email OTP warm-session status reader is unavailable`}}function RN(e){let t=Ih(e.touchConfirm),n=e.getEmailOtpWarmSessionStatus;return n?{runtimeStatus:`configured`,touchConfirm:t,getEmailOtpWarmSessionStatus:n}:t?.statusPort===`single`||t?.statusPort===`single_and_batch`?{runtimeStatus:`configured`,touchConfirm:t,getEmailOtpWarmSessionStatus:async e=>await t.getWarmSessionStatus({thresholdSessionId:e.thresholdSessionId})}:t?{runtimeStatus:`configured`,touchConfirm:t,getEmailOtpWarmSessionStatus:async()=>LN()}:{runtimeStatus:`no_runtime_status`,touchConfirm:null,getEmailOtpWarmSessionStatus:async()=>LN()}}function zN(e){let t=String(e?.groupId||``).trim();return t?{seal:`configured`,groupId:t}:{seal:`unconfigured`}}function BN(e){let t=RN(e),n=IN({touchConfirm:t.touchConfirm,getEmailOtpWarmSessionStatus:t.getEmailOtpWarmSessionStatus});return NN({resolveActiveEcdsaCapabilityRuntime:e.resolveActiveEcdsaCapabilityRuntime,resolveActiveEcdsaCapabilityRuntimeForChain:e.resolveActiveEcdsaCapabilityRuntimeForChain,statusReader:n,signingSessionSeal:zN(e.signingSessionSeal),...e.resolveActiveEcdsaWalletSessionAuthorization?{resolveActiveEcdsaWalletSessionAuthorization:e.resolveActiveEcdsaWalletSessionAuthorization}:{},...e.resolveActiveEd25519WalletSessionAuthorization?{resolveActiveEd25519WalletSessionAuthorization:e.resolveActiveEd25519WalletSessionAuthorization}:{}})}function VN(e){return!e.ok&&(e.code===`not_found`||e.code===`worker_error`)}function HN(e){let{base:t,secondary:n}=e,r=async e=>{let r=await n.readWarmSessionStatusOnly(e.thresholdSessionId);return VN(r)?await t.getWarmSessionStatus(e):r},i=async e=>{let r=await Promise.all(e.thresholdSessionIds.map(async e=>({thresholdSessionId:e,result:await n.readWarmSessionStatusOnly(e)}))),i=r.filter(e=>VN(e.result)).map(e=>e.thresholdSessionId),a=i.length===0?{results:[]}:typeof t.getWarmSessionStatuses==`function`?await t.getWarmSessionStatuses({thresholdSessionIds:i}):{results:await Promise.all(i.map(async e=>({thresholdSessionId:e,result:await t.getWarmSessionStatus({thresholdSessionId:e})})))},o=new Map(a.results.map(e=>[e.thresholdSessionId,e]));return{results:r.map(e=>VN(e.result)&&o.get(e.thresholdSessionId)||e)}},a=async e=>{await Promise.all([t.clearVolatileWarmSessionMaterial(e).catch(()=>void 0),n.clearVolatileWarmSessionMaterial(e).catch(()=>void 0)])};return new Proxy(t,{get:(e,t,n)=>{if(t===`getWarmSessionStatus`)return r;if(t===`getWarmSessionStatuses`)return i;if(t===`clearVolatileWarmSessionMaterial`)return a;let o=Reflect.get(e,t,n);return typeof o==`function`?o.bind(e):o}})}function UN(e){let{base:t,secondary:n}=e;return{getWarmSessionStatus:async e=>{let r=await n.readWarmSessionStatusOnly(e.thresholdSessionId);return VN(r)?await t.getWarmSessionStatus(e):r},getWarmSessionStatuses:async e=>{let r=Array.from(new Set((Array.isArray(e.thresholdSessionIds)?e.thresholdSessionIds:[]).map(e=>String(e||``).trim()).filter(Boolean))),i=await Promise.all(r.map(async e=>({thresholdSessionId:e,result:await n.readWarmSessionStatusOnly(e)}))),a=i.filter(e=>VN(e.result)).map(e=>e.thresholdSessionId),o=a.length===0?{results:[]}:await t.getWarmSessionStatuses({thresholdSessionIds:a}),s=new Map(o.results.map(e=>[e.thresholdSessionId,e.result]));return{results:i.map(e=>VN(e.result)?{thresholdSessionId:e.thresholdSessionId,result:s.get(e.thresholdSessionId)||e.result}:e)}}}}function WN(e){return{queueByWallet:e.queueByWallet,activationDeps:e.activationDeps,persistEcdsaRoleLocalReadyRecord:e.persistEcdsaRoleLocalReadyRecord}}function GN(e){return{getWarmSession:t=>e.capabilityReader.getWarmSession(t),discoverPersistedSessionsForWallet:e.passkeyMpcSession.discoverPersistedSessionsForWallet.bind(e.passkeyMpcSession)}}function KN(e){let t=du(e),n=mu(e);return e.source===`registration`?{kind:`key_enrollment_bootstrap_parity`,walletId:t,chainTarget:n}:e.operationIntent===Zt.TransactionSign?{kind:`transaction_bootstrap_parity`,walletId:t,chainTarget:n,operationIntent:Zt.TransactionSign}:e.kind===`email_otp_ecdsa_bootstrap`?{kind:`email_otp_bootstrap_parity`,walletId:t,chainTarget:n,authMethod:`email_otp`}:{kind:`default_bootstrap_parity`,walletId:t,chainTarget:n}}async function qN(e,t){return await lu(WN(e),t)}function JN(e){let t=e.error instanceof Error?e.error.message:String(e.error||`unknown error`);return{ok:!1,code:YN(e.error),chainTargetKey:e.chainTargetKey,errorMessage:t}}function YN(e){let t=pd(e);if(t)switch(t.kind){case`expired`:return`sealed_record_expired`;case`exhausted`:return`sealed_record_exhausted`;case`missing`:case`invalid`:case`unavailable`:return`sealed_restore_failed`}switch(e&&typeof e==`object`?Reflect.get(e,`code`):void 0){case`expired`:return`sealed_record_expired`;case`exhausted`:return`sealed_record_exhausted`;default:return`sealed_restore_failed`}}async function XN(e,t,n){let r=n.chainTarget,i=H(r);if((await e.getWarmSession(t)).capabilities.ed25519.state!==`ready`)return{ok:!1,code:`missing_exact_material`,chainTargetKey:i};try{await e.discoverPersistedSessionsForWallet({kind:`discover_wallet_ecdsa_signing_sessions`,walletId:t,ecdsaChainTargets:[r],maxRecords:1})}catch(e){return console.warn(`[SigningEngine][ecdsa] reuse warm sealed discovery failed`,{walletId:t,chainTarget:r,error:e instanceof Error?e.message:String(e||`unknown error`)}),JN({chainTargetKey:i,error:e})}return{ok:!1,code:`missing_exact_material`,chainTargetKey:i}}function ZN(e){switch(e.code){case`missing_exact_material`:return`[SigningEngine][ecdsa] reuse_warm_ecdsa_bootstrap requires restored passkey ECDSA material for ${e.chainTargetKey}`;case`sealed_restore_failed`:return`[SigningEngine][ecdsa] reuse_warm_ecdsa_bootstrap sealed restore failed for ${e.chainTargetKey}: ${e.errorMessage||`unknown error`}`;case`sealed_record_expired`:return`[SigningEngine][ecdsa] reuse_warm_ecdsa_bootstrap sealed record expired for ${e.chainTargetKey}`;case`sealed_record_exhausted`:return`[SigningEngine][ecdsa] reuse_warm_ecdsa_bootstrap sealed record exhausted for ${e.chainTargetKey}`}return`[SigningEngine][ecdsa] reuse_warm_ecdsa_bootstrap failed`}function QN(e){return Error(ZN(e))}async function $N(e,t){await bd(e.ensureSealedRefreshStartupParity,KN(t));let n=V(du(t));switch(t.kind){case`reuse_warm_ecdsa_bootstrap`:{let r=await XN(GN(e),n,t);return r.ok?{ok:!0,bootstrap:r.bootstrap}:{ok:!1,kind:`reuse_failed`,failure:r}}case`passkey_fresh_ecdsa_bootstrap`:case`passkey_preauthorized_ecdsa_bootstrap`:case`wallet_session_reconnect_ecdsa_bootstrap`:case`email_otp_ecdsa_bootstrap`:return{ok:!0,bootstrap:await qN(e,t)}}throw Error(`[SigningEngine][ecdsa] unsupported warm bootstrap request`)}function eP(e){return typeof e?.clearAllVolatileWarmSessionMaterial==`function`}function tP(e){return typeof e?.clearVolatileWarmSessionMaterial==`function`}async function nP(e){let t=new Set,r=await Promise.all([hs({walletId:e,filter:{authMethod:`passkey`,curve:`ed25519`}}),hs({walletId:e,filter:{authMethod:`email_otp`,curve:`ed25519`}})]);for(let e of r.flat()){let r=n(e.thresholdSessionIds.ed25519);r.ok&&t.add(r.value)}return[...t]}async function rP(e,t){if(t==null&&eP(e.touchConfirm)){await e.touchConfirm.clearAllVolatileWarmSessionMaterial(wh()).catch(()=>void 0);return}let n=t==null?[]:await nP(t);tP(e.touchConfirm)&&await Promise.all(n.map(t=>e.clearVolatileThresholdSessionMaterial(Ch(t)).catch(()=>void 0)))}function iP(e){switch(e.kind){case`rehydrated`:return e;case`device_link_required`:throw Error(`ECDSA login prefill requires local role-local material`);case`corrupt`:throw Error(`ECDSA login prefill role-local material is corrupt (${e.reason}): ${e.message}`);default:{let t=e;throw Error(`Unsupported ECDSA login prefill material state: ${String(t)}`)}}}function aP(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>{let n=iP(await Bd({purpose:`wallet_unlock`,source:Pd({authority:e.manifest.signer.authority,materialActivation:e.manifest.durableMaterial.materialActivation,publicFacts:e.manifest.durableMaterial.roleLocalPublicFacts}),workerCtx:t.workerCtx}));return await Ru({materialHandle:n.liveHandle.materialHandle,material:{kind:`persisted`,materialRef:n.materialRef},...t})},stepClientPresignSession:Xu,abortClientPresignSession:ju,admitClientPresignature:Au,destroyClientPresignature:Mu,reserveClientPresignature:ku,commitClientPresignature:ad,listAvailableClientPresignatures:Vu.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:Hu}}function oP(e){let t={exportArtifactsByLane:e.ecdsaExportArtifacts.exportArtifactsByLane},n=UN({base:e.passkeyMpcSession,secondary:{readWarmSessionStatusOnly:t=>e.getEmailOtpWarmSessionStatus({kind:`ecdsa`,thresholdSessionId:t})}}),r=IN({touchConfirm:n,getEmailOtpWarmSessionStatus:e.getEmailOtpWarmSessionStatus});return{ecdsaSessions:t,statusUiConfirm:n,capabilityReader:BN({resolveActiveEcdsaCapabilityRuntime:e.resolveActiveEcdsaCapabilityRuntime,resolveActiveEcdsaCapabilityRuntimeForChain:e.resolveActiveEcdsaCapabilityRuntimeForChain,touchConfirm:e.passkeyMpcSession,signingSessionSeal:e.signingSessionSeal.mode===`sealed_refresh_v1`?{groupId:Ze}:null,getEmailOtpWarmSessionStatus:e.getEmailOtpWarmSessionStatus,...e.resolveActiveEcdsaWalletSessionAuthorization?{resolveActiveEcdsaWalletSessionAuthorization:e.resolveActiveEcdsaWalletSessionAuthorization}:{},...e.resolveActiveEd25519WalletSessionAuthorization?{resolveActiveEd25519WalletSessionAuthorization:e.resolveActiveEd25519WalletSessionAuthorization}:{}}),statusReader:r}}function sP(e){return{getWarmSession:t=>e.warmSigning.capabilityReader.getWarmSession(V(t)),provisionThresholdEd25519Session:async t=>await mh({credentialStore:e.credentialStore,touchIdPrompt:e.touchIdPrompt,touchConfirm:e.passkeyMpcSession,defaultRelayerUrl:e.seamsWebConfigs.network.relayer?.url||``,getSignerWorkerContext:()=>e.walletSessionActivationDeps.getSignerWorkerContext()},t),bootstrapEcdsaSession:async t=>{let n=await $N({ensureSealedRefreshStartupParity:e.ensureSealedRefreshStartupParity,queueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,activationDeps:e.walletSessionActivationDeps,passkeyMpcSession:e.passkeyMpcSession,persistEcdsaRoleLocalReadyRecord:e.persistEcdsaRoleLocalReadyRecord,capabilityReader:e.warmSigning.capabilityReader},t);if(n.ok)return n.bootstrap;switch(n.kind){case`reuse_failed`:throw QN(n.failure)}throw Error(`[SigningEngine][ecdsa] unsupported warm bootstrap result`)}}}function cP(e){return{statusReader:e.warmSigning.statusReader,persistThresholdEcdsaBootstrapForWalletTarget:async t=>await _h({bootstrapStore:e.bootstrapStore,walletId:t.walletId,chainTarget:t.chainTarget,bootstrap:t.bootstrap,signerAuth:t.signerAuth}),hydrateSigningSession:async t=>await Ll(e.passkeyMpcSession,t),clearVolatileWarmSigningMaterial:async t=>await rP({touchConfirm:e.passkeyMpcSession,clearVolatileThresholdSessionMaterial:async t=>await e.passkeyMpcSession.clearVolatileWarmSessionMaterial(t)},t),getWalletSessionStatus:t=>e.signingSessionCoordinator.getAvailableStatus(t),routerAbEcdsaDerivationPresignaturePoolPolicy:e.seamsWebConfigs.signing.routerAbEcdsaDerivation.presignaturePool,getSignerWorkerContext:()=>e.walletSessionActivationDeps.getSignerWorkerContext(),resolveClientSigningMaterialSource:aP}}function lP(e){return{laneSelection:e.laneSelection,sessionLifecycle:e.sessionLifecycle,ecdsa:{...e.ecdsa,theme:e.getTheme()},ed25519Yao:{...e.ed25519Yao,theme:e.getTheme()}}}async function uP(e,t){let{exportKeypairWithUI:n}=await import(`./exportKeypairOperation-B9_ulzNz.js`);return await n(lP(e),t)}async function dP(e,t){let{resolveExactKeyExportLane:n}=await import(`./exportKeypairOperation-B9_ulzNz.js`);return await n(lP(e),t)}function fP(e){return e.session.chainTargets.length===e.walletKeys.length?e.walletKeys.every((t,n)=>{let r=e.session.chainTargets[n];return r!==void 0&&H(r)===H(t.chainTarget)}):!1}function pP(e){let t=e.walletKey;return{keyScope:t.keyScope,chainTarget:t.chainTarget,walletId:t.walletId,evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,keyHandle:t.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,thresholdOwnerAddress:t.thresholdOwnerAddress,relayerKeyId:t.relayerKeyId,relayerVerifyingShareB64u:t.relayerVerifyingShareB64u,participantIds:t.participantIds,publicCapability:t.publicCapability,roleLocalMaterialRef:e.materialRef,ecdsaRoleLocalPublicFacts:e.publicFacts}}async function mP(e){if(!fP({session:e.session,walletKeys:e.walletKeys}))throw Error(`[SigningEngine] strict ECDSA registration requires one family activation projected to every wallet target`);let t=V(e.walletId);if(e.session.authority.walletId!==t)throw Error(`[SigningEngine] strict ECDSA registration authority does not match the target wallet`);let n=e.session.roleLocalMaterial,r=Li({kind:`ecdsa_role_local_persisted_material_ref_v1`,durableMaterialRef:n.durableMaterialRef,bindingDigest:n.bindingDigest,materialActivation:e.session.materialActivation}),[i,...a]=e.walletKeys.map(n=>pP({walletKey:n,publicFacts:ji({walletId:t,chainTarget:n.chainTarget,keyHandle:n.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,applicationBindingDigestB64u:e.session.bootstrap.applicationBindingDigestB64u,clientParticipantId:1,relayerParticipantId:2,participantIds:n.participantIds,contextBinding32B64u:e.session.clientPublicFacts.contextBinding32B64u,derivationClientSharePublicKey33B64u:e.session.clientPublicFacts.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:e.session.clientPublicFacts.relayerPublicKey33B64u,groupPublicKey33B64u:e.session.clientPublicFacts.groupPublicKey33B64u,ethereumAddress:e.session.clientPublicFacts.ethereumAddress,publicCapability:e.session.publicCapability}),materialRef:r}));if(!i)throw Error(`[SigningEngine] strict ECDSA registration did not persist any wallet keys`);return[i,...a]}async function hP(e,t){return await e.touchConfirm.requestRegistrationCredentialConfirmation({walletId:t.walletId,nearAccountId:t.nearAccountId,signerSlot:t.signerSlot,confirmerText:t.confirmerText,confirmationConfigOverride:t.confirmationConfigOverride,challengeB64u:t.challengeB64u,registrationOptions:t.registrationOptions})}async function gP(e,t){return await e.touchIdPrompt.getAuthenticationCredentialsSerializedForChallengeB64u({subjectId:t.subjectId,challengeB64u:t.challengeB64u,allowCredentials:t.allowCredentials,includeSecondPrfOutput:t.includeSecondPrfOutput??!1})}function _P(e){e instanceof Uint8Array&&e.fill(0)}function vP(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} returned invalid JSON`);return e}function yP(e,t){return N(e,t)}function bP(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function xP(e){if(!e||typeof e.requestWorkerOperation!=`function`)throw Error(`Email OTP secret-bearing operations require the dedicated emailOtp worker`);return e}function SP(e,t){if(!(e instanceof Uint8Array))throw Error(`${t} must be a Uint8Array`);if(e.length!==32)throw Error(`${t} must contain 32 bytes`);return Uint8Array.from(e)}function CP(e){return e.routeFamily===`registration`?Ss({routeFamily:`registration`,operation:Vt}):Ss({routeFamily:`login`,operation:Ht})}function wP(e){let t=vP(e,`Email OTP registration ECDSA handle`),n=yP(t.kind,`emailOtpSessionHandle.handle.kind`);if(n!==`email_otp_worker_session_handle_v1`)throw Error(`Unsupported Email OTP worker handle kind: ${n}`);let r=yP(t.action,`emailOtpSessionHandle.handle.action`);if(r!==`wallet_registration_ecdsa_prepare`)throw Error(`Unsupported Email OTP worker handle action: ${r}`);if(yP(t.operation,`emailOtpSessionHandle.handle.operation`)!==`registration`)throw Error(`Email OTP registration ECDSA handle requires registration operation`);if(yP(t.keyScope,`emailOtpSessionHandle.handle.keyScope`)!==`evm-family`)throw Error(`Email OTP registration ECDSA handle requires evm-family keyScope`);return{kind:`email_otp_worker_session_handle_v1`,sessionId:yP(t.sessionId,`emailOtpSessionHandle.handle.sessionId`),walletId:yP(t.walletId,`emailOtpSessionHandle.handle.walletId`),evmFamilySigningKeySlotId:yP(t.evmFamilySigningKeySlotId,`emailOtpSessionHandle.handle.evmFamilySigningKeySlotId`),authSubjectId:yP(t.authSubjectId,`emailOtpSessionHandle.handle.authSubjectId`),action:`wallet_registration_ecdsa_prepare`,operation:`registration`,keyScope:`evm-family`,chainTarget:TP(t.chainTarget)}}function TP(e){let t=e&&typeof e==`object`?e:null;if(!t)throw Error(`Email OTP registration ECDSA handle requires chainTarget`);return xn(t)}function EP(e){let t=vP(e,`Email OTP registration ECDSA handle result`),n=yP(t.kind,`emailOtpSessionHandle.kind`);switch(n){case`available`:if(!Array.isArray(t.handles)||t.handles.length===0)throw Error(`Email OTP registration ECDSA handle result requires handles`);{let e=[];for(let n of t.handles)e.push(wP(n));let n=e[0];if(!n)throw Error(`Email OTP registration ECDSA handle result requires handles`);return{kind:`available`,handles:[n,...e.slice(1)]}}case`not_requested`:if(`handles`in t)throw Error(`Email OTP unrequested registration ECDSA handle result forbids handles`);return{kind:`not_requested`};default:throw Error(`Unsupported Email OTP registration ECDSA handle result kind: ${n}`)}}async function DP(e){let t=xP(e.workerCtx),n=null;try{n=e.clientSecret32?SP(e.clientSecret32,`clientSecret32`):null;let r=await t.requestWorkerOperation({kind:`emailOtp`,request:{type:`prepareEmailOtpRegistrationEnrollmentMaterial`,payload:{relayUrl:yP(e.relayUrl,`relayUrl`),walletId:yP(e.walletId,`walletId`),userId:yP(e.userId,`userId`),groupId:yP(e.groupId,`groupId`),routePlan:CP({routeFamily:`registration`}),otpChannel:e.otpChannel||`email_otp`,ecdsaSessionHandle:e.ecdsaSessionHandle,...n?{clientSecret32:bP(n)}:{}}}});return{...r,emailOtpSessionHandle:EP(r.emailOtpSessionHandle),emailOtpEnrollment:r.emailOtpEnrollment}}finally{_P(n)}}function OP(e,t){return rc({freshRouteFamily:t,operation:e.operation})}function kP(e){return{walletSession:e.walletSession,authoritySelector:e.authoritySelector,chainTarget:e.chainTarget,otpCode:e.otpCode,routePlan:OP(e,`login`),ecdsaBootstrapAuthorization:e.ecdsaBootstrapAuthorization,emailHashHex:e.emailHashHex,providerIdentity:e.providerIdentity,ed25519YaoRecovery:e.ed25519YaoRecovery??{kind:`not_requested`},...e.emailOtpAuthPolicy?{emailOtpAuthPolicy:e.emailOtpAuthPolicy}:{},...e.emailOtpAuthReason?{emailOtpAuthReason:e.emailOtpAuthReason}:{},...e.relayUrl?{relayUrl:e.relayUrl}:{},...e.challengeId?{challengeId:e.challengeId}:{},...e.operation?{operation:e.operation}:{},...e.groupId?{groupId:e.groupId}:{},...e.keyHandle?{keyHandle:e.keyHandle}:{},...e.participantIds?{participantIds:e.participantIds}:{},...e.publicationChainTargets?{publicationChainTargets:e.publicationChainTargets}:{},...typeof e.ttlMs==`number`?{ttlMs:e.ttlMs}:{},...typeof e.remainingUses==`number`?{remainingUses:e.remainingUses}:{},...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},...e.onProgress?{onProgress:e.onProgress}:{}}}async function AP(e,t){return await e.emailOtpSessions.loginWithEcdsaCapabilityInternal(kP(t))}async function jP(e,t){let n=V(t.walletId),r=String(t.relayUrl||e.relayerUrl||``).trim();if(!r)throw Error(`Missing relayer url (configs.network.relayer.url)`);let i=String(t.groupId||e.groupId||``).trim();if(!i)throw Error(`Missing shamir prime for Email OTP runtime`);let a=String(t.userId).trim();if(!a)throw Error(`Email OTP registration enrollment material requires userId`);return await DP({relayUrl:r,walletId:String(n),userId:a,groupId:i,workerCtx:e.getSignerWorkerContext(),otpChannel:t.otpChannel,ecdsaSessionHandle:{kind:`not_requested`},...t.clientSecret32?{clientSecret32:t.clientSecret32}:{}})}function MP(e){return e.binding.kind===`ed25519_yao_client_root_v1`}function NP(e){if(!MP(e))throw Error(`[SigningEngine][ed25519-export] export envelope has the wrong secret kind`);return e}function PP(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} fields are invalid`)}function FP(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} is invalid`);return e}function IP(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||Number(e[0])<1||Number(e[1])<1||e[0]===e[1])throw Error(`Ed25519 export bootstrap participantIds are invalid`);return[Number(e[0]),Number(e[1])]}async function LP(e){let t=e.authorization.operationCredential,r=e.authorization.status,i=e.authorization.record.authorizationId,a=e.subject.signer,o=e.source;if(e.authorization.record.walletId!==a.account.wallet.walletId||e.authorization.record.authMethodId!==e.authorization.selectedAuthMethod.walletAuthMethodId||e.authorization.factorAuthority.factor.providerUserId!==e.subject.auth.providerSubjectId||!o.signingWorkerId||o.participantIds.length!==2||!o.registeredPublicKeyB64u)throw Error(`[SigningEngine][ed25519-export] sealed custody identity mismatch`);let s=Lr({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:String(a.account.wallet.walletId),nearAccountId:String(a.account.nearAccountId),nearEd25519SigningKeyId:String(a.nearEd25519SigningKeyId),signerSlot:a.signerSlot,thresholdSessionId:e.subject.thresholdSessionId,signingWorkerId:o.signingWorkerId,participantIds:o.participantIds});if(!s.ok)throw Error(s.message);let c=await e.fetch(`${new URL(e.relayerUrl).origin}${Mr}`,{method:`POST`,headers:{Authorization:`Bearer ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(s.value)}),l=await c.json().catch(()=>null);if(!c.ok){let e=l&&typeof l==`object`?l:null;throw Error(`[SigningEngine][ed25519-export] capability bootstrap failed (HTTP ${c.status}): ${String(e?.message||`invalid response`)}`)}let u=E(l,`Ed25519 export bootstrap`);if(PP(u,[`kind`,`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`signerSlot`,`thresholdSessionId`,`walletSessionId`,`quotaId`,`signingWorkerId`,`thresholdExpiresAtMs`,`participantIds`,`runtimePolicyScope`,`routerAbNormalSigning`,`capability`],`Ed25519 export bootstrap`),u.kind!==`router_ab_ed25519_yao_v2_session_bootstrap_v1`)throw Error(`Ed25519 export bootstrap kind is invalid`);let d=D(u.walletId,`bootstrap.walletId`),f=D(u.nearAccountId,`bootstrap.nearAccountId`),p=D(u.nearEd25519SigningKeyId,`bootstrap.nearEd25519SigningKeyId`),m=n(u.thresholdSessionId),h=Tt(u.walletSessionId),_=Ct(u.quotaId),v=e.authorization.factorAuthority,y=Fe(u.runtimePolicyScope),b=Pe(y),x=Qe(u.routerAbNormalSigning),S={kind:`router_ab_ed25519_yao_active_capability_v1`,...ao(u.capability)},C=IP(u.participantIds),w=P(Uint8Array.from(S.registeredPublicKey));if(!m.ok||!h.ok||!_.ok||!b||!x||d!==String(a.account.wallet.walletId)||f!==String(a.account.nearAccountId)||p!==String(a.nearEd25519SigningKeyId)||m.value!==S.lifecycle.thresholdSessionId||h.value!==t.walletSessionId||_.value!==e.authorization.record.quotaId||FP(u.signerSlot,`bootstrap.signerSlot`)!==a.signerSlot||D(u.signingWorkerId,`bootstrap.signingWorkerId`)!==o.signingWorkerId||C[0]!==o.participantIds[0]||C[1]!==o.participantIds[1]||v.factor.providerUserId!==e.subject.auth.providerSubjectId||w!==o.registeredPublicKeyB64u||!g(S.materialActivation,e.expectedMaterialActivation))throw Error(`[SigningEngine][ed25519-export] capability bootstrap identity mismatch`);return{emailHashHex:v.verifier.emailHashHex,bootstrap:{kind:`router_ab_ed25519_yao_email_otp_recovery_v1`,session:{walletId:a.account.wallet.walletId,nearAccountId:f,nearEd25519SigningKeyId:p,authorityScope:{kind:`email_otp`,provider:v.factor.provider,providerUserId:v.factor.providerUserId},thresholdSessionId:m.value,authorizationId:i,walletSessionId:h.value,quotaId:_.value,expiresAtMs:Math.min(FP(u.thresholdExpiresAtMs,`bootstrap.thresholdExpiresAtMs`),r.expiresAtMs),participantIds:C,remainingUses:r.remainingUses,signingRootId:b.signingRootId,signingRootVersion:y.signingRootVersion,runtimePolicyScope:y,routerAbNormalSigning:x},capability:S}}}async function RP(e){let t=HP({subject:e.subject,expectedMaterialActivation:e.expectedMaterialActivation,result:e.authorization});return(await LP({subject:e.subject,authorization:t,source:e.source,expectedMaterialActivation:e.expectedMaterialActivation,relayerUrl:e.relayerUrl,fetch:e.fetch})).bootstrap}async function zP(e){let t=e.authorization.operationCredential,r=e.subject.signer;if(e.authorization.record.walletId!==r.account.wallet.walletId||e.authorization.record.authMethodId!==e.authorization.selectedAuthMethod.walletAuthMethodId||e.authorization.factorAuthority.factor.providerUserId!==e.subject.auth.providerSubjectId)throw Error(`[SigningEngine][ed25519-export] linked Wallet Session is unavailable`);let i=Lr({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:String(r.account.wallet.walletId),nearAccountId:String(r.account.nearAccountId),nearEd25519SigningKeyId:String(r.nearEd25519SigningKeyId),signerSlot:r.signerSlot,thresholdSessionId:e.subject.thresholdSessionId,signingWorkerId:e.source.signingWorkerId,participantIds:e.source.participantIds});if(!i.ok)throw Error(i.message);let a=await e.fetch(`${new URL(e.relayerUrl).origin}${Mr}`,{method:`POST`,headers:{Authorization:`Bearer ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(i.value)}),o=await a.json().catch(()=>null);if(!a.ok){let e=o&&typeof o==`object`?o:null;throw Error(`[SigningEngine][ed25519-export] linked capability bootstrap failed (HTTP ${a.status}): ${String(e?.message||`invalid response`)}`)}let s=E(o,`linked Ed25519 export bootstrap`);if(PP(s,[`kind`,`walletId`,`nearAccountId`,`nearEd25519SigningKeyId`,`signerSlot`,`thresholdSessionId`,`walletSessionId`,`quotaId`,`signingWorkerId`,`thresholdExpiresAtMs`,`participantIds`,`runtimePolicyScope`,`routerAbNormalSigning`,`capability`],`linked Ed25519 export bootstrap`),s.kind!==`router_ab_ed25519_yao_v2_session_bootstrap_v1`)throw Error(`linked Ed25519 export bootstrap kind is invalid`);let c=n(s.thresholdSessionId),l=Tt(s.walletSessionId),u=Ct(s.quotaId),d=Fe(s.runtimePolicyScope),f=Qe(s.routerAbNormalSigning),p={kind:`router_ab_ed25519_yao_active_capability_v1`,...ao(s.capability)},m=IP(s.participantIds),h=P(Uint8Array.from(p.registeredPublicKey));if(!c.ok||!l.ok||!u.ok||!d||!f||D(s.walletId,`bootstrap.walletId`)!==String(r.account.wallet.walletId)||D(s.nearAccountId,`bootstrap.nearAccountId`)!==String(r.account.nearAccountId)||D(s.nearEd25519SigningKeyId,`bootstrap.nearEd25519SigningKeyId`)!==String(r.nearEd25519SigningKeyId)||FP(s.signerSlot,`bootstrap.signerSlot`)!==r.signerSlot||c.value!==p.lifecycle.thresholdSessionId||l.value!==t.walletSessionId||u.value!==e.authorization.record.quotaId||D(s.signingWorkerId,`bootstrap.signingWorkerId`)!==e.source.signingWorkerId||m[0]!==e.source.participantIds[0]||m[1]!==e.source.participantIds[1]||h!==e.source.registeredPublicKeyB64u||!g(p.materialActivation,e.expectedMaterialActivation))throw Error(`[SigningEngine][ed25519-export] linked capability identity mismatch`);return p}function BP(e,t){let n=0;for(let r of e)switch(r.kind){case`export_keys`:r.keyFamily===`ed25519`&&g(r.materialActivation,t)&&(n+=1);break;case`sign`:case`link_devices`:case`revoke_devices`:break;default:break}return n}function VP(e){let{authorization:t}=e,n=t.selectedAuthority,r=t.selectedAuthMethod,i=t.factorAuthority,a=t.record,o=t.operationCredential,s=t.status,c=s.status===`active`&&s.quotaLifecycle===`active`&&s.remainingUses>0||s.status===`exhausted`&&s.quotaLifecycle===`exhausted`&&s.remainingUses===0;if(n.state!==`active`||n.walletId!==e.subject.signer.account.wallet.walletId||r.status!==`active`||r.walletId!==e.subject.signer.account.wallet.walletId||r.walletAuthorityId!==n.authorityId||i.walletId!==e.subject.signer.account.wallet.walletId||i.bindingId!==r.walletAuthMethodId||i.verifier.emailHashHex!==r.emailHashHex||i.factor.providerUserId!==e.subject.auth.providerSubjectId||a.walletId!==e.subject.signer.account.wallet.walletId||a.authorityId!==n.authorityId||a.authMethodId!==r.walletAuthMethodId||String(a.authorityDigestB64u)!==String(n.authorityDigestB64u)||a.authorityRevocationEpoch!==n.revocationEpoch||!c||s.walletSessionId!==o.walletSessionId||s.quotaId!==a.quotaId||!Ue(s.authorization,a)||o.walletSessionId.trim().length===0||o.token.trim().length===0||s.expiresAtMs<=Date.now()||BP(a.capabilitySubjects,e.expectedMaterialActivation)!==1)throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization identity mismatch`)}function HP(e){switch(e.result.kind){case`found`:return VP({subject:e.subject,expectedMaterialActivation:e.expectedMaterialActivation,authorization:e.result.authorization}),e.result.authorization;case`missing`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization is missing`);case`upgrade_required`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization requires an upgrade`);case`corrupt`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization is corrupt`);case`persistence_unavailable`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization persistence is unavailable`);case`exhausted`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization is exhausted`);case`expired`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization is expired`);case`superseded`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authorization is superseded`);case`authority_unavailable`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP authority is unavailable`);case`method_unavailable`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP method is unavailable`);case`capability_unavailable`:throw Error(`[SigningEngine][ed25519-export] exact Email OTP export capability is unavailable`);default:return e.result}}function UP(e){if(e.material.activeClient.status().kind!==`active`)throw Error(`[SigningEngine][ed25519-export] wallet custody client is inactive`);let t=e.material.activeClient.metadata(),r=e.subject.signer;if(!g(t.materialActivation,e.expectedMaterialActivation)||e.material.facts.signer.account.wallet.walletId!==r.account.wallet.walletId||String(e.material.facts.signer.account.nearAccountId)!==String(r.account.nearAccountId)||e.material.facts.signer.nearEd25519SigningKeyId!==r.nearEd25519SigningKeyId||e.material.facts.signer.signerSlot!==r.signerSlot||t.applicationBinding.wallet_id!==r.account.wallet.walletId||t.applicationBinding.near_ed25519_signing_key_id!==r.nearEd25519SigningKeyId||t.applicationBinding.key_creation_signer_slot!==r.signerSlot)throw Error(`[SigningEngine][ed25519-export] wallet custody client changed the exact lane`);let i=n(t.scope.threshold_session_id);if(!i.ok)throw Error(`[SigningEngine][ed25519-export] threshold session id is invalid: ${i.error.message}`);return{kind:`router_ab_ed25519_yao_active_capability_v1`,materialActivation:t.materialActivation,activeCapabilityBinding:t.activeCapabilityBinding,registeredPublicKey:[...t.registeredPublicKey],nearAccountId:String(r.account.nearAccountId),applicationBinding:t.applicationBinding,runtimePolicyScope:e.material.facts.runtimePolicyScope,participantIds:t.participantIds,lifecycle:{lifecycleId:t.scope.lifecycle_id,rootShareEpoch:t.scope.root_share_epoch,accountId:t.scope.account_id,thresholdSessionId:i.value,signerSetId:t.scope.signer_set_id,signingWorkerId:t.scope.signing_worker_id},stateEpoch:Number(t.stateEpoch),registrationContinuity:{kind:`recovery`,activationTranscript:[...t.transcript]}}}async function WP(e){let t=e.subject.signer.account.wallet.walletId,n=HP({subject:e.subject,expectedMaterialActivation:e.expectedMaterialActivation,result:await e.readExactWalletSessionAuthorization({subject:e.subject,expectedMaterialActivation:e.expectedMaterialActivation})}),r=e.resolveActiveCapability(t,e.subject.signer.account.nearAccountId,e.expectedMaterialActivation),i=r?UP({subject:e.subject,expectedMaterialActivation:e.expectedMaterialActivation,material:r}):null,a=e.resolveEd25519YaoClientRootEnvelope?await e.resolveEd25519YaoClientRootEnvelope({subject:e.subject,capability:i,selectedMaterialActivation:e.expectedMaterialActivation}):null,o=a&&`envelope`in a?a.envelope:a,s=i;if(a&&`envelope`in a&&(s=await zP({subject:e.subject,authorization:n,source:a.source,expectedMaterialActivation:a.source.materialActivation,relayerUrl:e.relayerUrl,fetch:e.fetch})),o){if(!s)throw Error(`[SigningEngine][ed25519-export] Ed25519 export-root capability is unavailable`);return{kind:`wallet_custody_ed25519_export_context_v1`,lane:e.subject,authorization:n,material:{kind:`sealed_export_root`,materialActivation:s.materialActivation,capability:s,exportRootEnvelope:NP(o)}}}if(r){if(!i)throw Error(`[SigningEngine][ed25519-export] active Email OTP capability is unavailable`);return{kind:`wallet_custody_ed25519_export_context_v1`,lane:e.subject,authorization:n,material:{kind:`active_capability`,materialActivation:e.expectedMaterialActivation,capability:i}}}let c=await e.loadWalletCustodyMaterial();if(c.kind!==`found`)throw Error(`[SigningEngine][ed25519-export] sealed wallet custody material is unavailable`);let l=await LP({subject:e.subject,authorization:n,source:c.material.binding,expectedMaterialActivation:e.expectedMaterialActivation,relayerUrl:e.relayerUrl,fetch:e.fetch});return{kind:`wallet_custody_ed25519_export_context_v1`,lane:e.subject,authorization:n,material:{kind:`sealed_custody`,materialActivation:e.expectedMaterialActivation,capability:l.bootstrap.capability,walletCustodyEd25519Material:c.material,bootstrap:l.bootstrap,activateRecoveredCapability:t=>{if(t.operationCredential.walletSessionId!==n.operationCredential.walletSessionId||t.operationCredential.token!==n.operationCredential.token)throw Error(`[SigningEngine][ed25519-export] recovered capability credential does not match authorization`);return e.activateRecoveredCapability({activation:{...t.activation,bootstrap:l.bootstrap,emailHashHex:l.emailHashHex},operationCredential:t.operationCredential})}}}}async function GP(e){return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`sealEmailOtpWarmSessionMaterial`,timeoutMs:3e4,payload:{target:e.target,transport:{...e.transport,authorizationThresholdSessionId:e.authorizationThresholdSessionId}}}})}async function KP(e){return await e.worker.requestWorkerOperation({kind:`emailOtp`,request:{type:`getEmailOtpWarmSessionStatus`,timeoutMs:5e3,payload:{target:e.target}}})}async function qP(e){return await e.worker.requestWorkerOperation({kind:`emailOtp`,request:{type:`consumeEmailOtpWarmSessionUses`,timeoutMs:5e3,payload:{target:e.target,...typeof e.uses==`number`?{uses:e.uses}:{}}}})}async function JP(e){return await e.worker.requestWorkerOperation({kind:`emailOtp`,request:{type:`clearEmailOtpWarmSessionMaterial`,timeoutMs:5e3,payload:{target:e.target}}})}async function YP(e){return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`rehydrateEmailOtpEcdsaWarmSessionMaterial`,timeoutMs:6e4,payload:{target:e.target,sealedSecretB64u:e.sealedSecretB64u,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs,transport:{...e.transport,authorizationThresholdSessionId:e.authorizationThresholdSessionId},restore:e.restore}}})}async function XP(e){return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`rehydrateEmailOtpEd25519YaoOperationMaterial`,timeoutMs:12e4,payload:e.payload}})}function ZP(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function QP(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||e[0]<1||e[1]<1||e[0]===e[1])throw Error(`warm recovery participantIds must contain two distinct positive integers`);return[Number(e[0]),Number(e[1])]}const $P=[`capability`,`kind`,`nearAccountId`,`nearEd25519SigningKeyId`,`participantIds`,`quotaId`,`routerAbNormalSigning`,`runtimePolicyScope`,`signerSlot`,`signingWorkerId`,`thresholdExpiresAtMs`,`thresholdSessionId`,`walletId`,`walletSessionId`];function eF(e,t){let n=[...t].sort(),r=Object.keys(e).sort();if(r.length!==n.length)throw Error(`warm recovery bootstrap response fields are invalid`);for(let e=0;e<r.length;e+=1)if(r[e]!==n[e])throw Error(`warm recovery bootstrap response fields are invalid`)}function tF(e,t){if(e.authMethod!==`passkey`)return!1;let n=e.ed25519Restore;return n.credentialIdB64u?e.walletId===t.walletId&&n.nearAccountId===t.nearAccountId&&n.nearEd25519SigningKeyId===t.nearEd25519SigningKeyId&&n.signerSlot===t.signerSlot&&e.thresholdSessionIds.ed25519===t.thresholdSessionId:!1}async function nF(e,t){let n=await t.readExactEd25519SealedSession(Wd({authMethod:`passkey`,materialActivation:e.materialActivation}));return n&&(n.curve!==`ed25519`||!tF(n,e)||!g(n.ed25519Restore.materialActivation,e.materialActivation))||!n||n.expiresAtMs<=t.nowMs()||n.remainingUses<1?{kind:`unavailable`}:{kind:`ready`,record:n}}async function rF(e){let t;try{t=await e.runtime.resolveSelectedWalletAuthority(String(e.walletId))}catch{return null}if(t.kind!==`resolved`)return null;let{selection:n,authMethod:r,authority:i}=t;if(n.lockState!==`unlocked`||n.walletId!==e.walletId||e.expectedAuthorityRef.walletId!==e.walletId||n.walletAuthMethodId!==e.expectedAuthorityRef.walletAuthMethodId||r.kind!==`passkey`||r.status!==`active`||r.walletId!==e.walletId||r.walletAuthMethodId!==e.expectedAuthorityRef.walletAuthMethodId||r.walletAuthorityId!==i.authorityId||String(r.rpId)!==e.rpId||String(r.credentialIdB64u)!==e.credentialIdB64u||i.state!==`active`||i.walletId!==e.walletId)return null;try{return{authorizationRead:await e.runtime.readExactWalletSessionAuthorization({walletId:e.walletId,authorityId:i.authorityId,authMethodId:r.walletAuthMethodId}),authorityId:i.authorityId,authorityDigestB64u:i.authorityDigestB64u,authorityRevocationEpoch:i.revocationEpoch}}catch{return null}}async function iF(e){if(e.authorizationRead.kind!==`found`)return null;let t=e.authorizationRead,n=t.record,r=n.capabilitySubjects.filter(t=>t.kind===`sign`&&t.keyFamily===`ed25519`&&g(t.materialActivation,e.record.ed25519Restore.materialActivation));return n.walletId!==e.expectedAuthorityRef.walletId||n.walletId!==e.record.walletId||n.authorityId!==e.expectedAuthorityId||n.authMethodId!==e.expectedAuthorityRef.walletAuthMethodId||String(n.authorityDigestB64u)!==String(e.expectedAuthorityDigestB64u)||n.authorityRevocationEpoch!==e.expectedAuthorityRevocationEpoch||n.expiresAtMs<=e.nowMs||t.operationCredential.walletSessionId.trim().length===0||t.operationCredential.token.trim().length===0||r.length!==1?null:t}function aF(e,t){let n=e.ed25519Restore,r=Lr({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:e.walletId,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot,thresholdSessionId:t,signingWorkerId:n.routerAbNormalSigning.signingWorkerId,participantIds:n.participantIds});if(!r.ok)throw Error(r.message);return r.value}async function oF(e){let t=e.authorization.operationCredential.token;if(e.authorization.record.walletId!==e.request.walletId||!e.authorization.operationCredential.walletSessionId||!t.trim())throw Error(`[SigningEngine][near] active Wallet Session authorization does not match sealed material`);let n=await e.fetch(`${new URL(e.relayerUrl).origin}${Mr}`,{method:`POST`,headers:{Authorization:`Bearer ${t}`,"Content-Type":`application/json`},body:JSON.stringify(e.request)}),r=await sF(n),i=k(r)?r:null;if(!n.ok){let e=i?String(i.code||``).trim():``;if(n.status===401&&e===`wallet_session_expired`)return{kind:`unavailable`,reason:`wallet_session_expired`};let t=i?String(i.message||``).trim():``;throw Error(`[SigningEngine][near] Ed25519 warm recovery bootstrap failed (HTTP ${n.status}${e?`, ${e}`:``}): ${t||`invalid response`}`)}if(!i)throw Error(`Ed25519 warm recovery bootstrap returned invalid JSON`);return{kind:`ready`,descriptor:await cF({record:e.record,authorization:e.authorization,expectedAuthorityRef:e.expectedAuthorityRef,expectedThresholdSessionId:e.expectedThresholdSessionId,response:i})}}async function sF(e){try{return await e.json()}catch{return null}}async function cF(e){let t=e.record,n=e.response;if(eF(n,$P),n.kind!==`router_ab_ed25519_yao_v2_session_bootstrap_v1`)throw Error(`warm recovery bootstrap response kind is invalid`);let r=t.ed25519Restore,i=N(n.walletId,`response.walletId`),a=N(n.nearAccountId,`response.nearAccountId`),o=N(n.nearEd25519SigningKeyId,`response.nearEd25519SigningKeyId`),s=ZP(n.signerSlot,`response.signerSlot`),c=N(n.thresholdSessionId,`response.thresholdSessionId`),l=N(n.signingWorkerId,`response.signingWorkerId`),u=ZP(n.thresholdExpiresAtMs,`response.thresholdExpiresAtMs`),d=QP(n.participantIds),f=Fe(E(n.runtimePolicyScope,`response.runtimePolicyScope`)),p=Fe(E(r.runtimePolicyScope,`ed25519Restore.runtimePolicyScope`)),m=Qe(n.routerAbNormalSigning),h=Tt(n.walletSessionId),g=Ct(n.quotaId),_=ao(n.capability),v=e.authorization.operationCredential.token;if(!h.ok||!g.ok||e.expectedAuthorityRef.walletId!==t.walletId||String(h.value)!==String(e.authorization.operationCredential.walletSessionId)||String(g.value)!==String(e.authorization.record.quotaId)||!m||i!==t.walletId||a!==r.nearAccountId||o!==r.nearEd25519SigningKeyId||s!==r.signerSlot||c!==String(e.expectedThresholdSessionId)||!v||l!==r.relayerKeyId||l!==r.routerAbNormalSigning.signingWorkerId||m.signingWorkerId!==l||t.expiresAtMs>u||d[0]!==r.participantIds[0]||d[1]!==r.participantIds[1]||!Ie(f,p))throw Error(`warm recovery bootstrap does not match the exact sealed Ed25519 lane`);if(!Pe(f))throw Error(`warm recovery bootstrap signing-root scope is invalid`);if(!v)throw Error(`[SigningEngine][near] active Wallet Session authorization is unavailable`);let y={authority:e.expectedAuthorityRef,walletId:ki(i),nearAccountId:B(a),nearEd25519SigningKeyId:o,signerSlot:s,operationalPublicKey:`ed25519:${tn(Uint8Array.from(_.registeredPublicKey))}`,relayerKeyId:l,credentialIdB64u:N(r.credentialIdB64u,`ed25519Restore.credentialIdB64u`),session:{sessionKind:`opaque`,home:e.authorization.operationCredential.home,walletSessionToken:v,thresholdSessionId:c,walletSessionId:h.value,authorizationId:e.authorization.record.authorizationId,quotaId:g.value,expiresAtMs:u,remainingUses:t.remainingUses,runtimePolicyScope:f,participantIds:d,routerAbNormalSigning:m},capability:_};return $o(y,r.materialActivation),y}async function lF(e,t){let n=await nF(e.subject,t);if(n.kind===`unavailable`)return{kind:`capability_recovery_required`};let r=_(n.record.walletId);if(!r.ok)throw Error(`[SigningEngine][near] sealed Ed25519 wallet identity is invalid`);let i=N(n.record.ed25519Restore.credentialIdB64u,`ed25519Restore.credentialIdB64u`),a;try{a=await t.resolveExactPasskeyWalletAuthAuthorityRef({walletId:r.value,rpId:n.record.ed25519Restore.rpId,credentialIdB64u:i})}catch{return{kind:`capability_recovery_required`}}if(!a)return{kind:`capability_recovery_required`};let o=await rF({walletId:r.value,rpId:n.record.ed25519Restore.rpId,credentialIdB64u:i,expectedAuthorityRef:a,runtime:t});if(!o)return{kind:`capability_recovery_required`};let s=await iF({record:n.record,authorizationRead:o.authorizationRead,expectedAuthorityRef:a,expectedAuthorityId:o.authorityId,expectedAuthorityDigestB64u:o.authorityDigestB64u,expectedAuthorityRevocationEpoch:o.authorityRevocationEpoch,nowMs:t.nowMs()});if(!s)return{kind:`capability_recovery_required`};let c=await oF({request:aF(n.record,e.subject.thresholdSessionId),authorization:s,record:n.record,expectedAuthorityRef:a,expectedThresholdSessionId:e.subject.thresholdSessionId,relayerUrl:e.relayerUrl,fetch:e.fetch});if(c.kind===`unavailable`)return{kind:`capability_recovery_required`};let l=c.descriptor,u=await t.readPasskeyCustodySessionEnvelope({walletId:String(l.walletId),credentialIdB64u:l.credentialIdB64u});return!u||u.binding.kind!==`wallet_custody_seed_v1`?{kind:`capability_recovery_required`}:{kind:`ready`,context:{kind:`passkey_ed25519_yao_export_context_v1`,selectedLaneMaterialActivation:l.capability.materialActivation,material:{authority:l.authority,walletId:l.walletId,nearAccountId:l.nearAccountId,nearEd25519SigningKeyId:l.nearEd25519SigningKeyId,signerSlot:l.signerSlot,operationalPublicKey:l.operationalPublicKey,relayerKeyId:l.relayerKeyId,credentialIdB64u:l.credentialIdB64u,capability:l.capability},authorization:s,relayerUrl:e.relayerUrl,rpId:n.record.ed25519Restore.rpId,walletCustodyEnvelope:u}}}function uF(e){let t=e.capability===`ecdsa`?e.runtime?.sealedRecord.thresholdSessionId:e.runtime?.thresholdSessionId,n=t?String(t).trim():null;return{state:e.state,thresholdSessionId:n||null,authState:e.auth?`present`:`missing`,prfClaimState:e.prfClaim?.state||null,...e.prfClaim?.state===`warm`?{remainingUses:e.prfClaim.remainingUses,expiresAtMs:e.prfClaim.expiresAtMs}:{}}}function dF(e){return{capabilities:{ed25519:uF(e.capabilities.ed25519),ecdsa:{evm:uF(e.capabilities.ecdsa.evm),tempo:uF(e.capabilities.ecdsa.tempo)}}}}function fF(e){if(typeof e.onTransition==`function`)try{let t=e.onTransition(e.event);t&&typeof t.then==`function`&&Promise.resolve(t).catch(t=>{console.warn(`[WarmSessionStore] warm-session transition callback failed`,{type:e.event.type,walletId:e.event.walletId,error:t})})}catch(t){console.warn(`[WarmSessionStore] warm-session transition callback failed`,{type:e.event.type,walletId:e.event.walletId,error:t})}}function pF(e){return String(e||``).trim()||void 0}function mF(e){let t=String(e.persistedSessionIdRaw||``).trim();if(t!==e.expectedThresholdSessionId)throw Error(`[WarmSessionStore] provisioned Ed25519 capability was not persisted for ${e.walletId} (expected thresholdSessionId=${e.expectedThresholdSessionId}, found=${t||`missing`})`)}function hF(e){return e.kind===`exact_ed25519_provisioning`?V(tl(e.laneIdentity,`exact Ed25519 capability provisioning`).walletId):V(e.walletId)}function gF(e){return B(e.kind===`exact_ed25519_provisioning`?tl(e.laneIdentity,`exact Ed25519 capability provisioning`).nearAccountId:e.nearAccountId)}async function _F(e,t){let n=gF(t),r=hF(t);if(!r)throw Error(`[WarmSessionStore] walletId is required to provision Ed25519 capability`);if(typeof e.provisionThresholdEd25519Session!=`function`)throw Error(`[WarmSessionStore] provisionThresholdEd25519Session is required to provision Ed25519 capability`);let i=await e.getWarmSession(r);await t.beforeProvision?.(),t.assertNotCancelled?.();let a=await e.provisionThresholdEd25519Session(t);if(t.assertNotCancelled?.(),!a.ok)return a;let o=pF(a.thresholdSessionId);if(!o)throw Error(`[WarmSessionStore] provisioned Ed25519 capability is missing thresholdSessionId for ${n}`);let s=await e.getWarmSession(r);return mF({walletId:r,expectedThresholdSessionId:o,persistedSessionIdRaw:s.capabilities.ed25519.runtime?.thresholdSessionId}),fF({onTransition:e.onTransition,event:{type:`ed25519_capability_provisioned`,walletId:r,thresholdSessionId:o,before:dF(i),after:dF(s)}}),a}async function vF(e,t){return await _F({getWarmSession:t=>e.getWarmSession(t),provisionThresholdEd25519Session:async t=>await e.provisionThresholdEd25519Session(t)},t)}async function yF(e,t){return await e.bootstrapEcdsaSession(t)}function bF(e){if(!e.authorization)throw Error(`Available Ed25519 lane requires Wallet Session authorization`);return Cl({signer:fl({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:e.auth,walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId,thresholdSessionId:e.thresholdSessionId})}function xF(e){let t=e.signer;return JSON.stringify([String(t.account.wallet.walletId),String(t.account.nearAccountId),String(t.nearEd25519SigningKeyId),t.signerSlot,$t(e.auth),String(e.thresholdSessionId)])}function SF(e){return{kind:`near_ed25519_material_identity`,signer:fl({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:e.auth,thresholdSessionId:Qt.thresholdEd25519Session(e.thresholdSessionId)}}function CF(e){return{kind:`near_ed25519_material_identity`,signer:e.signer,auth:e.auth,thresholdSessionId:e.thresholdSessionId}}function wF(e){switch(e.kind){case`exact_lane`:return{kind:`near_ed25519_material_identity`,signer:e.laneIdentity.signer,auth:e.laneIdentity.auth,thresholdSessionId:e.laneIdentity.thresholdSessionId};case`export_exact_lane`:return CF(e.laneIdentity);case`material_identity`:return e.materialIdentity;default:return DF(e)}}function TF(e,t){if(!Jd(e)||e.curve!==`ed25519`)return!1;let n=wF(t),r=n.signer;if(String(e.walletId)!==String(r.account.wallet.walletId)||String(e.nearAccountId)!==String(r.account.nearAccountId)||e.signerSlot!==r.signerSlot||String(e.thresholdSessionId)!==n.thresholdSessionId)return!1;switch(t.kind){case`exact_lane`:return e.authorizationState===`authorized`&&rl(bF(e),t.laneIdentity);case`export_exact_lane`:return xF(SF(e))===xF(n)&&g(e.materialActivation,t.materialActivation);case`material_identity`:return xF(SF(e))===xF(n);default:return DF(t)}}function EF(e){switch(e.kind){case`exact_lane`:return JSON.stringify([e.kind,el(e.laneIdentity)]);case`export_exact_lane`:return JSON.stringify([e.kind,xF(CF(e.laneIdentity)),tf(e.materialActivation)]);case`material_identity`:return JSON.stringify([e.kind,xF(e.materialIdentity)]);default:return DF(e)}}function DF(e){throw Error(`Unknown Ed25519 capability rehydration subject: ${String(e)}`)}async function OF(e,t){let{runtime:n,session:r,operationCredential:i}=t.capability.authorization,a=i.walletSessionId;try{let o=n.relayerUrl,s=n.clientVerifyingPublicKey33B64u,c=Date.now(),l=Math.min(n.expiresAtMs,r.expiresAtMs);if(l<=c)return{status:`skipped`,reason:`session_expired`,walletSessionId:a};let u=ld(e.routerAbEcdsaDerivationPresignaturePoolPolicy);if(!u.enabled)return{status:`skipped`,reason:`pool_disabled`,walletSessionId:a};let d=n.remainingUses,f={kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.normalSigning.scope,ceremonyExpiresAtMs:l,materialExpiresAtMs:c+bn},p=e.resolveClientSigningMaterialSource({manifest:t.capability.capability.manifest}),m=ud({relayerUrl:o,keyHandle:Wi(n.keyHandle),ecdsaThresholdKeyId:Pi(n.ecdsaThresholdKeyId),clientVerifyingShareB64u:Ri(s),clientSigningMaterial:p,thresholdEcdsaPublicKeyB64u:n.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:n.normalSigning.scope.public_identity.server_public_key33_b64u,credential:{kind:`wallet_session_opaque`,walletSessionToken:i.token,home:i.home,ownershipGeneration:i.ownershipGeneration},authorization:{kind:`reusable_wallet_session`,wallet_session_id:i.walletSessionId},materialActivation:oi(n.materialActivation),routerAbEcdsaDerivationPoolFill:f,workerCtx:e.getSignerWorkerContext(),poolPolicy:u});return m.scheduled?(t.waitForPoolReady&&await sd({ownershipGeneration:i.ownershipGeneration,relayerUrl:o,scope:n.normalSigning.scope,materialActivation:oi(n.materialActivation)}),{status:`scheduled`,reason:`scheduled`,walletSessionId:a,remainingUses:d,schedule:m}):(t.waitForPoolReady&&m.reason===`in_flight_for_pool_key`&&await sd({ownershipGeneration:i.ownershipGeneration,relayerUrl:o,scope:n.normalSigning.scope,materialActivation:oi(n.materialActivation)}),{status:`skipped`,reason:`refill_not_scheduled`,walletSessionId:a,remainingUses:d,schedule:m})}catch(e){return{status:`failed`,reason:`unexpected_error`,walletSessionId:a,error:e instanceof Error?e.message:`unexpected error`}}}async function kF(e,t){let n=await e.statusReader.getEd25519SigningSessionStatus(t),r=t.authorization?ym({owner:fm(t.runtime.walletId),authorization:{walletSessionId:t.authorization.operationCredential.walletSessionId,quotaId:t.authorization.session.quotaId}}):null;return vm(n,r?await _m({getAvailableStatus:e.getWalletSessionStatus},r):null)}async function AF(e,t){return await OF({getSignerWorkerContext:e.getSignerWorkerContext,resolveClientSigningMaterialSource:e.resolveClientSigningMaterialSource,routerAbEcdsaDerivationPresignaturePoolPolicy:e.routerAbEcdsaDerivationPresignaturePoolPolicy},t)}async function jF(e,t){await e.hydrateSigningSession(t)}async function MF(e,t){await e.clearVolatileWarmSigningMaterial(t)}var NF=class{state={kind:`active`};handlePageHideBound;constructor(e,t){this.eventTarget=e,this.clientOwner=t,this.handlePageHideBound=this.handlePageHide.bind(this),this.eventTarget?.addEventListener(`pagehide`,this.handlePageHideBound)}handlePageHide(){this.dispose()}dispose(){this.state.kind!==`disposed`&&(this.state={kind:`disposed`},this.eventTarget?.removeEventListener(`pagehide`,this.handlePageHideBound),this.clientOwner.dispose())}};function PF(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required`);return n}function FF(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<1)throw Error(`${t} must be a positive integer`);return n}function IF(e){let t=n(e);if(!t.ok)throw Error(`thresholdSessionId is invalid`);return t.value}function LF(e){let t=e.bootstrap.session,n=e.bootstrap.capability;if(!t.walletId||!t.walletSessionId||!t.quotaId||!t.thresholdSessionId)throw Error(`Wallet custody Ed25519 bootstrap Wallet Session binding is invalid`);if(e.operationCredential.walletSessionId!==t.walletSessionId)throw Error(`Wallet custody Ed25519 operation credential does not identify the bootstrap session`);let r=String(e.identity.walletId);if(String(t.walletId)!==r||t.nearAccountId!==String(e.identity.nearAccountId)||t.thresholdSessionId!==e.identity.expectedThresholdSessionId||n.applicationBinding.wallet_id!==r||n.applicationBinding.key_creation_signer_slot!==e.identity.signerSlot||n.nearAccountId!==String(e.identity.nearAccountId)||n.lifecycle.accountId!==r||n.lifecycle.thresholdSessionId!==e.identity.expectedThresholdSessionId||n.lifecycle.signerSetId!==String(ua(e.identity.signerSlot))||`ed25519:${tn(Uint8Array.from(n.registeredPublicKey))}`!==e.identity.expectedOperationalPublicKey)throw Error(`Wallet custody Ed25519 bootstrap identity changed`)}async function RF(e){let t=e.bootstrap.session,n=t.authorityScope;if(n.kind!==`email_otp`)throw Error(`Wallet custody Ed25519 bootstrap returned another authority kind`);let r=PF(e.providerSubject,`providerSubject`);if(n.providerUserId!==r)throw Error(`Wallet custody Ed25519 bootstrap provider subject changed`);if(e.authority.walletId!==t.walletId)throw Error(`Wallet custody Ed25519 Wallet Session authority changed wallets`);let i=cs({walletId:String(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,walletSessionId:t.walletSessionId,authorizationId:t.authorizationId,quotaId:t.quotaId,thresholdSessionId:t.thresholdSessionId,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs,runtimePolicyScope:t.runtimePolicyScope,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,routerAbNormalSigning:t.routerAbNormalSigning,walletSessionToken:e.operationCredential.token,home:e.operationCredential.home,nowMs:Date.now()});if(!i.ok)throw Error(`Wallet custody Ed25519 Wallet Session is unusable (${i.reason})`);return uc({walletId:t.walletId,nearAccountId:B(t.nearAccountId),nearEd25519SigningKeyId:Oi(t.nearEd25519SigningKeyId),providerSubjectId:r,signerSlot:FF(e.bootstrap.capability.applicationBinding.key_creation_signer_slot,`server capability signerSlot`),relayerUrl:PF(e.relayerUrl,`relayerUrl`),authority:e.authority,signingWalletSession:i.value})}function zF(e,t){return{activeClient:t,facts:{thresholdSessionId:e.thresholdSessionId,signer:e.signingLane.identity.signer,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,routerAbNormalSigning:e.routerAbNormalSigning,runtimePolicyScope:e.runtimePolicyScope,relayerUrl:e.relayerUrl}}}async function BF(e){let t={walletId:e.walletSession.walletId,nearAccountId:PF(e.nearAccountId,`nearAccountId`),signerSlot:FF(e.signerSlot,`signerSlot`),expectedOperationalPublicKey:PF(e.expectedOperationalPublicKey,`expectedOperationalPublicKey`),expectedThresholdSessionId:PF(e.expectedThresholdSessionId,`expectedThresholdSessionId`)};if(LF({bootstrap:e.bootstrap,identity:t,operationCredential:e.operationCredential}),e.metadata.applicationBinding.wallet_id!==String(e.walletSession.walletId)||e.metadata.applicationBinding.key_creation_signer_slot!==t.signerSlot||e.metadata.scope.threshold_session_id!==t.expectedThresholdSessionId||!g(e.metadata.materialActivation,e.bootstrap.capability.materialActivation))throw Error(`Wallet custody Ed25519 active client metadata changed`);let n=await RF({bootstrap:e.bootstrap,operationCredential:e.operationCredential,providerSubject:e.providerSubject,relayerUrl:e.relayerUrl,authority:e.authority}),r=new Iy(e.workerContext,e.activeClientHandle,e.metadata);try{let i=zF(n,r),a=await e.activateCapability(i);if(String(a.walletId)!==String(t.walletId)||String(a.nearAccountId)!==t.nearAccountId||!g(a.materialActivation,e.metadata.materialActivation))throw Error(`Wallet custody Ed25519 active client identity changed during activation`);return r=null,{thresholdSessionId:IF(n.thresholdSessionId),material:i,walletSessionState:n}}finally{r?.dispose()}}function VF(e){let t;try{t=JSON.parse(e.activationResultJson)}catch{throw Error(`the Router activation result is not JSON`)}let n=Ir(t);if(!n.ok)throw Error(`Router activation result is invalid: ${n.message}`);let r=n.value,i=r.public_receipt;if(r.binding.lifecycle.lifecycle_id!==e.admissionRequest.scope.lifecycle_id)throw Error(`the Router activation result belongs to another lifecycle`);let a=i.material_activation,o=m({kind:a.kind,activationId:a.activation_id,capability:a.capability,materialOwner:a.material_owner,keyBinding:a.key_binding,lifecycleBinding:a.lifecycle_binding,signingWorker:a.signing_worker});if(!o.ok)throw Error(`Invalid activation material reference: ${o.error.message}`);let s=e.admissionRequest.participant_ids;if(s.length!==2)throw Error(`an Ed25519 Yao registration has exactly two participants`);return{kind:Ts,scope:e.admissionRequest.scope,applicationBinding:e.admissionRequest.application_binding,participantIds:[s[0],s[1]],registeredPublicKey:Uint8Array.from(i.registered_public_key),signingWorkerVerifyingShare:Uint8Array.from(i.signing_worker_verifying_share),stateEpoch:BigInt(i.state_epoch),transcript:Uint8Array.from(i.transcript),activeCapabilityBinding:r.binding.session_id,materialActivation:o.value}}function HF(e){let t;try{t=JSON.parse(e.activationResultJson)}catch{throw Error(`the Router recovery result is not JSON`)}let n=Or(t);if(!n.ok)throw Error(`Router recovery result is invalid: ${n.message}`);if(n.value.binding.lifecycle.lifecycle_id!==e.admissionRequest.scope.lifecycle_id)throw Error(`the Router recovery result belongs to another lifecycle`);if(e.activationReceipt.binding.lifecycle.lifecycle_id!==e.admissionRequest.scope.lifecycle_id)throw Error(`the Router recovery activation belongs to another lifecycle`);let r=e.activationReceipt.public_receipt,i=m({kind:r.material_activation.kind,activationId:r.material_activation.activation_id,capability:r.material_activation.capability,materialOwner:r.material_activation.material_owner,keyBinding:r.material_activation.key_binding,lifecycleBinding:r.material_activation.lifecycle_binding,signingWorker:r.material_activation.signing_worker});if(!i.ok)throw Error(`Invalid recovery material reference: ${i.error.message}`);return{kind:Ts,scope:e.admissionRequest.scope,applicationBinding:e.admissionRequest.application_binding,participantIds:[e.admissionRequest.participant_ids[0],e.admissionRequest.participant_ids[1]],registeredPublicKey:Uint8Array.from(r.registered_public_key),signingWorkerVerifyingShare:Uint8Array.from(r.signing_worker_verifying_share),stateEpoch:BigInt(r.state_epoch),transcript:Uint8Array.from(r.transcript),activeCapabilityBinding:[...e.activationReceipt.active_capability_binding],materialActivation:i.value}}function UF(e,t){let n=e.trim();if(!n)throw Error(`Wallet custody Ed25519 projection requires ${t}`);return n}async function WF(e,t,n,r){let i=String(t.walletId),a=UF(String(n),`providerSubject`),o=(await e.listPublicCapabilityReferences()).filter(e=>String(e.walletId)===i&&g(e.materialActivation,r));if(o.length===0)return null;if(o.length!==1||!o[0])throw Error(`Wallet custody Ed25519 requires one exact public capability reference`);let s=o[0],c=(await e.listUsers()).filter(e=>String(e.walletId)===i&&String(e.nearAccountId)===String(s.nearAccountId));if(c.length!==1||!c[0])throw Error(`Wallet custody Ed25519 requires one exact persisted signer projection`);return{identity:s,user:c[0],providerSubject:a}}function GF(e){let t=e.clientExtensionResults.prf?.results?.first;if(typeof t!=`string`||!t)throw Error(`the replacement passkey returned no wallet-custody PRF output`);let n=F(t);if(n.length!==32)throw Error(`the replacement passkey returned an invalid wallet-custody PRF output`);return Uint8Array.from(n).buffer}function KF(e){let t=a(String(e.rawId||e.id||``).trim());if(!t.ok)throw Error(`replacement passkey credential id ${t.error.message}`);return{registration:e,credentialIdB64u:t.value,factorSecret:GF(e)}}async function qF(e){let t=ii(e.currentScope.material_activation),n=h(ve(`wallet-recovery-ed25519-material-activation`,32,`wallet recovery Ed25519 activation identities`)),r=y(`${e.lifecycleId}:material-activation`);if(!n.ok||!r.ok)throw Error(`wallet recovery Ed25519 material activation identity is invalid`);let i=b({activationId:n.value,capability:t.capability,materialOwner:t.materialOwner,keyBinding:t.keyBinding,lifecycleBinding:r.value,signingWorker:t.signingWorker}),a=new Uint8Array(32);globalThis.crypto.getRandomValues(a);try{return YF(Ar({scope:{lifecycle_id:e.lifecycleId,root_share_epoch:e.currentScope.root_share_epoch,account_id:e.currentScope.account_id,threshold_session_id:e.thresholdSessionId,signer_set_id:e.currentScope.signer_set_id,signing_worker_id:e.currentScope.signing_worker_id,material_activation:oi(i)},active_material_activation:e.currentScope.material_activation,application_binding:e.applicationBinding,participant_ids:e.participantIds,active_capability_binding:e.activeCapabilityBinding,replacement_capability_binding:[...a],registered_public_key:e.registeredPublicKey}),`wallet recovery Ed25519 admission request is invalid`)}finally{a.fill(0)}}function JF(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=(e[r]??0)^(t[r]??0);return n===0}function YF(e,t){if(!e.ok)throw Error(`${t}: ${e.message}`);return e.value}async function XF(e){let t=await ca({reservationId:la(e.reservationId),keySetId:e.entry.keySetId});return await qF({lifecycleId:t,thresholdSessionId:`${t}:threshold-session`,currentScope:e.entry.recoveryBasis.scope,applicationBinding:e.entry.recoveryBasis.applicationBinding,participantIds:e.entry.recoveryBasis.participantIds,activeCapabilityBinding:e.entry.recoveryBasis.activeCapabilityBinding,registeredPublicKey:e.entry.recoveryBasis.registeredPublicKey})}async function ZF(e){return await qF({lifecycleId:ve(`wallet-session-ed25519-recovery`,32,`wallet-session Ed25519 recovery lifecycles`),thresholdSessionId:e.basis.lifecycle.thresholdSessionId,currentScope:{root_share_epoch:e.basis.lifecycle.rootShareEpoch,account_id:e.basis.lifecycle.accountId,signer_set_id:e.basis.lifecycle.signerSetId,signing_worker_id:e.basis.lifecycle.signingWorkerId,material_activation:oi(e.basis.materialActivation)},applicationBinding:e.basis.applicationBinding,participantIds:e.basis.participantIds,activeCapabilityBinding:e.basis.activeCapabilityBinding,registeredPublicKey:e.basis.registeredPublicKey})}async function QF(e){let t=await e.transport.send({kind:`recovery_admit`,path:Nr,body:e.request});if(!t.ok)throw Error(`Router Ed25519 recovery admission failed: ${t.message}`);let n=YF(kr(t.value),`Router Ed25519 recovery admission is invalid`);if(n.binding.lifecycle.lifecycle_id!==e.request.scope.lifecycle_id||!ei(n.binding.material_activation,e.request.scope.material_activation))throw Error(`Router Ed25519 recovery admission changed the requested lifecycle`);return{request:e.request,receipt:n}}async function $F(e){let t=YF(Pr(JSON.parse(e.executeRequestJson)),`wallet recovery Ed25519 execute request is invalid`),n=await e.transport.send({kind:`recovery_execute`,path:Er,body:t});if(!n.ok)throw Error(`Router Ed25519 recovery execute failed: ${n.message}`);let r=YF(Or(n.value),`Router Ed25519 recovery result is invalid`);return JSON.stringify(r)}async function eI(e){let t=YF(Or(JSON.parse(e.protocolResultJson)),`Router Ed25519 recovery result is invalid`),n=await e.transport.send({kind:`recovery_activate`,path:Dr,body:{binding:t.binding,public_receipt:t.public_receipt}});if(!n.ok)throw Error(`Router Ed25519 recovery activation failed: ${n.message}`);let r=YF(Fr(n.value),`Router Ed25519 recovery activation is invalid`);if(!JF(r.active_capability_binding,e.request.replacement_capability_binding)||!JF(r.retired_capability_binding,e.request.active_capability_binding)||!JF(r.public_receipt.transcript,t.public_receipt.transcript)||!JF(r.public_receipt.registered_public_key,t.public_receipt.registered_public_key)||!JF(r.public_receipt.signing_worker_verifying_share,t.public_receipt.signing_worker_verifying_share)||r.public_receipt.state_epoch!==t.public_receipt.state_epoch||!ei(r.public_receipt.material_activation,e.request.scope.material_activation))throw Error(`Router Ed25519 recovery activation changed the requested identity`);return r}function tI(e){let t=F(e);if(t.length!==20)throw Error(`wallet recovery ECDSA identity has an invalid address`);return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function nI(e){let t=e.activationReceipt.ecdsa_activation;if(t.context.application_binding_digest_b64u!==e.publicCapability.context.application_binding_digest_b64u||!ri(t.public_identity,e.publicCapability.public_identity)||!fi(t.signing_worker,e.publicCapability.signer_set.selected_server)||!ei(t.material_activation,e.publicCapability.material_activation)||t.activation_epoch!==e.publicCapability.activation_epoch||e.activationReceipt.server_generation!==e.serverGeneration)throw Error(`wallet recovery ECDSA activation changed its registered capability`)}function rI(e){let t=e.publicCapability.public_identity;if(e.challenge.walletId!==e.walletId||e.challenge.reservationId!==e.reservationId||e.challenge.replacementId!==e.replacementId||e.challenge.keySetId!==e.entry.keySetId||e.challenge.keyHandle!==e.entry.keyHandle||e.challenge.recordedKeyManifestDigestB64u!==e.entry.recordedKeyManifestDigestB64u||e.challenge.expectedServerGeneration!==String(e.entry.recoveryBasis.serverGeneration)||e.challenge.derivationClientSharePublicKey33B64u!==t.derivation_client_share_public_key33_b64u)throw Error(`wallet recovery ECDSA possession challenge changed its registered identity`)}function iI(e){let t=e.publicCapability.public_identity;if(e.publicFacts.contextBinding32B64u!==t.context_binding_b64u||e.publicFacts.derivationClientSharePublicKey33B64u!==t.derivation_client_share_public_key33_b64u||e.publicFacts.clientVerifyingShare33B64u!==t.derivation_client_share_public_key33_b64u||e.publicFacts.relayerPublicKey33B64u!==t.server_public_key33_b64u||e.publicFacts.groupPublicKey33B64u!==t.threshold_public_key33_b64u||e.publicFacts.clientShareRetryCounter!==t.client_share_retry_counter||e.publicFacts.relayerShareRetryCounter!==t.server_share_retry_counter||e.publicFacts.ethereumAddress!==tI(t.ethereum_address20_b64u))throw Error(`wallet recovery ECDSA custody public facts changed the capability`)}function aI(e){let t=e.trim();if(!t)throw Error(`wallet recovery ECDSA returned no ready state blob`);return{kind:`ecdsa_role_local_state_blob_v1`,curve:`secp256k1`,encoding:`base64url`,producer:`signer_core`,stateBlobB64u:t}}async function oI(e){let t=ci(e.entry.recoveryBasis.publicCapability),n=Zr(e.entry.recoveryBasis.activationReceipt);nI({activationReceipt:n,publicCapability:t,serverGeneration:String(e.entry.recoveryBasis.serverGeneration)});let r=Pl(e.entry.recoveryBasis.possessionChallenge);rI({challenge:r,entry:e.entry,walletId:e.walletId,reservationId:e.reservationId,replacementId:e.replacementId,publicCapability:t});let i=P(await ee(ne(t)));if(r.publicCapabilityDigestB64u!==i)throw Error(`wallet recovery ECDSA possession challenge changed the capability digest`);iI({publicFacts:e.publicFacts,publicCapability:t});let a=await id({workerCtx:e.workerCtx,challenge:r,stateBlob:aI(e.readyStateBlobB64u)}),o=await Ml(r);if(a.challengeDigestB64u!==o||a.derivationClientSharePublicKey33B64u!==r.derivationClientSharePublicKey33B64u)throw Error(`wallet recovery ECDSA possession proof changed its challenge binding`);return{activationReceipt:n,publicCapability:t,possessionProof:a.proof}}function sI(e){return e.entryIndex===0?{kind:`reseal_replacement_factor`,factorJson:JSON.stringify({envelopeId:e.replacementFactor.replacementId,walletAuthMethodId:e.replacementFactor.walletAuthMethodId,factor:e.replacementFactor.factor}),factorSecret:e.replacementFactor.factorSecret.slice(0)}:{kind:`preserve_existing`}}function cI(e){return Uint8Array.from(e).buffer}function lI(e){e.kind===`reseal_replacement_factor`&&new Uint8Array(e.factorSecret).fill(0)}function uI(e){let t=F(e);if(t.length!==20)throw Error(`wallet recovery ECDSA identity has an invalid address`);return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function dI(e){let t=e.entry.recoveryBasis.publicCapability.public_identity;if(e.bootstrap.contextBinding32B64u!==t.context_binding_b64u||e.bootstrap.clientSharePublicKey33B64u!==t.derivation_client_share_public_key33_b64u||e.bootstrap.clientShareRetryCounter!==t.client_share_retry_counter)throw Error(`wallet recovery changed ECDSA identity for ${e.entry.keySetId}`)}function fI(e){if(!e.candidate)return e.current;if(e.current)throw Error(`wallet recovery produced more than one replacement envelope`);return e.candidate}async function pI(e){let t=[],n=[],r=null;for(let[i,a]of e.prepared.keyManifest.entries.entries()){let o=null,s=null;try{let c=cI(e.recoveryCodeBytes);o=c;let l=sI({entryIndex:i,replacementFactor:e.replacementFactor});switch(s=l,a.kind){case`near_ed25519`:{let n=new Ds({routing:{kind:`discovery`},routerOrigin:new URL(e.relayUrl).origin,authorization:{kind:`recovery_challenge`,challengeId:e.recoveryChallengeId},fetch:globalThis.fetch}),i=await XF({reservationId:e.prepared.reservationId,entry:a}),o=await QF({request:i,transport:n}),s=await $s({runStep:e.runStep,walletId:e.walletId,custodyJson:e.custodyJson,recoveryCode:c,recordedKeyManifestDigestB64u:a.recordedKeyManifestDigestB64u,factorReplacement:l,nearEd25519SigningKeyId:a.recoveryBasis.applicationBinding.near_ed25519_signing_key_id,yaoAdmission:o.receipt,yaoApplication:o.request.application_binding,participantIds:o.request.participant_ids,registeredPublicKeyB64u:P(Uint8Array.from(a.recoveryBasis.registeredPublicKey)),runRouterRound:e=>$F({executeRequestJson:e,transport:n}),activateRouterRecovery:e=>eI({request:i,protocolResultJson:e,transport:n})});if(!s.localMaterial)throw Error(`wallet recovery produced no NEAR local material`);r=fI({current:r,candidate:s.recoveryReplacementEnvelope}),t.push({entry:a,metadata:HF({admissionRequest:i,activationResultJson:s.activationResultJson,activationReceipt:s.activationReceipt}),localMaterial:s.localMaterial});break}case`evm_family_ecdsa`:{let t=await cc({runStep:e.runStep,walletId:e.walletId,custodyJson:e.custodyJson,recoveryCode:c,recordedKeyManifestDigestB64u:a.recordedKeyManifestDigestB64u,factorReplacement:l,evmFamilySigningKeySlotId:a.evmFamilySigningKeySlotId,applicationBindingDigestB64u:a.recoveryBasis.publicCapability.context.application_binding_digest_b64u,registeredClientRootPublicKey33B64u:a.recoveryBasis.clientRootPublicKey33B64u,resolveRelayerPublicIdentity:async e=>(dI({entry:a,bootstrap:e}),JSON.stringify({relayerKeyId:a.recoveryBasis.publicCapability.signer_set.selected_server.server_id,relayerPublicKey33B64u:a.recoveryBasis.publicCapability.public_identity.server_public_key33_b64u,groupPublicKey33B64u:a.recoveryBasis.publicCapability.public_identity.threshold_public_key33_b64u,ethereumAddress:uI(a.recoveryBasis.publicCapability.public_identity.ethereum_address20_b64u),relayerShareRetryCounter:a.recoveryBasis.publicCapability.public_identity.server_share_retry_counter}))}),i=await oI({entry:a,walletId:e.walletId,reservationId:e.prepared.reservationId,replacementId:e.replacementFactor.replacementId,readyStateBlobB64u:t.readyStateBlobB64u,publicFacts:t.publicFacts,workerCtx:e.workerCtx});r=fI({current:r,candidate:t.recoveryReplacementEnvelope}),n.push({entry:a,activation:i,readyStateBlobB64u:t.readyStateBlobB64u,publicFacts:t.publicFacts});break}}}finally{s&&lI(s),o&&new Uint8Array(o).fill(0)}}if(!r)throw Error(`wallet recovery produced no replacement custody envelope`);return{replacementEnvelope:Zs({expectedWalletId:e.walletId,replacement:r,activatedAtMs:(e.nowMs??Date.now)()}),nearKeySets:t,ecdsaKeySets:n}}const mI=[250,500,1e3];function hI(e){return new Promise(t=>setTimeout(t,e))}async function gI(e){let t=e.wait??hI,n=JSON.parse(e.executeRequestJson),r=0;for(let i=0;;i+=1){let a=await e.transport.send({kind:`execute`,path:jr,body:n});if(a.ok)return JSON.stringify(a.value);if(a.code!==`execution_in_progress`||r>=15e3)throw Error(`Router Ed25519 Yao execute failed: ${a.message}`);let o=mI[Math.min(i,mI.length-1)];await t(o),r+=o}}async function _I(e){let{authority:t,authMethod:n}=e.projection;if(String(t.walletId)!==e.walletId||String(n.walletId)!==e.walletId||String(n.walletAuthMethodId)!==e.walletAuthMethodId||String(n.walletAuthorityId)!==String(t.authorityId))throw Error(`Verified Email OTP authority changed during wallet unlock`);switch(t.provenance.kind){case`wallet_registration`:await K.persistFoundingWalletAuthority({authority:t,authMethod:n});return;case`wallet_recovery`:{if(!Gr(t))throw Error(`Recovered Email OTP authority provenance is invalid`);let r=await K.resolveWalletAuthorityForMethod(e.walletId,e.walletAuthMethodId),i=r.kind===`resolved`?[...String(r.authority.authorityId)===String(t.authorityId)?[]:[`authorityId`],...String(r.authority.authorityDigestB64u)===String(t.authorityDigestB64u)?[]:[`authorityDigest`],...r.authMethod.kind===`email_otp`?[]:[`method.kind`],...r.authMethod.status===`active`?[]:[`method.status`],...String(r.authMethod.walletAuthMethodId)===String(n.walletAuthMethodId)?[]:[`method.id`],...String(r.authMethod.walletAuthorityId)===String(n.walletAuthorityId)?[]:[`method.authorityId`],...r.authMethod.kind===`email_otp`&&r.authMethod.emailHashHex!==n.emailHashHex?[`method.emailHash`]:[]]:[`resolution:${r.kind}`];if(i.length>0)throw Error(`Verified recovered Email OTP authority is not installed on this device: ${i.join(`, `)}`);return}case`device_link`:{let n=await K.resolveWalletAuthorityForMethod(e.walletId,e.walletAuthMethodId);if(n.kind!==`resolved`||String(n.authority.authorityId)!==String(t.authorityId)||String(n.authority.authorityDigestB64u)!==String(t.authorityDigestB64u))throw Error(`Verified linked Email OTP authority is not installed on this device`);return}}t.provenance}async function vI(e){let{authority:t,authMethod:n}=e.projection;if(String(t.walletId)!==e.walletId||String(n.walletId)!==e.walletId||String(n.walletAuthMethodId)!==e.walletAuthMethodId||String(n.walletAuthorityId)!==String(t.authorityId)||n.emailHashHex!==e.emailHashHex)throw Error(`Verified Email OTP authority does not match the wallet unlock factor`);let r=di({walletId:e.walletId,provider:e.providerSubject.startsWith(`google:`)?`google`:`email`,providerUserId:e.providerSubject,emailHashHex:e.emailHashHex});return await U({authority:{walletId:r.walletId,factor:r.factor,verifier:r.verifier,bindingId:n.walletAuthMethodId}})}function yI(){}async function bI(e,t){switch(t.kind){case`near_ed25519_wallet`:await e.signingEngine.activateAuthenticatedWalletState({walletId:t.signer.account.wallet.walletId,nearAccountId:B(t.signer.account.nearAccountId),signerSlot:t.signer.signerSlot,...e.nearClient?{nearClient:e.nearClient}:{}}),await e.signingEngine.markSelectedEmailOtpWalletAuthorityUnlocked({walletId:t.signer.account.wallet.walletId,walletAuthMethodId:t.walletAuthMethodId}),e.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.signer.account.wallet.walletId,authMethod:`email_otp`});return;case`evm_family_ecdsa_wallet`:{let n=e.signingEngine.getUserPreferences();n.setCurrentWallet(t.walletId),await n.reloadUserSettings().catch(yI),await e.signingEngine.markSelectedEmailOtpWalletAuthorityUnlocked({walletId:t.walletId,walletAuthMethodId:t.walletAuthMethodId}),e.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.walletId,authMethod:`email_otp`});return}}}function xI(e){switch(e){case`email_otp`:return{authMethod:z.emailOtp,signerSource:Ut.emailOtpRegistration};case`login`:case`registration`:case`manual-bootstrap`:return{authMethod:z.passkey,signerSource:Ut.passkeyRegistration};default:throw Error(`[SigningEngine] unsupported threshold ECDSA session source`)}}function SI(e){throw Error(`[SigningEngine] unsupported threshold ECDSA bootstrap backend binding: ${JSON.stringify(e)}`)}async function CI(e){let t=e.bootstrap.thresholdEcdsaKeyRef.backendBinding;if(!t)throw Error(`[SigningEngine] ECDSA bootstrap is missing its backend binding`);let n=wI(t);if(!n)return;let r=await e.deps.persistEcdsaRoleLocalReadyRecord({record:n,storageKeyFacts:Ni(n)});if(!r.ok)throw Error(`[SigningEngine] ECDSA role-local ready record persistence failed (${r.code}): ${r.message}`)}function wI(e){switch(e.materialKind){case`role_local_ready_state_blob`:return e.ecdsaRoleLocalReadyRecord;case`role_local_worker_handle`:case`role_local_durable_public_anchor`:case`role_local_durable_sealed_ref`:case`metadata_only`:return null;default:return SI(e)}}async function TI(e,t){return t.source===`email_otp`?await e.ensureSealedRefreshStartupParityForThresholdEcdsaBootstrap({kind:`email_otp_bootstrap_parity`,walletId:t.walletId,chainTarget:t.chainTarget,authMethod:z.emailOtp}):await e.ensureSealedRefreshStartupParityForThresholdEcdsaBootstrap({kind:`default_bootstrap_parity`,walletId:t.walletId,chainTarget:t.chainTarget}),await _u(e.queueByWallet,t.walletId,async()=>{let n=t.bootstrap;if(!String(n.thresholdEcdsaKeyRef.ecdsaThresholdKeyId||``).trim())throw Error(`[SigningEngine] threshold-ecdsa bootstrap did not provide canonical ecdsaThresholdKeyId`);return await _h({bootstrapStore:e.bootstrapStore,walletId:t.walletId,chainTarget:t.chainTarget,bootstrap:n,signerAuth:xI(t.source)}),await CI({deps:e,bootstrap:n}),{bootstrap:n,authorization:await Bl(q,{walletId:t.walletId,authority:t.authority,bootstrap:n})}})}async function EI(e,t){let n=t.source===`email_otp`?await TI(e,{walletId:t.walletId,chainTarget:t.chainTarget,bootstrap:t.bootstrap,source:`email_otp`,authority:t.authority,emailOtpAuthContext:t.emailOtpAuthContext}):await TI(e,{walletId:t.walletId,chainTarget:t.chainTarget,bootstrap:t.bootstrap,source:t.source,authority:t.authority});return{bootstrap:n.bootstrap,authorization:n.authorization}}function DI(e){let t=[],n=new Set;for(let r of e.network.chains){let e=qe(r.network);if(e!==`evm`&&e!==`tempo`)continue;let i=Sn(r),a=H(i);n.has(a)||(n.add(a),t.push(i))}if(!t.length)throw Error(`[EmailOtpSession] exact ECDSA snapshot requires configured ECDSA targets`);return t}function OI(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}function kI(){return{signingSessionSealApplyMs:0,warmCapabilityPersistenceMs:0}}function AI(e,t,n){e[t]+=Math.max(0,Math.round(OI()-n))}function jI(e,t){e.signingSessionSealApplyMs+=t.signingSessionSealApplyMs,e.warmCapabilityPersistenceMs+=t.warmCapabilityPersistenceMs}function MI(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:null}function NI(e){let t=[],n=new Set,r=e=>{let r=H(e);n.has(r)||(n.add(r),t.push(e))};r(e.chainTarget);let i=e.additionalChainTargets!==void 0;for(let t of e.additionalChainTargets||[])r(t);if(!i&&_l(e.emailOtpAuthContext)===`session`)for(let t of DI(e.configs))r(t);return t}function PI(e){let t=Pe(e.runtimePolicyScope),n=String(t.signingRootId).trim(),r=String(t.signingRootVersion||`default`).trim();if(!n||!r)throw Error(`Email OTP ECDSA persisted identity is incomplete`);return{signingRootId:n,signingRootVersion:r}}function FI(e){let t=e.existingKey.persistedRoleLocalMaterial.publicFacts,n=ji({walletId:t.walletId,chainTarget:e.chainTarget,keyHandle:t.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,applicationBindingDigestB64u:t.applicationBindingDigestB64u,clientParticipantId:t.clientParticipantId,relayerParticipantId:t.relayerParticipantId,participantIds:t.participantIds,contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:t.relayerPublicKey33B64u,groupPublicKey33B64u:t.groupPublicKey33B64u,ethereumAddress:t.ethereumAddress,publicCapability:t.publicCapability});return{keyHandle:e.existingKey.keyHandle,publicCapability:n.publicCapability,walletKey:Ma({walletId:n.walletId,keyHandle:n.keyHandle,chainTarget:e.chainTarget,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,participantIds:n.participantIds,thresholdOwnerAddress:n.ethereumAddress,thresholdEcdsaPublicKeyB64u:n.groupPublicKey33B64u}),persistedRoleLocalMaterial:Rd({authority:e.existingKey.persistedRoleLocalMaterial.authority,materialActivation:e.existingKey.persistedRoleLocalMaterial.materialActivation,publicFacts:n}),runtimePolicyScope:e.existingKey.runtimePolicyScope}}function II(e){let t=e.durableMaterial.roleLocalPublicFacts,n=Ma({walletId:t.walletId,keyHandle:t.keyHandle,chainTarget:t.chainTarget,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,participantIds:t.participantIds,thresholdOwnerAddress:t.ethereumAddress,thresholdEcdsaPublicKeyB64u:t.groupPublicKey33B64u});return{keyHandle:String(n.keyHandle),publicCapability:t.publicCapability,walletKey:n,persistedRoleLocalMaterial:Rd({authority:e.signer.authority,materialActivation:e.activation.materialActivation,publicFacts:t}),runtimePolicyScope:e.durableMaterial.runtimePolicyScope}}async function LI(e){let t=e.scope.kind===`exact`?PI({runtimePolicyScope:e.scope.runtimePolicyScope}):null,n=String(e.keyHandle||``).trim(),r=e.scope.kind===`durable_manifest`?null:e.scope.authorityRef,i=(await e.listActiveEcdsaCapabilityManifestsForWallet(e.walletId)).filter(i=>{let a=i.durableMaterial.roleLocalPublicFacts;return i.signer.walletId===e.walletId&&(!r||i.signer.authority.walletAuthMethodId===r.walletAuthMethodId&&String(i.signer.authority.authorityDigest)===String(r.authorityDigest))&&i.signer.scope.targetMemberships.some(t=>wn(t,e.chainTarget))&&(!n||String(a.keyHandle).trim()===n)&&(!t||String(a.signingRootId).trim()===t.signingRootId)&&(!t||String(a.signingRootVersion||`default`).trim()===t.signingRootVersion)}).map(II).reduce((t,n)=>{let r=t.find(e=>e.keyHandle===n.keyHandle);if(!r)return t.push(n),t;if(!ti(r.publicCapability,n.publicCapability)||!g(r.persistedRoleLocalMaterial.materialActivation,n.persistedRoleLocalMaterial.materialActivation))throw Error(`Email OTP ECDSA has conflicting persisted role-local material for ${H(e.chainTarget)}`);return t},[]);if(i.length===0)return null;if(i.length!==1)throw Error(`Email OTP ECDSA has multiple persisted public capabilities for ${H(e.chainTarget)}`);return FI({existingKey:i[0],chainTarget:e.chainTarget})}function RI(e){return{authMethod:`email_otp`,curve:`ecdsa`,walletId:e.walletId,chainTarget:e.chainTarget,walletSessionId:e.walletSessionId,quotaId:e.quotaId,thresholdSessionId:Qt.thresholdEcdsaSession(e.thresholdSessionId),emailOtpAuthContext:e.emailOtpAuthContext,material:{kind:`worker_handle`,workerSessionId:e.thresholdSessionId}}}function zI(e){let t=String(e.warmThresholdSessionId).trim();if(!t)throw Error(`Email OTP sealed refresh requires a warm threshold session`);return{warmMaterialTarget:{kind:`ecdsa`,thresholdSessionId:t},authorizationThresholdSessionId:BI(e.normalSigning)}}function BI(e){return ni(e)}async function VI(e,t){if(e.bootstraps.length!==e.publicationChainTargets.length)throw Error(`Email OTP ECDSA publication returned an unexpected lane count`);let n=kI(),r=[],i=e.bootstraps[0]?.session;if(!i)throw Error(`Email OTP ECDSA publication has no primary session`);for(let[t,n]of e.bootstraps.entries()){let a=e.publicationChainTargets[t],o=n.thresholdEcdsaKeyRef.chainTarget;if(!wn(o,a))throw Error(`Email OTP ECDSA publication returned ${H(o)} for ${H(a)}`);if(n.session.walletSessionId!==i.walletSessionId||n.session.quotaId!==i.quotaId)throw Error(`Email OTP ECDSA publication returned mismatched Wallet Session authority`);r.push({chainTarget:a,bootstrap:n})}let a={args:e,ports:t},o=await Promise.all(r.map(UI.bind(null,a))),s=o.map(HI);for(let e of o)jI(n,e.timings);let[c,...l]=s;if(!c)throw Error(`Email OTP ECDSA publication did not commit a primary lane`);return{bootstrap:c.bootstrap,authorization:c.authorization,authorizations:[c.authorization,...l.map(e=>e.authorization)],timings:n}}function HI(e){return e.result}async function UI(e,t){let n=kI(),r=t.bootstrap,i=OI(),a=await e.ports.commitEvmFamilyThresholdEcdsaSessions({walletId:e.args.walletId,chainTarget:t.chainTarget,bootstrap:r,source:`email_otp`,authority:e.args.authority,emailOtpAuthContext:e.args.emailOtpAuthContext});return AI(n,`warmCapabilityPersistenceMs`,i),jI(n,await WI({walletId:e.args.walletId,chainTarget:t.chainTarget,bootstrap:a.bootstrap,runtimePolicyScope:e.args.runtimePolicyScope,emailOtpAuthContext:e.args.emailOtpAuthContext,relayerUrl:e.args.relayerUrl,groupId:e.args.groupId},e.ports)),{result:a,timings:n}}async function WI(e,t){let n=kI();if(t.configs.signing.sessionPersistenceMode!==`sealed_refresh_v1`||_l(e.emailOtpAuthContext)!==`session`)return n;let r=t.getSignerWorkerContext();if(!r)throw Error(`Email OTP sealed refresh requires the dedicated emailOtp worker`);let i=e.bootstrap.thresholdEcdsaKeyRef,a=e.bootstrap.session,o=String(a.thresholdSessionId||``).trim(),s=String(e.relayerUrl||i.relayerUrl||``).trim();if(e.groupId&&e.groupId!==`rfc2409-group2`)throw Error(`Email OTP sealed refresh received an unsupported Shamir group`);let c=Ze;if(!o||!s)throw Error(`Email OTP sealed refresh is missing threshold-session persistence metadata`);let l=RI({walletId:e.walletId,chainTarget:e.chainTarget,walletSessionId:a.walletSessionId,quotaId:a.quotaId,thresholdSessionId:o,emailOtpAuthContext:e.emailOtpAuthContext}),u=a.operationCredential,d=e.runtimePolicyScope,f=Pe(d),p=String(f?.signingRootId||``).trim(),m=String(f?.signingRootVersion||``).trim(),h=String(i.ecdsaThresholdKeyId||``).trim(),_=String(i.userId||``).trim(),v=String(ll(e.emailOtpAuthContext)||_).trim(),y=String(xl(e.emailOtpAuthContext)).trim(),b=MI(i.ethereumAddress),x=String(i.backendBinding?.clientVerifyingShareB64u||``).trim(),S=String(i.thresholdEcdsaPublicKeyB64u||``).trim(),C=String(i.backendBinding?.relayerKeyId||``).trim(),w=i.routerAbEcdsaDerivationNormalSigning,T=i.backendBinding,E=null,D=null;(T?.materialKind===`role_local_worker_handle`||T?.materialKind===`role_local_durable_sealed_ref`)&&(E=T.roleLocalMaterialRef,D=T.publicFacts.publicCapability);let O=Array.isArray(i.participantIds)?i.participantIds.map(e=>Math.floor(Number(e))).filter(e=>Number.isFinite(e)&&e>0):[];if(!h||!_||!v||!y||!b||!x||!C||!w||!D||!E||!O.length||!u.token||!p||!m)throw Error(`Email OTP sealed refresh is missing ECDSA restore metadata`);if(l.material.kind!==`worker_handle`)throw Error(`Email OTP sealed refresh requires worker-owned warm material`);let k=l.material.workerSessionId,A=i.chainTarget;if(!A)throw Error(`Email OTP sealed refresh requires exact ECDSA chain target`);if(!wn(A,l.chainTarget))throw Error(`Email OTP sealed refresh chain target drifted from ${H(l.chainTarget)} to ${H(A)}`);let j=String(i.keyHandle||``).trim();if(!j)throw Error(`Email OTP sealed refresh requires exact ECDSA key handle`);let M=E.materialActivation,ee=zI({warmThresholdSessionId:k,normalSigning:w}),te=await U({authority:e.emailOtpAuthContext.authority}),ne=await LI({walletId:e.walletId,chainTarget:e.chainTarget,scope:{kind:`exact`,runtimePolicyScope:d,authorityRef:te},keyHandle:j,listActiveEcdsaCapabilityManifestsForWallet:t.listActiveEcdsaCapabilityManifestsForWallet});if(!ne||!g(ne.persistedRoleLocalMaterial.materialActivation,M))throw Error(`Email OTP sealed refresh material activation was superseded`);let re=OI(),N=await GP({workerCtx:r,target:ee.warmMaterialTarget,authorizationThresholdSessionId:ee.authorizationThresholdSessionId,transport:{relayerUrl:s,operationCredential:u,groupId:c}}).catch(e=>{let t=e instanceof Error?e.message:String(e||`unknown error`);throw Error(`Email OTP sealed refresh seal failed: ${t}`)});if(AI(n,`signingSessionSealApplyMs`,re),!N?.ok){let e=String(N?.message||N?.code||`unknown error`).trim();throw Error(`Email OTP sealed refresh seal failed: ${e}`)}let ie=String(N.sealedSecretB64u||``).trim(),ae=Math.floor(Number(N.expiresAtMs)||Number(a?.expiresAtMs)||0),oe=Math.floor(Number(N.remainingUses)||Number(a?.remainingUses)||0);if(!ie||ae<=0||oe<0)throw Error(`Email OTP sealed refresh seal returned invalid persistence metadata`);let se=String(N.keyVersion||``).trim();if(!se)throw Error(`Email OTP sealed refresh seal returned no key version`);let ce=Date.now(),le={thresholdSessionId:l.thresholdSessionId,sealedSecretB64u:ie,curve:`ecdsa`,authMethod:`email_otp`,thresholdSessionIds:{ecdsa:l.thresholdSessionId},walletId:String(e.walletId||``).trim(),relayerUrl:s,keyVersion:se,groupId:c,issuedAtMs:ce,expiresAtMs:ae,remainingUses:oe},ue=OI(),de=await LI({walletId:e.walletId,chainTarget:A,scope:{kind:`exact`,runtimePolicyScope:d,authorityRef:te},keyHandle:j,listActiveEcdsaCapabilityManifestsForWallet:t.listActiveEcdsaCapabilityManifestsForWallet});if(!de||!g(de.persistedRoleLocalMaterial.materialActivation,M))throw Error(`Email OTP sealed refresh material activation was superseded`);let fe=de.persistedRoleLocalMaterial.authority;await t.registerSigningSession({...le,ecdsaRestore:{chainTarget:A,source:`email_otp`,signingRootId:p,signingRootVersion:m,provider:cl(e.emailOtpAuthContext),providerSubjectId:v,emailHashHex:y,authority:fe,emailOtpAuthority:e.emailOtpAuthContext.authority,...d?{runtimePolicyScope:d}:{},keyHandle:j,ecdsaThresholdKeyId:h,ethereumAddress:b,relayerKeyId:C,clientVerifyingShareB64u:x,...S?{thresholdEcdsaPublicKeyB64u:S}:{},participantIds:O,routerAbEcdsaDerivationNormalSigning:w,publicCapability:D,roleLocalMaterialRef:E},updatedAtMs:ce});let pe=await t.readExactSealedSession(o,{authMethod:`email_otp`,curve:`ecdsa`,chainTarget:A}).catch(e=>{let t=e instanceof Error?e.message:String(e||`unknown error`);throw Error(`Email OTP sealed refresh read-back failed: ${t}`)});if(AI(n,`warmCapabilityPersistenceMs`,ue),!pe)throw Error(`Email OTP sealed refresh ${H(A)} record was not durably persisted`);let me=pe.ecdsaRestore?.roleLocalMaterialRef;if(pe.authMethod!==`email_otp`||pe.secretKind!==`signing_session_secret32`||pe.thresholdSessionIds.ecdsa!==o||pe.sealedSecretB64u!==ie||!me||!GI(me,E)||!pe.ecdsaRestore?.chainTarget||!wn(pe.ecdsaRestore.chainTarget,A))throw Error(`Email OTP sealed refresh read-back record does not match ${H(A)} unlock session`);return n}function GI(e,t){return e.kind===t.kind&&e.durableMaterialRef===t.durableMaterialRef&&e.bindingDigest===t.bindingDigest&&g(e.materialActivation,t.materialActivation)}function KI(e){return{thresholdSessionId:Qt.thresholdEcdsaSession(e.thresholdSessionId)}}function qI(e){if(!e)return{kind:`not_requested`};switch(e.kind){case`wallet_custody_cache_absent`:return{kind:`cache_absent`,bootstrap:e.ed25519YaoRecovery};case`ed25519_yao_capability`:return{kind:`capability`,activeClientHandle:e.activeClientHandle,metadata:e.metadata,bootstrap:e.ed25519YaoCapability}}throw Error(`Unsupported Email OTP Ed25519 unlock material`)}async function JI(e){if(e.workerResult){switch(e.workerResult.kind){case`wallet_custody_cache_absent`:return;case`ed25519_yao_capability`:if(!await Fy({workerContext:e.workerContext,activeClientHandle:e.workerResult.activeClientHandle}))throw Error(`Email OTP capability unlock local Ed25519 client was unavailable`);return}e.workerResult}}function YI(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}async function XI(e){try{await no(ro(e.workerContext),{existingEnvelope:e.unlock.ed25519ExportRootCustody.existingEnvelope,existingFactorSecret:e.unlock.ed25519ExportRootCustody.factorSecret32,walletId:String(e.authorization.record.walletId),walletAuthMethodId:e.walletAuthMethodId,walletSessionId:String(e.authorization.operationCredential.walletSessionId),expiresAtMs:e.authorization.record.expiresAtMs})}catch(e){console.warn(`[SigningEngine][email-otp] unlocked Ed25519 export-root capability was not established:`,e instanceof Error?e.message:String(e||`unknown error`))}}function ZI(){return{emailOtpProofVerificationMs:0,ecdsaMaterialRestoreMs:0,signingSessionSealApplyMs:0,warmCapabilityPersistenceMs:0}}function QI(e,t,n){e[t]+=Math.max(0,Math.round(YI()-n))}function $I(e,t){e.signingSessionSealApplyMs+=t.signingSessionSealApplyMs,e.warmCapabilityPersistenceMs+=t.warmCapabilityPersistenceMs}function eL(e,t){let n=String(e||``).trim();if(!n)throw Error(`[SigningEngine][email-otp] ${t} is required`);return n}function tL(e){return{provider:e.identity.provider,providerUserId:eL(e.identity.providerUserId,`Email OTP provider user id`)}}async function nL(e){let t=await e.ownerLaneScopeStores.listWalletAuthMethodsForWallet(String(e.walletId)),n=[];for(let r of t){if(r.kind!==`email_otp`||r.status!==`active`||String(r.walletId)!==String(e.walletId)||String(r.emailHashHex)!==String(e.emailHashHex))continue;let t=r.authority;String(t.walletId)!==String(e.walletId)||t.factor.provider!==e.provider||String(t.factor.providerUserId)!==String(e.providerUserId)||String(t.verifier.emailHashHex)!==String(e.emailHashHex)||n.push(t)}let[r,...i]=n;if(!r)return{kind:`canonical_boundary`};if(i.length>0)throw Error(`Email OTP identity matches more than one active wallet auth method`);return{kind:`selected_v2`,authority:r}}function rL(e){let t=r(e.walletAuthMethodId);if(!t.ok)throw Error(`Selected Email OTP wallet auth method is invalid`);let n=di({walletId:e.walletId,provider:e.provider,providerUserId:e.providerUserId,emailHashHex:e.emailHashHex});return{kind:`selected_v2`,authority:{walletId:n.walletId,factor:n.factor,verifier:n.verifier,bindingId:t.value}}}async function iL(e){if(e.authoritySelector.kind===`wallet_auth_method`)return await rL({walletId:e.walletId,walletAuthMethodId:e.authoritySelector.walletAuthMethodId,emailHashHex:e.emailHashHex,provider:e.provider,providerUserId:e.providerUserId});let t=await e.authorityPorts.resolveSelectedWalletAuthority(String(e.walletId));if(t.kind===`missing_selection`)return{kind:`canonical_boundary`};if(t.kind!==`resolved`)throw Error(`Email OTP authority selection is unavailable: ${t.kind}`);if(t.authMethod.kind!==`email_otp`)return await nL({walletId:e.walletId,emailHashHex:e.emailHashHex,provider:e.provider,providerUserId:e.providerUserId,ownerLaneScopeStores:e.authorityPorts.ownerLaneScopeStores});if(t.authMethod.status!==`active`||t.authority.state!==`active`||String(t.authMethod.walletId)!==String(e.walletId)||String(t.authority.walletId)!==String(e.walletId)||String(t.authMethod.walletAuthorityId)!==String(t.authority.authorityId))throw Error(`Email OTP authority selected by the wallet is not active`);let n=t.authMethod,r=String(n.walletAuthMethodId),i=await Jp({authMethod:n,stores:e.authorityPorts.ownerLaneScopeStores});if(!bi(i))throw Error(`Email OTP authority selected by the wallet session has the wrong factor`);let a=await U({authority:i});if(String(a.walletId)!==String(t.authority.walletId)||String(a.walletAuthMethodId)!==r||String(i.verifier.emailHashHex)!==String(e.emailHashHex)||i.factor.provider!==e.provider||String(i.factor.providerUserId)!==String(e.providerUserId))throw Error(`Email OTP authority selected by the wallet session does not match the request`);return{kind:`selected_v2`,authority:i}}function aL(e){return e.source.kind===`selected_v2`&&!e.runtimePolicyScope?{kind:`exact_authority`,authorityRef:e.authorityRef}:e.runtimePolicyScope?{kind:`exact`,runtimePolicyScope:e.runtimePolicyScope,authorityRef:e.authorityRef}:{kind:`durable_manifest`}}function oL(e){if(`persistedExportMaterial`in e&&`explicitExportAuthorization`in e&&e.operation===`export_key`)return e;throw Error(`Email OTP ECDSA export requires prepared operation authorization`)}function sL(e){switch(e.unseal.kind){case`email_otp_grant`:return{kind:`email_otp_unseal_grant`,grant:e.unseal.grant,challengeId:e.unseal.challenge_id};case`not_requested`:throw Error(`Email OTP ECDSA export requires its verified unseal grant`);default:{let t=e.unseal;throw Error(`Unsupported Email OTP ECDSA export unseal state: ${String(t)}`)}}}function cL(e){if(e.operation!==e.routePlan.operation)throw Error(`Email OTP operation does not match its route plan`)}function lL(e){let t=e.existingKey.walletKey;if(String(e.handle.walletId)!==String(t.walletId)||String(e.handle.keyHandle)!==String(t.keyHandle)||e.handle.authSubjectId!==ll(e.emailOtpAuthContext)||!wn(e.handle.chainTarget,t.chainTarget)||!wn(e.handle.chainTarget,e.chainTarget))throw Error(`Email OTP ECDSA export worker handle does not match the resolved lane`)}function uL(e){if(!hl(e))throw Error(`Email OTP ECDSA export requires single-use authorization`);return e}function dL(e){let t=Ce({ttlMs:e.ttlMs??Se.ttlMs,remainingUses:e.remainingUses});return{ttlMs:t.ttlMs,remainingUses:t.remainingUses}}function fL(e){let t=e.bootstrap.session,n=Math.floor(Number(t.expiresAtMs)),r=Math.floor(Number(t.remainingUses)),i=n-Date.now();if(!Number.isSafeInteger(n)||i<1)throw Error(`Email OTP capability unlock returned an invalid server signing budget`);if(r!==e.expectedRemainingUses)throw Error(`Email OTP capability unlock changed the requested signing budget uses`);return{ttlMs:i,remainingUses:r}}function pL(e){return e.ed25519YaoResult?fL({bootstrap:e.ed25519YaoResult.kind===`wallet_custody_cache_absent`?e.ed25519YaoResult.ed25519YaoRecovery:e.ed25519YaoResult.ed25519YaoCapability,expectedRemainingUses:e.requestedRemainingUses}):dL({ttlMs:e.requestedTtlMs,remainingUses:e.requestedRemainingUses})}function mL(e){if(!e)throw Error(`Email OTP capability recovery requires explicit wallet unlock`);return e}function hL(e){return{kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:String(e.keyHandle),session_policy:e.request.session_policy}}function gL(e){return{kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:String(e.keyHandle),session_policy:{threshold_session_id:SL(e.thresholdSessionId),wallet_session_mint_id:CL(e.walletSessionMintId),ttl_ms:e.ttlMs,remaining_uses:e.remainingUses,runtime_policy_scope:e.runtimePolicyScope}}}function _L(e,t){if(e.operation!==`wallet_unlock`||!e.ecdsaSession)throw Error(`Email OTP unlock did not return its ECDSA Wallet Session`);if(e.ecdsaSession.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){if(!t)throw Error(`Email OTP combined unlock did not return its exact Wallet Session`);return{kind:`credential_free_ecdsa_session_activation_authorization_v1`,activation:e.ecdsaSession,authorization:t}}return e.ecdsaSession}function vL(e){if(!e)throw Error(`Email OTP unlock did not return its prepared ECDSA Wallet Session`);return e}function yL(e,t,n){let r=e.signers[0];if(!r)throw Error(`Email OTP ECDSA custody continuity is empty`);if(r.walletKey.walletId!==t||r.walletKey.keyHandle!==n)throw Error(`Email OTP ECDSA custody continuity changed the requested wallet key`);for(let t of e.signers)if(t.walletKey.walletId!==r.walletKey.walletId||t.walletKey.keyHandle!==r.walletKey.keyHandle||t.walletKey.ecdsaThresholdKeyId!==r.walletKey.ecdsaThresholdKeyId||t.walletKey.signingRootId!==r.walletKey.signingRootId||t.walletKey.signingRootVersion!==r.walletKey.signingRootVersion||t.walletKey.relayerKeyId!==r.walletKey.relayerKeyId||!ti(t.walletKey.publicCapability,r.walletKey.publicCapability)||!xi(t.activationReceipt,r.activationReceipt)||!Ie(t.runtimePolicyScope,r.runtimePolicyScope))throw Error(`Email OTP ECDSA custody continuity conflicts across targets`);return r}function bL(e){let[t,...n]=e.signers;if(!t)throw Error(`Email OTP ECDSA custody continuity is empty`);return[t.chainTarget,...n.map(e=>e.chainTarget)]}async function xL(e){let t=e.restore.ecdsaCustody,n=yL(t.continuity,e.walletId,e.keyHandle);await e.restoreWalletCustodyEcdsaContinuity({authority:e.authority,chainTargets:bL(t.continuity),walletId:n.walletKey.walletId,keyHandle:n.walletKey.keyHandle,ecdsaThresholdKeyId:n.walletKey.ecdsaThresholdKeyId,signingRootId:n.walletKey.signingRootId,signingRootVersion:n.walletKey.signingRootVersion,relayerKeyId:n.walletKey.relayerKeyId,participantIds:n.walletKey.participantIds,publicCapability:n.walletKey.publicCapability,activationReceipt:n.activationReceipt,runtimePolicyScope:n.runtimePolicyScope,readyStateBlobB64u:t.readyStateBlobB64u,publicFacts:t.publicFacts})}function SL(e){let t=l(e);if(!t.ok)throw Error(`Failed to create Email OTP threshold session identity`);return t.value}function CL(e){let t=wt(e);if(!t.ok)throw Error(`Failed to create Email OTP Wallet Session mint identity`);return t.value}function wL(e){if(!e)throw Error(`Email OTP ECDSA bootstrap requires route auth`);return e}function TL(e){switch(e){case Wt:return`sign`;case Bt:return`export`;case Ht:throw Error(`Email OTP wallet unlock requires first-session activation`);case Kt:throw Error(`Email OTP relocation approval cannot create a signing session`);case Yt:throw Error(`Email OTP device linking requires linked-device activation`);case`registration`:throw Error(`Email OTP ECDSA registration requires wallet-registration prepare`)}throw Error(`Unsupported Email OTP non-unlock operation`)}function EL(e){switch(e.operation){case`sign`:return{keyHandle:e.keyHandle,authSubjectId:e.authSubjectId,operation:`sign`,chainTarget:e.chainTarget};case`export`:return{keyHandle:e.keyHandle,authSubjectId:e.authSubjectId,operation:`export`,chainTarget:e.chainTarget}}throw e.operation,Error(`Unsupported Email OTP non-unlock handle operation`)}function DL(e){if(e.emailOtpWorkerSessionHandle.action!==`threshold_ecdsa_bootstrap`)throw Error(`Email OTP ECDSA activation requires a threshold ECDSA worker handle`);let t=KI({thresholdSessionId:e.thresholdSessionId}),n=Ea({chainTarget:e.chainTarget,thresholdSessionId:t.thresholdSessionId,ttlMs:e.ttlMs,remainingUses:e.remainingUses,runtimePolicyScope:e.runtimePolicyScope});if(ul(e.emailOtpAuthContext)){let r={source:`email_otp`,relayerUrl:e.relayerUrl,sessionIdentity:t,sessionKind:`opaque`,sessionBudgetUses:e.remainingUses,runtimePolicy:{kind:`scoped_policy`,scope:e.runtimePolicyScope},emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,emailOtpAuthContext:e.emailOtpAuthContext,walletKey:e.existingKey.walletKey,lanePolicy:n,publicCapability:e.existingKey.publicCapability,existingRoleLocalMaterial:e.existingKey.persistedRoleLocalMaterial};return e.authorization.kind===`preauthorized_wallet_unlock`?gu({...r,preauthorizedSessionActivation:e.authorization.sessionActivation}):su({...r,walletSessionRouteAuth:e.authorization.routeAuth})}if(hl(e.emailOtpAuthContext)){if(e.authorization.kind===`preauthorized_wallet_unlock`)throw Error(`Email OTP operation step-up cannot adopt a reusable Wallet Session`);return ou({source:`email_otp`,relayerUrl:e.relayerUrl,sessionIdentity:t,sessionKind:`opaque`,sessionBudgetUses:e.remainingUses,runtimePolicy:{kind:`scoped_policy`,scope:e.runtimePolicyScope},emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,emailOtpAuthContext:e.emailOtpAuthContext,walletSessionRouteAuth:e.authorization.routeAuth,walletKey:e.existingKey.walletKey,lanePolicy:n,publicCapability:e.existingKey.publicCapability,existingRoleLocalMaterial:e.existingKey.persistedRoleLocalMaterial})}throw Error(`Email OTP ECDSA activation cannot use a consumed single-use context`)}function OL(e){if(e.emailOtpWorkerSessionHandle.action!==`threshold_ecdsa_bootstrap`)throw Error(`Email OTP ECDSA recovery requires a threshold ECDSA worker handle`);let t=Qt.thresholdEcdsaSession(e.thresholdSessionId);return vu({source:`email_otp`,relayerUrl:e.relayerUrl,sessionIdentity:{kind:`recovered_material_session`,thresholdSessionId:t,materialActivation:e.existingKey.persistedRoleLocalMaterial.materialActivation},sessionKind:`opaque`,sessionBudgetUses:e.remainingUses,runtimePolicy:{kind:`scoped_policy`,scope:e.runtimePolicyScope},emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,emailOtpAuthContext:e.emailOtpAuthContext,walletSessionRouteAuth:e.routeAuth,walletKey:e.existingKey.walletKey,lanePolicy:Fa({chainTarget:e.chainTarget,thresholdSessionId:t,ttlMs:e.ttlMs,remainingUses:e.remainingUses,runtimePolicyScope:e.runtimePolicyScope}),publicCapability:e.existingKey.publicCapability,existingRoleLocalMaterial:e.existingKey.persistedRoleLocalMaterial})}function kL(e){switch(e.kind){case`route_authorized`:return{sessionIdentity:e.sessionIdentity,authorization:{kind:`route_authorized`,routeAuth:e.routeAuth}};case`preauthorized_wallet_unlock`:{let t=e.request.session_policy,n=au(e.response)?e.response.activation.session:e.response.session;if(t.threshold_session_id!==n.threshold_session_id)throw Error(`Email OTP unlock returned a different prepared ECDSA session identity`);return{sessionIdentity:KI({thresholdSessionId:n.threshold_session_id}),authorization:{kind:`preauthorized_wallet_unlock`,sessionActivation:e.response}}}}}async function AL(e){let t=vf(e.emailOtpSessionHandle);if(t.action!==`threshold_ecdsa_bootstrap`)throw Error(`Email OTP wallet unlock returned an invalid ECDSA worker handle`);let n=kL(e.primarySession),r={args:e,sessionIdentity:n.sessionIdentity,authorization:n.authorization,emailOtpWorkerSessionHandle:t},i=e.publicationChainTargets[0];if(!i)throw Error(`Email OTP ECDSA activation requires a primary target`);let a=await jL(r,i),o=e.primarySession.kind===`preauthorized_wallet_unlock`?n.authorization:{kind:`route_authorized`,routeAuth:a.session.operationCredential},s={...r,args:{...e,primarySession:{kind:`route_authorized`,sessionIdentity:n.sessionIdentity,routeAuth:a.session.operationCredential}},authorization:o},c=[a,...await Promise.all(e.publicationChainTargets.slice(1).map(jL.bind(null,s)))];if(!a)throw Error(`Email OTP ECDSA activation did not return a primary warm session`);return c}async function jL(e,t){let n=FI({existingKey:e.args.primaryExistingKey,chainTarget:t});return await e.args.ports.provisionThresholdEcdsaSession(DL({existingKey:n,chainTarget:t,thresholdSessionId:e.sessionIdentity.thresholdSessionId,ttlMs:e.args.ttlMs,remainingUses:e.args.remainingUses,runtimePolicyScope:e.args.runtimePolicyScope,relayerUrl:e.args.relayerUrl,emailOtpAuthContext:e.args.emailOtpAuthContext,emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,authorization:e.authorization}))}async function ML(e){return await e.ports.provisionEmailOtpEcdsaExplicitExportSession(fu({relayerUrl:e.relayerUrl,existingRoleLocalMaterial:e.persistedMaterial,authorization:e.authorization}))}function NL(e){let t=Math.floor(Number(e)||0);if(!Number.isFinite(t)||t<=0)throw Error(`[SigningEngine][email-otp][ecdsa] signing remainingUses is required`);return t}function PL(e){let t=e.runtimePolicyScope;if(!t)throw Error(`Email OTP ECDSA signing refresh requires runtimePolicyScope`);return t}function FL(e){if(e.authority.factor.kind!==`email_otp`||!e.authLane)throw Error(`[SigningEngine][email-otp][ecdsa] committed lane requires Email OTP authority`);return{keyHandle:String(xa(e.lane.identity.signer.keyHandle)),participantIds:e.lane.identity.signer.key.participantIds.map(Number),emailHashHex:e.authority.verifier.emailHashHex,providerIdentity:{kind:`explicit_provider_user`,provider:e.authority.factor.provider,providerUserId:e.authority.factor.providerUserId}}}async function IL(e){let t=await e.resolveCurrentEcdsaCapabilityRuntime({walletId:V(e.committedLane.lane.identity.signer.walletId),chainTarget:e.chainTarget});if(t.kind!==`resolved`)throw Error(`[SigningEngine][email-otp][ecdsa] signing refresh runtime unavailable: ${t.reason}`);if(!g(t.runtime.materialActivation,e.committedLane.lane.materialActivation))throw Error(`[SigningEngine][email-otp][ecdsa] signing refresh runtime material activation mismatch`);return{...FL(e.committedLane),runtimePolicyScope:PL({runtimePolicyScope:t.runtime.runtimePolicyScope})}}async function LL(e,t){let n=Wt,r=NL(e.remainingUses),i=e.committedLane,a=await IL({committedLane:i,chainTarget:e.chainTarget,resolveCurrentEcdsaCapabilityRuntime:t.resolveCurrentEcdsaCapabilityRuntime}),o=Zo({authLane:Uo(i.authLane),operation:n});return await t.loginWithEcdsaCapabilityInternal({walletSession:e.walletSession,authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:String((await U({authority:i.authority})).walletAuthMethodId)},chainTarget:e.chainTarget,emailOtpAuthPolicy:`session`,emailOtpAuthReason:`sign`,challengeId:e.challengeId,otpCode:e.otpCode,operation:n,keyHandle:a.keyHandle,participantIds:a.participantIds,routePlan:o,emailHashHex:a.emailHashHex,providerIdentity:a.providerIdentity,ecdsaBootstrapAuthorization:{kind:`route_plan_auth`},remainingUses:r,runtimePolicyScope:a.runtimePolicyScope,ed25519YaoRecovery:{kind:`not_requested`}})}async function RL(e,t){let n=e.operation??e.routePlan.operation;cL({operation:n,routePlan:e.routePlan});let r=ZI(),i=e.chainTarget,a=e.emailOtpAuthPolicy||t.configs.signing.emailOtp.authPolicy,o=e.emailOtpAuthReason||`login`,s=o===`sign`,c=s&&a===`per_operation`?`single_use`:`session`,l=c===`session`?`session`:a,u=String(e.relayUrl||t.requireRelayUrl()).trim(),d=String(e.groupId||t.requireSigningSessionSealGroupId()).trim(),f=e.remainingUses,p=t.configs.signing.sessionDefaults?.remainingUses,m=Math.min(Math.max(1,Math.floor(Number(f??p??xe)||1)),xe),h=Math.max(1,Math.floor(Number(f)||1)),g=be({requestedRemainingUses:m})||(()=>{throw Error(`[SigningEngine][email-otp] unlock session uses are required`)})(),_=s?h:g,v=t.getSignerWorkerContext(),y=e.routePlan,b=e.ecdsaBootstrapAuthorization.kind===`route_plan_auth`?Yo(y):e.ecdsaBootstrapAuthorization.routeAuth,x=b?b.operationCredential:void 0,S=e.runtimePolicyScope;if(!v)throw Error(`Email OTP login requires the dedicated emailOtp worker`);let C=tL({identity:e.providerIdentity}),w=await iL({walletId:e.walletSession.walletId,authoritySelector:e.authoritySelector,emailHashHex:e.emailHashHex,provider:C.provider,providerUserId:C.providerUserId,authorityPorts:t}),T=c===`single_use`?w.kind===`selected_v2`?sl({policy:l,authority:w.authority,retention:`single_use`}):yl({policy:l,walletId:V(e.walletSession.walletId),emailHashHex:e.emailHashHex,retention:`single_use`,provider:C.provider,providerUserId:C.providerUserId}):w.kind===`selected_v2`?sl({policy:l,authority:w.authority,retention:`session`,reason:o}):yl({policy:l,walletId:V(e.walletSession.walletId),emailHashHex:e.emailHashHex,retention:`session`,reason:o,provider:C.provider,providerUserId:C.providerUserId}),E=aL({source:w,runtimePolicyScope:S,authorityRef:await U({authority:T.authority})}),D=NI({configs:t.configs,chainTarget:i,emailOtpAuthContext:T,...e.publicationChainTargets?{additionalChainTargets:e.publicationChainTargets}:{}}),O=t.publicationPorts,k=n===Ht,A=String(e.keyHandle||``).trim(),j=await LI({walletId:V(e.walletSession.walletId),chainTarget:i,scope:E,keyHandle:e.keyHandle,listActiveEcdsaCapabilityManifestsForWallet:O.listActiveEcdsaCapabilityManifestsForWallet});if(!j&&!k)throw Error(`device_link_required: local threshold ECDSA material is unavailable for ${i.kind}:${i.chainId}`);let M=String(j?.keyHandle||A).trim();if(!M)throw Error(`Email OTP ECDSA wallet unlock requires an exact key handle`);let ee=j?.runtimePolicyScope||S;if(!ee)throw Error(`Email OTP ECDSA wallet unlock requires runtime policy scope`);let te=e.ed25519YaoRecovery.kind===`requested`?await t.loadWalletCustodyEd25519Material({nearAccountId:e.ed25519YaoRecovery.nearAccountId,signerSlot:e.ed25519YaoRecovery.signerSlot}):null,ne=k?Ce({ttlMs:e.ttlMs??Se.ttlMs,remainingUses:_}):null,re=ne?SL(Il(`threshold-ecdsa-login`)):null,N=ne&&re&&j?uu({publicCapability:j.publicCapability,thresholdSessionId:re,walletSessionMintId:CL(Il(`wallet-session-mint`)),ttlMs:ne.ttlMs,remainingUses:ne.remainingUses,runtimePolicyScope:ee}):null,ie=ne&&re?gL({keyHandle:M,thresholdSessionId:re,walletSessionMintId:CL(Il(`wallet-session-mint`)),ttlMs:ne.ttlMs,remainingUses:ne.remainingUses,runtimePolicyScope:ee}):null,ae=YI(),oe=n===`export_key`?oL(e):null,se=oe?{walletSession:e.walletSession,authoritySelector:e.authoritySelector,relayUrl:u,groupId:d,verification:sL(oe.explicitExportAuthorization),routePlan:y,workerCtx:v,runtimePolicyScope:ee,...e.onProgress?{onProgress:e.onProgress}:{}}:{walletSession:e.walletSession,authoritySelector:e.authoritySelector,relayUrl:u,groupId:d,verification:{kind:`otp`,...e.challengeId?{challengeId:e.challengeId}:{},otpCode:e.otpCode},routePlan:y,workerCtx:v,runtimePolicyScope:ee,...e.onProgress?{onProgress:e.onProgress}:{}},ce=e.ed25519YaoRecovery.kind===`not_requested`?await gs({...se,...ie?{ecdsaSessionHandleBinding:{keyHandle:M,authSubjectId:C.providerUserId,operation:`wallet_unlock`,chainTarget:i},ecdsaSessionPolicy:N?hL({request:N,keyHandle:M}):ie}:{ecdsaSessionHandleBinding:EL({keyHandle:M,authSubjectId:C.providerUserId,operation:TL(y.operation),chainTarget:i})}}):await bs({...se,ecdsaSessionHandleBinding:{keyHandle:M,authSubjectId:C.providerUserId,operation:`wallet_unlock`,chainTarget:i},providerSubject:e.ed25519YaoRecovery.providerSubject,signerSlot:e.ed25519YaoRecovery.signerSlot,nearAccountId:e.ed25519YaoRecovery.nearAccountId,expectedOperationalPublicKey:e.ed25519YaoRecovery.expectedOperationalPublicKey,expectedThresholdSessionId:e.ed25519YaoRecovery.expectedThresholdSessionId,walletCustodyEd25519Material:te||{kind:`absent`},remainingUses:_,ecdsaSessionPolicy:N?hL({request:N,keyHandle:M}):mL(ie)}),le=ce.kind===`wallet_unlock_capabilities`?ce.ecdsa:ce,ue=ce.kind===`wallet_unlock_capabilities`?ce.ed25519Yao:null,de=ce.kind===`wallet_unlock_capabilities`?ce.walletSessionAuthorization:void 0;try{if(le.operation===`wallet_unlock`&&!j){let n=await U({authority:T.authority});await xL({restore:le,walletId:String(e.walletSession.walletId),keyHandle:M,authority:n,restoreWalletCustodyEcdsaContinuity:t.restoreWalletCustodyEcdsaContinuity})}if(!j&&(j=await LI({walletId:V(e.walletSession.walletId),chainTarget:i,scope:E,keyHandle:M,listActiveEcdsaCapabilityManifestsForWallet:O.listActiveEcdsaCapabilityManifestsForWallet}),!j))throw Error(`Email OTP ECDSA custody restore did not publish the canonical key`);let a=N||(ie?uu({publicCapability:j.publicCapability,thresholdSessionId:ie.session_policy.threshold_session_id,walletSessionMintId:ie.session_policy.wallet_session_mint_id,ttlMs:ie.session_policy.ttl_ms,remainingUses:ie.session_policy.remaining_uses,runtimePolicyScope:ee}):null),o=n===`export_key`?uL(T):null,s=n===`export_key`?nf(le.emailOtpSessionHandle):null;s&&o&&lL({handle:s,existingKey:j,chainTarget:i,emailOtpAuthContext:o}),QI(r,`emailOtpProofVerificationMs`,ae);let c=a?_L(le,de):null,l=c?dL({ttlMs:e.ttlMs,remainingUses:_}):pL({ed25519YaoResult:ue,requestedTtlMs:e.ttlMs,requestedRemainingUses:_});if(ae=YI(),n===`export_key`){if(!s||!o)throw Error(`Email OTP ECDSA export worker handle is unavailable`);let n=oL(e),i=await ML({relayerUrl:u,persistedMaterial:n.persistedExportMaterial,authorization:n.explicitExportAuthorization,ports:t});return QI(r,`ecdsaMaterialRestoreMs`,ae),{kind:`transient_export`,value:{bootstrap:i}}}let f=await AL({primaryExistingKey:j,publicationChainTargets:D,runtimePolicyScope:ee,relayerUrl:u,ttlMs:l.ttlMs,remainingUses:l.remainingUses,emailOtpAuthContext:T,emailOtpSessionHandle:le.emailOtpSessionHandle,primarySession:a?{kind:`preauthorized_wallet_unlock`,request:a,response:vL(c)}:{kind:`route_authorized`,sessionIdentity:KI({thresholdSessionId:Il(`threshold-ecdsa-login`)}),routeAuth:wL(x)},ports:t});QI(r,`ecdsaMaterialRestoreMs`,ae);let{bootstrap:p,authorization:m,authorizations:h,timings:g}=await VI({walletId:V(e.walletSession.walletId),publicationChainTargets:D,bootstraps:f,runtimePolicyScope:ee,authority:j.persistedRoleLocalMaterial.authority,emailOtpAuthContext:T,relayerUrl:u,groupId:d},O);return ce.kind===`wallet_unlock_capabilities`&&await XI({workerContext:v,unlock:ce,authorization:m,walletAuthMethodId:String(T.authority.bindingId)}),$I(r,g),{kind:`published_signing_session`,value:{recovery:ce.recovery,bootstrap:p,authorization:m,authorizations:h,emailOtpSessionHandle:le.emailOtpSessionHandle,ed25519YaoRecovery:qI(ue),timings:r}}}catch(e){try{await JI({workerResult:ue,workerContext:v})}catch(t){throw AggregateError([e,t],`Email OTP unlock failed and Ed25519 material disposal failed`)}throw e}finally{ce.kind===`wallet_unlock_capabilities`&&ce.ed25519ExportRootCustody.factorSecret32.fill(0)}}async function zL(e,t){if((e.operation??e.routePlan.operation)===`export_key`)throw Error(`Email OTP ECDSA export must use transient export preparation`);let n=await RL(e,t);if(n.kind!==`published_signing_session`)throw Error(`Email OTP ECDSA login did not publish a signing session`);return n.value}async function BL(e,t){let n=await RL(e,t);if(n.kind!==`transient_export`)throw Error(`Email OTP ECDSA export preparation published a signing session`);return n.value}var VL=class extends Error{code=`material_activation_superseded`;constructor(e){super(`Email OTP sealed refresh material activation was superseded ${e.replace(`_`,` `)}`),this.phase=e,this.name=`EmailOtpEcdsaSealedRestoreSupersededError`}};function HL(e){return sl({policy:`session`,authority:e,retention:`session`,reason:`login`})}function UL(e){if(e.length!==2||e[0]!==1||e[1]!==2)throw Error(`Email OTP sealed refresh requires participantIds [1, 2]`);return[1,2]}async function WL(e){if((await U({authority:e.emailOtpAuthority})).walletId!==e.authority.walletId)throw Error(`Email OTP sealed refresh route authority wallet mismatch`);let t=e.publicCapability,n=t.public_identity,r=ji({walletId:V(e.walletId),chainTarget:e.chainTarget,keyHandle:e.keyHandle,ecdsaThresholdKeyId:Qr(e.ecdsaThresholdKeyId),signingRootId:li(e.signingRootId),signingRootVersion:$r(e.signingRootVersion),applicationBindingDigestB64u:t.context.application_binding_digest_b64u,participantIds:UL(e.participantIds),clientParticipantId:1,relayerParticipantId:2,contextBinding32B64u:n.context_binding_b64u,derivationClientSharePublicKey33B64u:n.derivation_client_share_public_key33_b64u,relayerPublicKey33B64u:n.server_public_key33_b64u,groupPublicKey33B64u:n.threshold_public_key33_b64u,ethereumAddress:e.ethereumAddress,publicCapability:t}),i=Ma({walletId:r.walletId,keyHandle:r.keyHandle,chainTarget:r.chainTarget,ecdsaThresholdKeyId:r.ecdsaThresholdKeyId,signingRootId:r.signingRootId,signingRootVersion:r.signingRootVersion,participantIds:r.participantIds,thresholdOwnerAddress:r.ethereumAddress,thresholdEcdsaPublicKeyB64u:r.groupPublicKey33B64u});return{keyHandle:String(i.keyHandle),publicCapability:t,walletKey:i,runtimePolicyScope:e.runtimePolicyScope,persistedRoleLocalMaterial:Rd({authority:e.authority,materialActivation:e.roleLocalMaterialRef.materialActivation,publicFacts:r})}}function GL(e){let t=String(e.keyVersion||``).trim(),n=String(e.groupId||``).trim();if(!t||!n)throw Error(`Email OTP sealed refresh is missing normalized seal transport metadata`);return{signingSessionSealKeyVersion:t,signingSessionSealGroupId:n}}function KL(e){let{sealedRecord:t}=e,n=GL(t);if(!t.thresholdSessionId||!t.relayerUrl||!t.keyHandle||!t.relayerKeyId||!t.participantIds.length)throw Error(`Email OTP sealed refresh is missing durable ECDSA restore metadata`);return{kind:`sealed_record_restore`,sealedRecord:t,emailOtpAuthContext:HL(t.emailOtpAuthority),authorization:e.authorization,relayerUrl:t.relayerUrl,chainTarget:t.chainTarget,keyHandle:t.keyHandle,...n,...t.runtimePolicyScope?{runtimePolicyScope:t.runtimePolicyScope}:{}}}async function qL(e,t){let n=await e(String(t));if(n.kind!==`resolved`||n.selection.lockState!==`unlocked`||n.selection.walletId!==t||n.selection.walletAuthMethodId!==n.authMethod.walletAuthMethodId||n.authMethod.kind!==`email_otp`||n.authMethod.status!==`active`||n.authMethod.walletId!==t||n.authMethod.walletAuthorityId!==n.authority.authorityId||n.authority.state!==`active`||n.authority.walletId!==t)throw Error(`Email OTP sealed refresh selected authority is invalid`);return{kind:`resolved`,selection:n.selection,authMethod:n.authMethod,authority:n.authority,signerMaterials:n.signerMaterials,exportRoot:n.exportRoot}}function JL(e){if(e.authBinding.kind!==`email_otp`)throw Error(`Email OTP sealed refresh runtime is not Email OTP bound`);return e.authBinding.emailOtpAuthority}function YL(e){if(e.authorizationRead.kind!==`found`)throw Error(`Email OTP sealed refresh requires active Wallet Session authorization: ${e.authorizationRead.kind}`);let{record:t,operationCredential:n}=e.authorizationRead;if(e.runtime.kind!==`exact_ecdsa_sealed_runtime_v1`)throw Error(`Email OTP sealed refresh ECDSA runtime is unavailable`);if(e.sealedRecord.authMethod!==`email_otp`||t.walletId!==V(e.sealedRecord.walletId)||t.authorityId!==e.selected.authority.authorityId||t.authMethodId!==e.selected.authMethod.walletAuthMethodId||t.authorityDigestB64u!==e.selected.authority.authorityDigestB64u||t.authorityRevocationEpoch!==e.selected.authority.revocationEpoch||t.expiresAtMs<=e.nowMs||n.walletSessionId.trim().length===0||n.token.trim().length===0||e.runtime.walletId!==t.walletId||!wn(e.runtime.chainTarget,e.sealedRecord.chainTarget)||e.runtime.sealedRecord.thresholdSessionId!==e.sealedRecord.thresholdSessionId||e.runtime.sealedRecord.authMethod!==e.selected.authMethod.kind||e.runtime.authBinding.kind!==`email_otp`||e.runtime.authBinding.emailOtpAuthority.bindingId!==e.selected.authMethod.walletAuthMethodId||e.runtime.authBinding.emailOtpAuthority.walletId!==t.walletId)throw Error(`Email OTP sealed refresh Wallet Session authorization mismatch`);return Md({capability:e.capability,selected:e.selected,session:t,operationCredential:n,runtime:e.runtime,nowMs:e.nowMs})}function XL(e){return async t=>await ZL({...e,...t})}async function ZL(e){let t=e.sealedRecord;if(t.authMethod!==`email_otp`||t.curve!==`ecdsa`)return null;let n=t.roleLocalMaterialRef.materialActivation;return await e.withThresholdEcdsaSigningQueue({queueKey:Yd({materialActivation:n}),walletId:V(t.walletId),enabled:!0,task:async()=>await QL(e)})}async function QL(e){let t=e.sealedRecord,n=t.roleLocalMaterialRef.materialActivation,r=V(t.walletId),i=await e.resolveCurrentEcdsaCapabilityRuntime({walletId:r,chainTarget:t.chainTarget});if(i.kind!==`resolved`||!g(i.runtime.materialActivation,n))throw new VL(`before_rehydrate`);let a=await qL(e.resolveSelectedWalletAuthority,r),o=await e.readExactWalletSessionAuthorization({walletId:r,authorityId:a.authority.authorityId,authMethodId:a.authMethod.walletAuthMethodId}),s=await WL(t),c=await Sd({authority:JL(i.runtime),manifest:i.manifest,material:s.persistedRoleLocalMaterial}),l=KL({sealedRecord:t,authorization:YL({sealedRecord:t,authorizationRead:o,selected:a,runtime:i.runtime,capability:c,nowMs:Date.now()})});if(l.authorization.runtime.kind!==`exact_ecdsa_sealed_runtime_v1`)throw Error(`Email OTP sealed refresh requires a sealed ECDSA runtime`);let u=l.authorization.operationCredential;if(_l(l.emailOtpAuthContext)!==`session`)return null;let d=e.getSignerWorkerContext();if(!d)throw Error(`Email OTP sealed refresh requires the dedicated emailOtp worker`);if(t.expiresAtMs<=Date.now())throw Error(`Email OTP sealed refresh expired sealed record`);if(t.remainingUses<=0)throw Error(`Email OTP sealed refresh exhausted sealed record`);let f=n,p=l.authorization.runtime.sealedRecord.thresholdSessionId,m=BI(t.routerAbEcdsaDerivationNormalSigning),h=await YP({workerCtx:d,target:{kind:`ecdsa`,thresholdSessionId:p},authorizationThresholdSessionId:m,sealedSecretB64u:t.sealedSecretB64u,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs,transport:{relayerUrl:l.relayerUrl,operationCredential:u,signingSessionSealKeyVersion:Bi(l.signingSessionSealKeyVersion),groupId:l.signingSessionSealGroupId},restore:{thresholdSessionId:p,walletId:t.walletId,keyHandle:l.keyHandle,chainTarget:l.chainTarget,authSubjectId:ll(l.emailOtpAuthContext)}});if(!h.ok)throw Error(h.message||h.code||`Email OTP sealed refresh failed`);if(!l.runtimePolicyScope)throw Error(`Email OTP sealed refresh requires runtime policy scope`);let _=vf(h.emailOtpSessionHandle),v=await e.provisionThresholdEcdsaSession(OL({existingKey:s,chainTarget:l.chainTarget,thresholdSessionId:p,ttlMs:Math.max(1,h.expiresAtMs-Date.now()),remainingUses:h.remainingUses,runtimePolicyScope:l.runtimePolicyScope,relayerUrl:l.relayerUrl,emailOtpAuthContext:l.emailOtpAuthContext,emailOtpWorkerSessionHandle:_,routeAuth:u})),y=await e.resolveCurrentEcdsaCapabilityRuntime({walletId:V(t.walletId),chainTarget:l.chainTarget});if(y.kind!==`resolved`||!g(y.runtime.materialActivation,f))throw new VL(`before_commit`);let b=await e.commitEvmFamilyThresholdEcdsaSessions({walletId:r,chainTarget:l.chainTarget,bootstrap:v,source:`email_otp`,authority:s.persistedRoleLocalMaterial.authority,emailOtpAuthContext:l.emailOtpAuthContext});return{authorization:Md({capability:c,selected:a,session:b.bootstrap.session.walletSession,operationCredential:b.bootstrap.session.operationCredential,runtime:y.runtime,nowMs:Date.now()}),remainingUses:b.bootstrap.session.remainingUses,expiresAtMs:b.bootstrap.session.expiresAtMs}}var $L=class{constructor(e){this.ports=e}async loginWithEcdsaCapabilityForSigning(e){return await LL(e,{resolveCurrentEcdsaCapabilityRuntime:this.ports.resolveCurrentEcdsaCapabilityRuntime,loginWithEcdsaCapabilityInternal:e=>this.loginWithEcdsaCapabilityInternal(e)})}async loginWithEcdsaCapabilityInternal(e){return await zL(e,{configs:this.ports.configs,getSignerWorkerContext:this.ports.getSignerWorkerContext,loadWalletCustodyEd25519Material:this.ports.loadWalletCustodyEd25519Material,restoreWalletCustodyEcdsaContinuity:this.ports.restoreWalletCustodyEcdsaContinuity,provisionThresholdEcdsaSession:this.ports.provisionThresholdEcdsaSession,provisionEmailOtpEcdsaExplicitExportSession:this.ports.provisionEmailOtpEcdsaExplicitExportSession,requireRelayUrl:()=>this.ports.runtimeConfig.requireRelayUrl(),requireSigningSessionSealGroupId:()=>this.ports.runtimeConfig.requireSigningSessionSealGroupId(),ownerLaneScopeStores:this.ports.ownerLaneScopeStores,resolveSelectedWalletAuthority:this.ports.resolveSelectedWalletAuthority,publicationPorts:this.ports.publicationPorts()})}async prepareEcdsaExportCapability(e){return await BL(e,{configs:this.ports.configs,getSignerWorkerContext:this.ports.getSignerWorkerContext,loadWalletCustodyEd25519Material:this.ports.loadWalletCustodyEd25519Material,restoreWalletCustodyEcdsaContinuity:this.ports.restoreWalletCustodyEcdsaContinuity,provisionThresholdEcdsaSession:this.ports.provisionThresholdEcdsaSession,provisionEmailOtpEcdsaExplicitExportSession:this.ports.provisionEmailOtpEcdsaExplicitExportSession,requireRelayUrl:()=>this.ports.runtimeConfig.requireRelayUrl(),requireSigningSessionSealGroupId:()=>this.ports.runtimeConfig.requireSigningSessionSealGroupId(),ownerLaneScopeStores:this.ports.ownerLaneScopeStores,resolveSelectedWalletAuthority:this.ports.resolveSelectedWalletAuthority,publicationPorts:this.ports.publicationPorts()})}};async function eR(e,t){let n=await e.resolveSelectedWalletAuthority(String(t));if(n.kind===`missing_selection`)return{kind:`canonical`};if(n.kind!==`resolved`)throw Error(`Email OTP challenge authority selection is unavailable: ${n.kind}`);if(n.authMethod.kind!==`email_otp`)return{kind:`canonical`};if(n.authMethod.status!==`active`||n.authority.state!==`active`||String(n.authMethod.walletId)!==String(t)||String(n.authority.walletId)!==String(t)||String(n.authMethod.walletAuthorityId)!==String(n.authority.authorityId))throw Error(`Email OTP challenge selected authority is not active`);return{kind:`exact`,walletAuthMethodId:String(n.authMethod.walletAuthMethodId)}}function tR(e){return e===`near`?`ed25519`:`ecdsa`}function nR(e){let t=e.authLane;return t?.kind!==`signing_session`&&ws({kind:`auth_lane_missing`,source:`provided_route_auth`,expectedCurve:tR(e.chain)}),t}async function rR(e,t){let n=t.kind===`wallet_session`?t.walletId:t.walletSession.walletId,r=e.requireRelayUrl(),i=e.getSignerWorkerContext();if(!i)throw Error(`Email OTP signing requires the dedicated emailOtp worker`);let a=await eR(e,n),o=await i.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpChallenge`,timeoutMs:3e4,payload:{relayUrl:r,walletId:String(n),...a.kind===`exact`?{walletAuthMethodId:a.walletAuthMethodId}:{},routePlan:t.routePlan,otpChannel:zt,...t.operationFingerprintDigest?{operationFingerprintDigest:t.operationFingerprintDigest}:{}}}}),s=String(o.challengeId||``).trim();if(!s)throw Error(`Email OTP signing challenge response did not include challengeId`);let c=o.delivery;return{challengeId:s,emailHint:c.emailHint,delivery:c}}async function iR(e,t){let n=aR(e,t);return t.kind===`near_account_challenge`?await rR(e,{kind:`near_account`,walletSession:t.walletSession,routePlan:n,...t.operationFingerprintDigest?{operationFingerprintDigest:t.operationFingerprintDigest}:{}}):await rR(e,{kind:`wallet_session`,walletId:t.walletSession.walletId,routePlan:n,...t.operationFingerprintDigest?{operationFingerprintDigest:t.operationFingerprintDigest}:{}})}function aR(e,t){switch(t.kind){case`wallet_operation_challenge`:return Ss({routeFamily:`operation_step_up`,operation:Wt,operationCredential:t.operationCredential});case`wallet_session_challenge`:case`near_account_challenge`:return e.buildSigningSessionRoutePlan({authLane:nR({authLane:t.authLane,chain:t.chain}),operation:Wt})}}async function oR(e,t){let n=sR(e,t);return t.kind===`near_account_challenge`?await rR(e,{kind:`near_account`,walletSession:t.walletSession,routePlan:n}):t.kind===`wallet_export_challenge`?await rR(e,{kind:`wallet_session`,walletId:t.walletId,routePlan:n}):await rR(e,{kind:`wallet_session`,walletId:t.walletSession.walletId,routePlan:n})}function sR(e,t){switch(t.kind){case`wallet_login_challenge`:return Ss({routeFamily:`login`,operation:Bt});case`wallet_session_challenge`:case`near_account_challenge`:return e.buildSigningSessionRoutePlan({authLane:nR({authLane:t.authLane,chain:t.chain}),operation:Bt});case`wallet_export_challenge`:return Ss({routeFamily:`login`,operation:Bt})}}function cR(e){return Ss({routeFamily:`login`,operation:Bt})}function lR(e){switch(e.material.kind){case`active_capability`:return e.material;case`sealed_custody`:return{kind:`sealed_custody`,materialActivation:e.material.materialActivation,walletCustodyEd25519Material:e.material.walletCustodyEd25519Material,bootstrap:e.material.bootstrap};case`sealed_export_root`:return{kind:`sealed_export_root`,materialActivation:e.material.materialActivation,capability:e.material.capability,exportRootEnvelope:e.material.exportRootEnvelope};default:throw e.material,Error(`Email OTP Ed25519 export material is invalid`)}}async function uR(e,t){let n=e.getSignerWorkerContext();if(!n)throw Error(`Email OTP Ed25519 Yao export requires the dedicated emailOtp worker`);let r=e.requireRelayUrl(),i=t.exportContext.lane.signer.account.wallet.walletId,a=await n.requestWorkerOperation({kind:`emailOtp`,request:{type:`exportEmailOtpEd25519YaoSeed`,timeoutMs:6e4,payload:{relayUrl:r,challengeId:t.challengeId,otpCode:t.otpCode,lane:{walletId:String(i),providerSubjectId:t.exportContext.lane.auth.providerSubjectId,walletAuthMethodId:String(t.exportContext.authorization.record.authMethodId),nearAccountId:String(t.exportContext.lane.signer.account.nearAccountId),nearEd25519SigningKeyId:String(t.exportContext.lane.signer.nearEd25519SigningKeyId),signerSlot:t.exportContext.lane.signer.signerSlot},material:lR(t.exportContext)}}});switch(a.kind){case`exported`:return a;case`exported_and_rehydrated`:if(t.exportContext.material.kind!==`sealed_custody`)throw await Fy({workerContext:n,activeClientHandle:a.activeClientHandle}).catch(()=>void 0),Error(`Email OTP Ed25519 export returned unexpected recovered material`);if(t.exportContext.authorization.status.status===`exhausted`)return await Fy({workerContext:n,activeClientHandle:a.activeClientHandle}),a;try{await t.exportContext.material.activateRecoveredCapability({activation:{activeClientHandle:a.activeClientHandle,metadata:a.metadata,bootstrap:a.bootstrap},operationCredential:t.exportContext.authorization.operationCredential})}catch(e){throw await Fy({workerContext:n,activeClientHandle:a.activeClientHandle}).catch(()=>void 0),e}return a;default:throw Error(`Email OTP Ed25519 export returned an invalid result`)}}async function dR(e,t){let n=cR(t.explicitExportAuthorization);return await fR({walletSession:t.walletSession,authority:await U({authority:t.authority}),chainTarget:t.chainTarget,challengeId:t.challengeId,otpCode:t.otpCode,routePlan:n,keyHandle:String(t.publicFacts.keyHandle),participantIds:t.publicFacts.participantIds.map(Number),emailHashHex:t.authority.verifier.emailHashHex,provider:t.authority.factor.provider,providerUserId:t.authority.factor.providerUserId,runtimePolicyScope:t.runtimePolicyScope,relayUrl:e.requireRelayUrl(),getSignerWorkerContext:e.getSignerWorkerContext,prepareEcdsaExportCapability:t.prepareEcdsaExportCapability,persistedMaterial:t.persistedMaterial,explicitExportAuthorization:t.explicitExportAuthorization})}async function fR(e){let t=await e.prepareEcdsaExportCapability({walletSession:e.walletSession,authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:String(e.authority.walletAuthMethodId)},chainTarget:e.chainTarget,relayUrl:e.relayUrl,emailOtpAuthPolicy:`per_operation`,emailOtpAuthReason:`sign`,challengeId:e.challengeId,otpCode:e.otpCode,operation:Bt,routePlan:e.routePlan,ecdsaBootstrapAuthorization:{kind:`route_plan_auth`},keyHandle:e.keyHandle,participantIds:e.participantIds,remainingUses:1,emailHashHex:e.emailHashHex,providerIdentity:{kind:`explicit_provider_user`,provider:e.provider,providerUserId:e.providerUserId},runtimePolicyScope:e.runtimePolicyScope,ed25519YaoRecovery:{kind:`not_requested`},persistedExportMaterial:e.persistedMaterial,explicitExportAuthorization:e.explicitExportAuthorization}),n=e.getSignerWorkerContext();if(!n)throw Error(`Email OTP ECDSA export requires the dedicated signer worker`);return await hu({getSignerWorkerContext:()=>n},{walletSessionUserId:e.walletSession.walletSessionUserId,exportProvision:t.bootstrap,factorAuthorization:{kind:`email_otp_verified`}})}var pR=class{constructor(e){this.ports=e}async requestTransactionSigningChallenge(e){return await iR(this.workerPorts(),e)}async requestExportChallenge(e){return await oR(this.workerPorts(),e)}async exportEcdsaKeyWithDurableAuthorization(e){return await dR({getSignerWorkerContext:this.ports.getSignerWorkerContext,requireRelayUrl:this.ports.requireRelayUrl},{walletSession:e.walletSession,chainTarget:e.chainTarget,challengeId:e.challengeId,otpCode:e.otpCode,publicFacts:e.publicFacts,runtimePolicyScope:e.runtimePolicyScope,authority:e.authority,persistedMaterial:e.persistedMaterial,explicitExportAuthorization:e.explicitExportAuthorization,prepareEcdsaExportCapability:this.ports.prepareEcdsaExportCapability})}async exportEd25519YaoSeedWithFreshEmailOtpLane(e){return await uR({getSignerWorkerContext:this.ports.getSignerWorkerContext,requireRelayUrl:this.ports.requireRelayUrl},e)}workerPorts(){return{getSignerWorkerContext:this.ports.getSignerWorkerContext,requireRelayUrl:this.ports.requireRelayUrl,requireSigningSessionSealGroupId:this.ports.requireSigningSessionSealGroupId,resolveSelectedWalletAuthority:this.ports.resolveSelectedWalletAuthority,buildSigningSessionRoutePlan:Zo}}},mR=class{constructor(e){this.ports=e}requireRelayUrl(){let e=String(this.ports.configs.network.relayer?.url||``).trim();if(!e)throw Error(`Missing relayer url (configs.network.relayer.url)`);return e}requireSigningSessionSealGroupId(){return Ze}requireRpId(e){let t=String(this.ports.getRpId()||``).trim();if(!t)throw Error(`${e} requires an RP ID for ECDSA bootstrap`);return t}},hR=class{constructor(e){this.ports=e}async registerSigningSession(e){let t=ns(e);if(!t)throw Error(`[SigningSessionSealedStore] invalid sealed session record write input`);await this.ports.writeExactSealedSession(t),this.ports.clearEcdsaRestoreCaches()}ecdsaPublicationPorts(){return{configs:this.ports.configs,getSignerWorkerContext:this.ports.getSignerWorkerContext,commitEvmFamilyThresholdEcdsaSessions:this.ports.commitEvmFamilyThresholdEcdsaSessions,registerSigningSession:e=>this.registerSigningSession(e),readExactSealedSession:this.ports.readExactSealedSession,listActiveEcdsaCapabilityManifestsForWallet:this.ports.listActiveEcdsaCapabilityManifestsForWallet}}async persistEcdsaSessionForRefresh(e){await WI({walletId:e.walletId,chainTarget:e.chainTarget,bootstrap:e.bootstrap,runtimePolicyScope:e.runtimePolicyScope,emailOtpAuthContext:e.emailOtpAuthContext,relayerUrl:this.ports.configs.network.relayer?.url||``,groupId:Ze},this.ecdsaPublicationPorts())}},gR=class{constructor(e){this.ports=e}sealedRecordFilter(e){return{authMethod:`email_otp`,curve:`ecdsa`,chainTarget:e.chainTarget}}async recordSessionUseConsumed(e,t){await this.recordSessionPolicyResult({purpose:e,result:t})}async recordSessionMaterialRestored(e,t){await this.recordSessionPolicyResult({purpose:e,result:t})}async recordSessionPolicyResult(e){let t=String(e.purpose.thresholdSessionId||``).trim();if(t){if(!e.result.ok){this.ports.clearEcdsaRestoreCaches();return}await this.ports.updateExactSealedSessionPolicy({thresholdSessionId:t,filter:this.sealedRecordFilter(e.purpose),expiresAtMs:e.result.expiresAtMs,remainingUses:e.result.remainingUses,updatedAtMs:Date.now()}).catch(()=>void 0),this.ports.clearEcdsaRestoreCaches()}}};const _R={listed:0,discovered:0,truncated:0},vR={kind:`completed`,attempted:0,restored:0,deferred:0};var yR=class{restoreCache=nM();restoreAttempts=rM();requestedChainTarget=null;constructor(e){this.ports=e}clearCache(){this.restoreCache.clear(),this.restoreAttempts.clear()}async tryRestoreEcdsaWarmSessionStatusFromSealedRecord(e){if(this.ports.sessionPersistenceMode!==`sealed_refresh_v1`)return null;let t=String(e.thresholdSessionId||``).trim();if(!t)return null;this.requestedChainTarget=e.chainTarget;let n=t,r=await this.readEcdsaSealedRecord(t);if(!r)return null;if(r.remainingUses<=0||Date.now()>=r.expiresAtMs)return console.debug(`[EmailOtpSession] sealed refresh restore deferred by durable policy hint`,{thresholdSessionId:n,remainingUses:r.remainingUses,expiresAtMs:r.expiresAtMs}),null;if(r.authMethod!==`email_otp`||r.thresholdSessionId!==n)return console.warn(`[EmailOtpSession] sealed refresh restore deferred by store metadata mismatch`,{thresholdSessionId:n,authMethod:r.authMethod,ecdsaThresholdSessionId:r.thresholdSessionId}),null;let i=await this.ports.acquireSigningSessionRestoreLease({thresholdSessionId:n,authMethod:`email_otp`,curve:`ecdsa`,chainTarget:r.chainTarget}).catch(()=>null);if(!i){let e=`lease-unavailable:${n}`;return this.ports.shouldLogDiagnostic(e)&&console.debug(`[EmailOtpSession] sealed refresh restore deferred; lease unavailable`,{thresholdSessionId:n}),null}try{console.debug(`[EmailOtpSession] sealed refresh restore started`,{thresholdSessionId:n});let e=await this.ports.restoreEcdsaSigningSessionMaterialFromSealedRecord({sealedRecord:r}).catch(e=>(console.warn(`[EmailOtpSession] sealed refresh restore failed`,{thresholdSessionId:n,error:e instanceof Error?e.message:String(e||`unknown error`)}),null));if(!e)return null;console.debug(`[EmailOtpSession] sealed refresh restore succeeded`,{thresholdSessionId:n,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs});let t={ok:!0,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs};return await this.ports.recordSessionMaterialRestored({thresholdSessionId:n,chainTarget:r.chainTarget},t),t}finally{await this.ports.releaseSigningSessionRestoreLease(i).catch(()=>void 0)}}async discoverPersistedSessionsForWallet(e){if(this.ports.sessionPersistenceMode!==`sealed_refresh_v1`)return{..._R};let t=String(V(e.walletId)||``).trim();if(!t)return{..._R};let n=await aM({...e,walletId:t},{listExactSealedSessionsForWallet:({walletId:e,...t})=>this.ports.listExactSealedSessionsForWallet({walletId:e,filter:t}),onListError:({walletId:e,error:t})=>{console.warn(`[EmailOtpSession] wallet-scoped sealed ECDSA discovery list failed`,{walletId:e,error:t instanceof Error?t.message:String(t||`unknown error`)})}});if(!n.listed){let e=`wallet-sealed-ecdsa-empty:${t}`;this.ports.shouldLogDiagnostic(e)&&console.debug(`[EmailOtpSession] no durable sealed ECDSA records for wallet discovery`,{walletId:t})}return n}async restorePersistedSessionForSigning(e){if(this.ports.sessionPersistenceMode!==`sealed_refresh_v1`)return{...vR};let t=String(V(e.walletId)||``).trim();return t?await iM({...e,walletId:t},{listExactSealedSessionsForWallet:({walletId:e,...t})=>t.curve===`ecdsa`?this.ports.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:t.authMethod,curve:`ecdsa`,chainTarget:t.chainTarget}}):Promise.resolve([]),restoreSealedRecordForWallet:e=>this.restoreEmailOtpSealedRecordForWallet(e),cache:this.restoreCache,onListError:({walletId:e,target:t,reason:n,error:r})=>{console.warn(`[EmailOtpSession] signing-intent sealed ECDSA restore list failed`,{walletId:e,target:t,reason:n,error:r instanceof Error?r.message:String(r||`unknown error`)})}}):{...vR}}async readEcdsaSealedRecord(e){let t=this.requestedChainTarget;return t?await this.readEcdsaSealedRecordForTarget(e,t):null}async readEcdsaSealedRecordForTarget(e,t){let n=await this.ports.readExactSealedSession(e,{authMethod:`email_otp`,curve:`ecdsa`,chainTarget:t}).catch(n=>(console.warn(`[EmailOtpSession] sealed refresh ECDSA read failed`,{thresholdSessionId:e,chain:t.kind,error:n instanceof Error?n.message:String(n||`unknown error`)}),null));if(!n)return null;let r=Vj(n);return r.kind===`accepted`&&r.record.authMethod===`email_otp`&&r.record.curve===`ecdsa`?r.record:null}async restoreEmailOtpSealedRecordForWallet(e){return e.purpose.authMethod!==`email_otp`||e.purpose.curve!==`ecdsa`||e.record.authMethod!==`email_otp`||e.record.curve!==`ecdsa`?`deferred`:await this.restoreEcdsaSealedRecordForWallet({...e,record:e.record,purpose:e.purpose})}async restoreEcdsaSealedRecordForWallet(e){let t=String(e.purpose.thresholdSessionId||``).trim();if(!t||e.record.authMethod!==e.purpose.authMethod||e.record.thresholdSessionId!==t||!wn(e.record.chainTarget,e.purpose.chainTarget)||!g(e.record.roleLocalMaterialRef.materialActivation,e.purpose.materialActivation))return`deferred`;let n=[e.walletId,e.purpose.authMethod,e.purpose.curve,H(e.purpose.chainTarget),tf(e.purpose.materialActivation),t].join(`:`);if(this.restoreAttempts.hasCompleted(n))return`ready`;let r=this.restoreAttempts.getInFlight(n);if(r)return await r,this.restoreAttempts.hasCompleted(n)?`ready`:`deferred`;let i=`deferred`,a=(async()=>{let r=await this.ports.restoreEcdsaSigningSessionMaterialFromSealedRecord({sealedRecord:e.record});r&&(await this.ports.recordSessionMaterialRestored({thresholdSessionId:t,chainTarget:e.record.chainTarget},{ok:!0,remainingUses:r.remainingUses,expiresAtMs:r.expiresAtMs}),this.restoreAttempts.rememberCompleted(n),i=`restored`)})().catch(n=>{console.warn(`[EmailOtpSession] wallet-scoped sealed ECDSA restore failed`,{walletId:e.walletId,thresholdSessionId:t,error:n instanceof Error?n.message:String(n||`unknown error`)})}).finally(()=>{this.restoreAttempts.clearInFlight(n)});return this.restoreAttempts.setInFlight(n,a),await a,i}};async function bR(e){let t=CR(e.target);return t?await e.readWarmSessionStatusFromWorker(t).catch(e=>({ok:!1,code:`worker_error`,message:e instanceof Error?e.message:String(e||`Email OTP worker error`)})):{ok:!1,code:`invalid_args`,message:`Missing thresholdSessionId`}}async function xR(e){let t=CR(e.target);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing thresholdSessionId`};try{let n=await e.consumeWarmSessionUsesFromWorker({target:t,...typeof e.uses==`number`?{uses:e.uses}:{}});if(!n.ok&&n.code===`not_found`&&e.ecdsaPurpose){let r=await e.tryRestoreEcdsaWarmSessionStatusFromSealedRecord(e.ecdsaPurpose);if(r?.ok){let n=await e.consumeWarmSessionUsesFromWorker({target:t,...typeof e.uses==`number`?{uses:e.uses}:{}});return e.ecdsaPurpose&&await e.recordSessionUseConsumed(e.ecdsaPurpose,n),n}return r&&e.ecdsaPurpose&&await e.recordSessionMaterialRestored(e.ecdsaPurpose,r),n}return e.ecdsaPurpose&&await e.recordSessionUseConsumed(e.ecdsaPurpose,n),n}catch(e){return{ok:!1,code:`worker_error`,message:e instanceof Error?e.message:String(e||`Email OTP worker error`)}}}async function SR(e){let t=CR(e.target);t&&await e.clearVolatileWarmSessionMaterialFromWorker(t).catch(()=>void 0)}function CR(e){let t=String(e.thresholdSessionId||``).trim();return t?e.kind===`ecdsa`?{kind:`ecdsa`,thresholdSessionId:t}:{kind:`ed25519_yao`,thresholdSessionId:t,materialActivation:e.materialActivation}:null}function wR(e){return{async readStatus(t){return await KP({worker:e.worker,target:t})},async consumeUses(t){return await qP({worker:e.worker,target:t.target,...typeof t.uses==`number`?{uses:t.uses}:{}})},async clearMaterial(t){await JP({worker:e.worker,target:t})}}}var TR=class{constructor(e){this.ports=e}async readWarmSessionStatusOnly(e){return await bR({target:e,readWarmSessionStatusFromWorker:e=>this.ports.workerClient.readStatus(e)})}async consumeWarmSessionUses(e){return await xR({target:ER(e),...typeof e.uses==`number`?{uses:e.uses}:{},consumeWarmSessionUsesFromWorker:e=>this.ports.workerClient.consumeUses(e),ecdsaPurpose:Ej(e.purpose),tryRestoreEcdsaWarmSessionStatusFromSealedRecord:e=>this.ports.sealedRestoreOrchestrator.tryRestoreEcdsaWarmSessionStatusFromSealedRecord(e),recordSessionUseConsumed:(e,t)=>this.ports.sealedRefreshPolicy.recordSessionUseConsumed(e,t),recordSessionMaterialRestored:(e,t)=>this.ports.sealedRefreshPolicy.recordSessionMaterialRestored(e,t)})}async clearVolatileWarmSessionMaterial(e){await SR({target:e,clearVolatileWarmSessionMaterialFromWorker:e=>this.ports.workerClient.clearMaterial(e)})}};function ER(e){let t=Tj(e);return e.purpose.curve===`ecdsa`?{kind:`ecdsa`,thresholdSessionId:t}:{kind:`ed25519_yao`,thresholdSessionId:t,materialActivation:e.purpose.materialActivation}}var DR=class{sealedRefreshDiagnosticLogAtMsByKey=new Map;sealedRefreshPolicy;sealedRestoreOrchestrator;runtimeConfig;sealedSessionRegistry;warmSessionRuntime;exportRecoveryRuntime;ecdsaLifecycleRuntime;constructor(e){this.runtimeConfig=new mR({configs:e.configs,getRpId:e.getRpId}),this.sealedSessionRegistry=new hR({configs:e.configs,getSignerWorkerContext:e.getSignerWorkerContext,commitEvmFamilyThresholdEcdsaSessions:e.commitEvmFamilyThresholdEcdsaSessions,listActiveEcdsaCapabilityManifestsForWallet:e.listActiveEcdsaCapabilityManifestsForWallet,writeExactSealedSession:e.writeExactSealedSession,readExactSealedSession:e.readExactSealedSession,clearEcdsaRestoreCaches:()=>this.clearEcdsaRestoreCaches()}),this.ecdsaLifecycleRuntime=new $L({configs:e.configs,getSignerWorkerContext:e.getSignerWorkerContext,loadWalletCustodyEd25519Material:e.loadWalletCustodyEd25519Material,restoreWalletCustodyEcdsaContinuity:e.restoreWalletCustodyEcdsaContinuity,provisionThresholdEcdsaSession:e.provisionThresholdEcdsaSession,provisionEmailOtpEcdsaExplicitExportSession:e.provisionEmailOtpEcdsaExplicitExportSession,runtimeConfig:this.runtimeConfig,ownerLaneScopeStores:e.ownerLaneScopeStores,resolveSelectedWalletAuthority:e.resolveSelectedWalletAuthority,resolveCurrentEcdsaCapabilityRuntime:e.resolveCurrentEcdsaCapabilityRuntime,publicationPorts:()=>this.sealedSessionRegistry.ecdsaPublicationPorts()}),this.exportRecoveryRuntime=new pR({getSignerWorkerContext:e.getSignerWorkerContext,requireRelayUrl:()=>this.runtimeConfig.requireRelayUrl(),requireSigningSessionSealGroupId:()=>this.runtimeConfig.requireSigningSessionSealGroupId(),resolveSelectedWalletAuthority:e.resolveSelectedWalletAuthority,prepareEcdsaExportCapability:e=>this.ecdsaLifecycleRuntime.prepareEcdsaExportCapability(e)});let t=XL({withThresholdEcdsaSigningQueue:e.withThresholdEcdsaSigningQueue,getSignerWorkerContext:e.getSignerWorkerContext,resolveSelectedWalletAuthority:e.resolveSelectedWalletAuthority,readExactWalletSessionAuthorization:e.readExactWalletSessionAuthorization,provisionThresholdEcdsaSession:e.provisionThresholdEcdsaSession,commitEvmFamilyThresholdEcdsaSessions:e.commitEvmFamilyThresholdEcdsaSessions,resolveCurrentEcdsaCapabilityRuntime:e.resolveCurrentEcdsaCapabilityRuntime}),n=wR({worker:e.signerWorkerManager});this.sealedRefreshPolicy=new gR({updateExactSealedSessionPolicy:e.updateExactSealedSessionPolicy,clearEcdsaRestoreCaches:()=>this.clearEcdsaRestoreCaches()}),this.sealedRestoreOrchestrator=new yR({sessionPersistenceMode:e.configs.signing.sessionPersistenceMode,listExactSealedSessionsForWallet:e.listExactSealedSessionsForWallet,readExactSealedSession:e.readExactSealedSession,acquireSigningSessionRestoreLease:e.acquireSigningSessionRestoreLease,releaseSigningSessionRestoreLease:e.releaseSigningSessionRestoreLease,readWarmSessionStatusFromWorker:e=>n.readStatus({kind:`ecdsa`,thresholdSessionId:e}),restoreEcdsaSigningSessionMaterialFromSealedRecord:e=>t(e),recordSessionMaterialRestored:(e,t)=>this.sealedRefreshPolicy.recordSessionMaterialRestored(e,t),shouldLogDiagnostic:e=>this.shouldLogSealedRefreshDiagnostic(e)}),this.warmSessionRuntime=new TR({workerClient:n,sealedRefreshPolicy:this.sealedRefreshPolicy,sealedRestoreOrchestrator:this.sealedRestoreOrchestrator})}async persistEcdsaSessionForRefresh(e){await this.sealedSessionRegistry.persistEcdsaSessionForRefresh(e)}clearEcdsaRestoreCaches(){this.sealedRestoreOrchestrator.clearCache()}shouldLogSealedRefreshDiagnostic(e,t=Date.now()){let n=String(e||``).trim();return!n||t-(this.sealedRefreshDiagnosticLogAtMsByKey.get(n)||0)<6e4?!1:(this.sealedRefreshDiagnosticLogAtMsByKey.set(n,t),!0)}async discoverPersistedSessionsForWallet(e){return await this.sealedRestoreOrchestrator.discoverPersistedSessionsForWallet(e)}async restorePersistedSessionForSigning(e){return await this.sealedRestoreOrchestrator.restorePersistedSessionForSigning(e)}async readWarmSessionStatusOnly(e){return await this.warmSessionRuntime.readWarmSessionStatusOnly(e)}async consumeWarmSessionUses(e){return await this.warmSessionRuntime.consumeWarmSessionUses(e)}async clearVolatileWarmSessionMaterial(e){await this.warmSessionRuntime.clearVolatileWarmSessionMaterial(e)}async requestTransactionSigningChallenge(e){return await this.exportRecoveryRuntime.requestTransactionSigningChallenge(e)}async requestExportChallenge(e){return await this.exportRecoveryRuntime.requestExportChallenge(e)}async exportEcdsaKeyWithDurableAuthorization(e){return await this.exportRecoveryRuntime.exportEcdsaKeyWithDurableAuthorization(e)}async exportEd25519YaoSeedWithFreshEmailOtpLane(e){return await this.exportRecoveryRuntime.exportEd25519YaoSeedWithFreshEmailOtpLane(e)}async loginWithEcdsaCapabilityForSigning(e){return await this.ecdsaLifecycleRuntime.loginWithEcdsaCapabilityForSigning(e)}async loginWithEcdsaCapabilityInternal(e){return await this.ecdsaLifecycleRuntime.loginWithEcdsaCapabilityInternal(e)}};function OR(e){let t=new DR({configs:e.seamsWebConfigs,signerWorkerManager:e.signerWorkerManager,getRpId:()=>e.touchIdPrompt.getRpId(),getSignerWorkerContext:e.getSignerWorkerContext,loadWalletCustodyEd25519Material:e.loadWalletCustodyEd25519Material,restoreWalletCustodyEcdsaContinuity:e.restoreWalletCustodyEcdsaContinuity,resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),ownerLaneScopeStores:{getWalletAuthMethodV2:K.getWalletAuthMethodV2.bind(K),listWalletAuthMethodsForWallet:K.listWalletAuthMethodsForWallet.bind(K),getWalletPasskeyAuthenticator:K.getWalletPasskeyAuthenticator.bind(K)},readExactWalletSessionAuthorization:q.readExactWithOperationCredential.bind(q),provisionThresholdEcdsaSession:e.provisionThresholdEcdsaSession,withThresholdEcdsaSigningQueue:t=>Hd({queueByKey:e.thresholdEcdsaSigningQueueByKey,...t}),provisionEmailOtpEcdsaExplicitExportSession:e.provisionEmailOtpEcdsaExplicitExportSession,commitEvmFamilyThresholdEcdsaSessions:t=>EI({queueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,bootstrapStore:e.ecdsaBootstrapStore,persistEcdsaRoleLocalReadyRecord:e.persistEcdsaRoleLocalReadyRecord,ensureSealedRefreshStartupParityForThresholdEcdsaBootstrap:t=>bd(e.ensureSealedRefreshStartupParity,t)},t),listActiveEcdsaCapabilityManifestsForWallet:t=>e.listActiveEcdsaCapabilityManifestsForWallet(String(t)),resolveCurrentEcdsaCapabilityRuntime:e.resolveActiveEcdsaCapabilityRuntime,writeExactSealedSession:e.sealedSessionStore.writeExactSealedSession,readExactSealedSession:e.sealedSessionStore.readExactSealedSession,listExactSealedSessionsForWallet:e.sealedSessionStore.listExactSealedSessionsForWallet,acquireSigningSessionRestoreLease:e.sealedSessionStore.acquireSigningSessionRestoreLease,releaseSigningSessionRestoreLease:e.sealedSessionStore.releaseSigningSessionRestoreLease,updateExactSealedSessionPolicy:e.sealedSessionStore.updateExactSealedSessionPolicy}),n=HN({base:e.passkeyMpcSession,secondary:{readWarmSessionStatusOnly:e=>t.readWarmSessionStatusOnly({kind:`ecdsa`,thresholdSessionId:String(e)}),clearVolatileWarmSessionMaterial:e=>t.clearVolatileWarmSessionMaterial({kind:`ecdsa`,thresholdSessionId:String(e.scope.thresholdSessionId)})}});return{emailOtpSessions:t,touchConfirm:e.baseTouchConfirm,passkeyMpcSession:n}}function kR(e){return OR({resolveActiveEcdsaCapabilityRuntime:dy,seamsWebConfigs:e.seamsWebConfigs,touchIdPrompt:e.touchIdPrompt,signerWorkerManager:e.signerWorkerManager,ecdsaBootstrapStore:e.stores.walletProfileAndSignerRecords.ecdsaBootstrapStore,sealedSessionStore:e.sealedSigningSessionStore,baseTouchConfirm:e.baseTouchConfirm,passkeyMpcSession:e.passkeyMpcSession,getSignerWorkerContext:()=>e.getEnginePorts().walletSessionActivationDeps.getSignerWorkerContext(),provisionThresholdEcdsaSession:t=>e.getEnginePorts().tempoSigningDeps.provisionThresholdEcdsaSession(t),provisionEmailOtpEcdsaExplicitExportSession:t=>pu({queueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,activationDeps:e.getEnginePorts().walletSessionActivationDeps,persistEcdsaRoleLocalReadyRecord:e.runtimePorts.storage.persistEcdsaRoleLocalReadyRecord},t),thresholdEcdsaBootstrapQueueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,thresholdEcdsaSigningQueueByKey:e.thresholdEcdsaSigningQueueByKey,loadWalletCustodyEd25519Material:e.loadWalletCustodyEd25519Material,restoreWalletCustodyEcdsaContinuity:e.restoreWalletCustodyEcdsaContinuity,persistEcdsaRoleLocalReadyRecord:e.runtimePorts.storage.persistEcdsaRoleLocalReadyRecord,listActiveEcdsaCapabilityManifestsForWallet:e.listActiveEcdsaCapabilityManifestsForWallet,ensureSealedRefreshStartupParity:e.ensureSealedRefreshStartupParity})}function AR(e){return{passkeyPublicDeps:sP({seamsWebConfigs:e.seamsWebConfigs,credentialStore:e.stores.recoveryAndDeviceLinking.credentialStore,touchIdPrompt:e.touchIdPrompt,passkeyMpcSession:e.passkeyMpcSession,warmSigning:e.warmSigning,thresholdEcdsaBootstrapQueueByWallet:e.thresholdEcdsaBootstrapQueueByWallet,ensureSealedRefreshStartupParity:e.ensureSealedRefreshStartupParity,walletSessionActivationDeps:e.enginePorts.walletSessionActivationDeps,persistEcdsaRoleLocalReadyRecord:e.runtimePorts.storage.persistEcdsaRoleLocalReadyRecord}),warmCapabilitiesPublicDeps:cP({seamsWebConfigs:e.seamsWebConfigs,bootstrapStore:e.stores.walletProfileAndSignerRecords.ecdsaBootstrapStore,passkeyMpcSession:e.passkeyMpcSession,warmSigning:e.warmSigning,walletSessionActivationDeps:e.enginePorts.walletSessionActivationDeps,signingSessionCoordinator:e.enginePorts.signingSessionCoordinator})}}function jR(e,t){let n=null;for(let r of e)if(r.signer.authority.authorityDigest===t){if(n&&n.durableMaterial.roleLocalBinding.keyHandle!==r.durableMaterial.roleLocalBinding.keyHandle)throw Error(`[SigningEngine][near] Email OTP ECDSA session identity is ambiguous`);n=r}if(!n)throw Error(`[SigningEngine][near] Email OTP ECDSA capability is unavailable`);return n}function MR(e){let t=wt(Il(`wallet-session-mint`));if(!t.ok)throw Error(`[SigningEngine][near] failed to generate an ECDSA Wallet Session mint id`);return{kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:String(e.manifest.durableMaterial.roleLocalBinding.keyHandle),session_policy:{threshold_session_id:Qt.thresholdEcdsaSession(Il(`threshold-ecdsa-login`)),wallet_session_mint_id:t.value,ttl_ms:Se.ttlMs,remaining_uses:e.remainingUses,runtime_policy_scope:e.manifest.durableMaterial.runtimePolicyScope}}}async function NR(e,t){if(e.selectedFactorAuthority.factor.kind!==`email_otp`)throw Error(`Email OTP restore requires an Email OTP factor authority`);if(Hr(e.selectedAuthority))return{kind:`absent`};let n=await U({authority:e.selectedFactorAuthority}),r=jR(await ly(String(e.selectedAuthority.walletId)),String(n.authorityDigest));return{kind:`required`,sessionHandleBinding:{operation:`wallet_unlock`,keyHandle:String(r.durableMaterial.roleLocalBinding.keyHandle),authSubjectId:e.selectedFactorAuthority.factor.providerUserId,chainTarget:r.signer.scope.targetMemberships[0]},runtimePolicyScope:r.durableMaterial.runtimePolicyScope,sessionPolicy:MR({manifest:r,remainingUses:t})}}function PR(e){let t=ii(e.activation.public_capability.material_activation),n=0;for(let r of e.walletSession.capabilitySubjects)r.kind===`sign`&&r.keyFamily===`ecdsa_secp256k1`&&g(r.materialActivation,t)&&(n+=1);return n===1}async function FR(e){let t=e.response.session,n=e.authorization.record,r=e.authorization.operationCredential;if(String(n.walletId)!==String(e.walletId)||String(e.response.public_capability.client_id)!==String(n.walletId)||n.authorizationId!==t.authorization_id||n.quotaId!==t.quota_id||n.expiresAtMs!==t.expires_at_ms||r.walletSessionId!==t.wallet_session_id||!PR({walletSession:n,activation:e.response}))throw Error(`[SigningEngine][near] refreshed ECDSA exact Wallet Session is inconsistent`);await q.writeExactWithOperationCredential({record:n,operationCredential:r})}async function IR(e){return await na(K,e)}async function LR(){return null}const RR={getWalletAuthMethodV2:e=>K.getWalletAuthMethodV2(e),listWalletAuthMethodsForWallet:e=>K.listWalletAuthMethodsForWallet(e),getWalletPasskeyAuthenticator:LR,readEmailOtpProviderSubjectForWallet:IR};function zR(e){let t=gi({kind:`wallet_auth_authority_ref`,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,authorityDigest:e.authorityDigestB64u});if(!t)throw Error(`[SigningEngine][near] exact Email OTP authority digest is invalid`);return t}async function BR(e){let t=await Jp({authMethod:e.authMethod,stores:RR});if(!bi(t)||t.walletId!==e.authMethod.walletId||t.bindingId!==e.authMethod.walletAuthMethodId||t.verifier.emailHashHex!==e.emailHashHex||t.factor.providerUserId!==e.providerSubject)throw Error(`[SigningEngine][near] exact Email OTP factor authority changed`);return t}function VR(e){let t=e.auth;switch(t.kind){case R.emailOtp:return{kind:e.kind,signer:e.signer,auth:t,thresholdSessionId:e.thresholdSessionId};case R.passkey:case`voiceid`:throw Error(`[SigningEngine][near] Email OTP material identity is required`);default:throw Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}}async function HR(e){if(String(e.identity.signer.account.wallet.walletId)!==String(e.walletId)||String(e.identity.signer.account.nearAccountId)!==String(e.nearAccountId)||e.identity.signer.signerSlot!==e.signerSlot)return null;let t;try{t=await K.resolveSelectedWalletAuthority(String(e.walletId))}catch{return null}if(t.kind!==`resolved`)return null;let{selection:n,authMethod:r,authority:i}=t,a=i.signerActivations.ed25519;if(n.lockState!==`unlocked`||n.walletId!==e.walletId||n.walletAuthMethodId!==r.walletAuthMethodId||r.kind!==R.emailOtp||r.status!==`active`||r.walletId!==e.walletId||r.walletAuthorityId!==i.authorityId||i.state!==`active`||i.walletId!==e.walletId||!a||a.signer.walletId!==e.walletId||!g(a.materialActivation,e.materialActivation))return null;try{let t=await U({authority:await BR({authMethod:r,emailHashHex:r.emailHashHex,providerSubject:e.identity.auth.providerSubjectId})});return t.walletId!==e.walletId||t.walletAuthMethodId!==r.walletAuthMethodId?null:t}catch{return null}}async function UR(e){let t=e.bootstrap.session,n=e.exactAuthorization?.record??await q.readExact(t.walletSessionId);if(!n||n.kind!==`active_wallet_session_v1`||n.walletId!==e.walletId||n.authorizationId!==t.authorizationId||n.quotaId!==t.quotaId||n.expiresAtMs<=Date.now())throw Error(`[SigningEngine][near] exact Email OTP activation session is unavailable`);let[r,i]=await Promise.all([K.getWalletAuthMethodV2(String(n.authMethodId)),K.getWalletAuthority(String(n.authorityId))]);if(!r||r.kind!==`email_otp`||r.status!==`active`||r.walletId!==e.walletId||r.walletAuthorityId!==n.authorityId||r.emailHashHex!==e.emailHashHex||!i||i.state!==`active`||i.walletId!==e.walletId||i.authorityId!==n.authorityId||i.authorityDigestB64u!==n.authorityDigestB64u||i.revocationEpoch!==n.authorityRevocationEpoch)throw Error(`[SigningEngine][near] exact Email OTP activation authority is unavailable`);let a=zR({walletId:e.walletId,walletAuthMethodId:r.walletAuthMethodId,authorityDigestB64u:i.authorityDigestB64u}),o=await U({authority:await BR({authMethod:r,emailHashHex:e.emailHashHex,providerSubject:e.providerSubject})});if(e.verifiedAuthority&&(e.verifiedAuthority.walletId!==o.walletId||e.verifiedAuthority.walletAuthMethodId!==o.walletAuthMethodId))throw Error(`[SigningEngine][near] verified Email OTP activation authority changed`);let s=e.exactAuthorization;if(s){if(!Ue(s.record,n)||s.operationCredential.walletSessionId!==t.walletSessionId)throw Error(`[SigningEngine][near] exact Email OTP activation credential is unavailable`);return{authority:a,operationCredential:s.operationCredential}}let c=await q.readExactActiveForWallet({walletId:e.walletId,authorityId:n.authorityId,authMethodId:n.authMethodId});if(c.kind!==`found`||!Ue(c.record,n)||c.operationCredential.walletSessionId!==t.walletSessionId)throw Error(`[SigningEngine][near] exact Email OTP activation credential is unavailable`);return{authority:a,operationCredential:c.operationCredential}}function WR(e){switch(e.status){case`missing`:return{kind:`missing`};case`expired`:return{kind:`expired`};case`superseded`:return{kind:`superseded`};case`authority_unavailable`:return{kind:`authority_unavailable`};case`method_unavailable`:return{kind:`method_unavailable`};case`capability_unavailable`:return{kind:`capability_unavailable`};case`invalid`:return{kind:`corrupt`};default:throw Error(`[SigningEngine][ed25519-export] unsupported exact session status`)}}async function GR(e){let t=e.subject.signer.account.wallet.walletId,n;try{n=await K.resolveSelectedWalletAuthority(String(t))}catch{return{kind:`persistence_unavailable`}}if(n.kind!==`resolved`)return n.kind===`integrity_error`?{kind:`corrupt`}:{kind:`missing`};let{selection:r,authority:i,authMethod:a}=n;if(r.lockState!==`unlocked`||r.walletId!==t||r.walletAuthMethodId!==a.walletAuthMethodId||i.state!==`active`||i.walletId!==t||a.kind!==`email_otp`||a.status!==`active`||a.walletId!==t||a.walletAuthorityId!==i.authorityId)return{kind:`corrupt`};let o;try{o=await BR({authMethod:a,emailHashHex:a.emailHashHex,providerSubject:e.subject.auth.providerSubjectId})}catch{return{kind:`corrupt`}}let s=await q.readExactActiveForWallet({walletId:t,authorityId:i.authorityId,authMethodId:a.walletAuthMethodId});switch(s.kind){case`missing`:case`upgrade_required`:case`corrupt`:case`persistence_unavailable`:return s;case`found`:break;default:throw Error(`[SigningEngine][ed25519-export] unsupported exact local session result`)}if(s.record.expiresAtMs<=Date.now())return{kind:`expired`};let c;try{c=await qa({relayerUrl:e.relayerUrl,operationCredential:s.operationCredential}).read({walletSessionId:s.operationCredential.walletSessionId,quotaId:s.record.quotaId})}catch{return{kind:`persistence_unavailable`}}return c.status!==`active`&&c.status!==`exhausted`?WR(c):{kind:`found`,authorization:{selectedAuthority:i,selectedAuthMethod:a,factorAuthority:o,record:s.record,operationCredential:s.operationCredential,status:c}}}function KR(e,t){return globalThis.fetch(e,t)}function qR(e){let t=e.walletSessionState.thresholdSessionId;switch(e.subject.kind){case`exact_lane`:return{kind:`exact_lane`,laneIdentity:e.walletSessionState.signingLane.identity};case`export_exact_lane`:return{kind:`export_exact_lane`,laneIdentity:$c({signer:e.walletSessionState.signingLane.identity.signer,auth:e.walletSessionState.signingLane.identity.auth,thresholdSessionId:t}),materialActivation:e.subject.materialActivation};case`material_identity`:return{kind:`material_identity`,materialIdentity:{kind:`near_ed25519_material_identity`,signer:e.walletSessionState.signingLane.identity.signer,auth:e.walletSessionState.signingLane.identity.auth,thresholdSessionId:t}};default:return JR(e.subject)}}function JR(e){throw Error(`Unknown Ed25519 capability rehydration subject: ${String(e)}`)}async function YR(e){let t=e.walletSessionState.thresholdSessionId,n=await e.claimWarmSessionMaterial({thresholdSessionId:t,purpose:{curve:`ed25519`,materialActivation:e.materialActivation},consume:!1});if(n.ok||n.code!==`not_found`)return n;if(e.runtime.factor.kind!==`passkey`)throw Error(`[SigningEngine][near] persisted Ed25519 credential is unavailable`);let r=String(e.walletSessionState.walletSessionAuth.walletSessionToken||``).trim(),i=String(e.runtime.sealedRecord.groupId||``).trim();if(!r||!i)return{ok:!1,code:`invalid_args`,message:`Passkey Ed25519 sealed restore metadata is incomplete`};if(!g(e.runtime.sealedRecord.ed25519Restore.materialActivation,e.materialActivation))throw Error(`[SigningEngine][near] persisted Ed25519 material activation mismatch`);let a=Bi(e.runtime.sealedRecord.keyVersion),o=await e.rehydrateWarmSessionMaterial({thresholdSessionId:t,sealedSecretB64u:e.runtime.sealedRecord.sealedSecretB64u,signingSessionSealKeyVersion:a,expiresAtMs:e.runtime.sealedRecord.expiresAtMs,remainingUses:e.runtime.sealedRecord.remainingUses,transport:{curve:`ed25519`,authMethod:`passkey`,walletId:String(e.runtime.walletId),relayerUrl:e.runtime.relayerUrl,signingSessionSealKeyVersion:a,groupId:i,walletSessionToken:r,ed25519Restore:es({rpId:e.runtime.factor.rpId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,relayerKeyId:e.runtime.relayerKeyId,participantIds:e.runtime.participantIds,runtimePolicyScope:e.runtime.runtimePolicyScope,signerSlot:e.runtime.signerSlot,routerAbNormalSigning:e.runtime.routerAbNormalSigning,credentialIdB64u:e.runtime.factor.credentialIdB64u,materialActivation:e.materialActivation})}});return o.ok?(n=await e.claimWarmSessionMaterial({thresholdSessionId:t,purpose:{curve:`ed25519`,materialActivation:e.materialActivation},consume:!1}),n):o}async function XR(e){let t=e.identity.signer,n=(await e.store.listLanes()).filter(n=>String(n.walletId)===String(t.account.wallet.walletId)&&String(n.nearAccountId)===String(t.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(t.nearEd25519SigningKeyId)&&n.signerSlot===t.signerSlot&&String(n.thresholdSessionId)===String(e.identity.thresholdSessionId)&&yz(n.auth,e.identity.auth));if(n.length>1)throw Error(`[SigningEngine][near] public Ed25519 capability lane is conflicting`);return n[0]?.materialActivation??null}function ZR(e){let t=e.walletSessionState.signingLane,n=t.identity.signer;if(t.auth.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP recovery returned another auth lane`);return{walletId:n.account.wallet.walletId,nearAccountId:n.account.nearAccountId,thresholdSessionId:e.walletSessionState.thresholdSessionId,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,materialActivation:e.materialActivation,auth:{kind:`email_otp`,providerSubjectId:t.auth.providerSubjectId},nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot,remainingUses:e.walletSessionState.signingWalletSession.remainingUses,expiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs}}function QR(e){return e.kind===`wallet_authority_linked_signer_material_v1`&&e.keyFamily===`ed25519`}function $R(e){let t=e.selected;if(t.kind!==`resolved`){let e=t.kind===`integrity_error`?`: ${t.reason}`:``;throw Error(`[SigningEngine][ed25519-export] selected Wallet Authority is ${t.kind}${e}`)}if(t.authority.provenance.kind===`wallet_registration`||t.authority.provenance.kind===`wallet_recovery`)return null;let{selection:n,authMethod:r,authority:i,signerMaterials:a,exportRoot:o}=t,s=e.subject.signer,c=i.signerActivations.ed25519;if(n.lockState!==`unlocked`||r.kind!==R.emailOtp||r.status!==`active`||i.state!==`active`||String(n.walletId)!==String(s.account.wallet.walletId)||n.walletAuthMethodId!==r.walletAuthMethodId||r.walletAuthorityId!==i.authorityId||String(r.walletId)!==String(s.account.wallet.walletId)||!i.permissions.includes(`export_keys`)||!c||!g(c.materialActivation,e.expectedMaterialActivation)||!o)throw Error(`[SigningEngine][ed25519-export] selected linked Email OTP authority has no exact export root`);let l=null;for(let t of a)if(!(!QR(t)||t.authorityId!==i.authorityId||t.walletAuthMethodId!==r.walletAuthMethodId||!g(t.materialActivation,e.expectedMaterialActivation))){if(l)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 material is ambiguous`);l=t}if(!l)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 material is unavailable`);let u=l.targetFactor,d=l.publicFacts.applicationBinding,f=l.publicFacts.targetBinding.lifecycle,p=c.signer.registeredPublicKeyB64u;if(u.kind!==R.emailOtp||u.walletAuthMethodId!==r.walletAuthMethodId||u.emailHashHex!==r.emailHashHex||u.registrationAuthorityId!==r.registrationAuthorityId||o.authorityId!==i.authorityId||o.walletAuthMethodId!==r.walletAuthMethodId||o.walletKeyId!==c.signer.walletKeyId||o.envelope.binding.kind!==`ed25519_yao_client_root_v1`||o.envelope.binding.registeredPublicKeyB64u!==p||o.envelope.factor.kind!==R.emailOtp||d.wallet_id!==String(s.account.wallet.walletId)||d.near_ed25519_signing_key_id!==String(s.nearEd25519SigningKeyId)||d.key_creation_signer_slot!==s.signerSlot||f.account_id!==String(s.account.wallet.walletId)||f.session_id!==String(e.subject.thresholdSessionId)||f.selected_server_id!==e.expectedMaterialActivation.signingWorker||P(Uint8Array.from(l.publicFacts.activationReceipt.registered_public_key))!==p)throw Error(`[SigningEngine][ed25519-export] linked Email OTP export identity changed`);if(e.activeCapability){if(!g(e.activeCapability.materialActivation,e.expectedMaterialActivation)||P(Uint8Array.from(e.activeCapability.registeredPublicKey))!==p)throw Error(`[SigningEngine][ed25519-export] active Email OTP capability changed`);return o.envelope}return{envelope:o.envelope,source:{materialActivation:e.expectedMaterialActivation,signingWorkerId:f.selected_server_id,participantIds:l.publicFacts.participantIds,registeredPublicKeyB64u:p}}}async function ez(e){let t=null;for(let n of e.signerMaterials)if(!(!QR(n)||n.authorityId!==e.authMethod.walletAuthorityId||n.walletAuthMethodId!==e.authMethod.walletAuthMethodId)){if(t)throw Error(`[SigningEngine] linked Passkey Ed25519 signer material is conflicting`);t=n}if(!t)throw Error(`[SigningEngine] linked Passkey Ed25519 signer material is unavailable`);let n=t.publicFacts.applicationBinding,r=Ai(n.key_creation_signer_slot,{min:1}),i=t.targetFactor;if(!r||n.wallet_id!==String(e.walletId)||String(t.materialActivation.materialOwner)!==String(e.walletId)||i.kind!==R.passkey||i.walletAuthMethodId!==e.authMethod.walletAuthMethodId||String(i.rpId)!==String(e.authMethod.rpId)||String(i.credentialIdB64u)!==String(e.authMethod.credentialIdB64u))throw Error(`[SigningEngine] linked Passkey Ed25519 signer material identity is invalid`);let a=0;for(let i of await e.publicLaneStore.listLanes())i.auth.kind===`passkey`&&(String(i.walletId)!==String(e.walletId)||String(i.auth.rpId)!==String(e.authMethod.rpId)||i.auth.credentialIdB64u!==e.authMethod.credentialIdB64u||String(i.nearEd25519SigningKeyId)!==String(n.near_ed25519_signing_key_id)||i.signerSlot!==r||!g(i.materialActivation,t.materialActivation)||(a+=1));if(a===0)throw Error(`[SigningEngine] linked Passkey Ed25519 public lane is unavailable`);if(a!==1)throw Error(`[SigningEngine] linked Passkey Ed25519 public lane is ambiguous`);return r}async function tz(e){let t=e.laneIdentity.signer,n=(await e.store.listLanes()).filter(n=>n.auth.kind===R.emailOtp&&e.laneIdentity.auth.kind===R.emailOtp&&n.auth.providerSubjectId===e.laneIdentity.auth.providerSubjectId&&String(n.walletId)===String(t.account.wallet.walletId)&&String(n.nearAccountId)===String(t.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(t.nearEd25519SigningKeyId)&&n.signerSlot===t.signerSlot&&String(n.thresholdSessionId)===String(e.laneIdentity.thresholdSessionId)&&g(n.materialActivation,e.materialActivation));if(n.length!==1)throw Error(n.length===0?`[SigningEngine][near] Email OTP public lane is unavailable`:`[SigningEngine][near] Email OTP public lane is ambiguous`);return n[0]}async function nz(e){if(e.laneIdentity.auth.kind!==R.passkey)throw Error(`[SigningEngine][near] Passkey public lane authority is required`);let t=e.laneIdentity.auth,n=e.laneIdentity.signer,r=(await e.store.listLanes()).filter(r=>r.auth.kind===R.passkey&&r.auth.rpId===t.rpId&&r.auth.credentialIdB64u===t.credentialIdB64u&&String(r.walletId)===String(n.account.wallet.walletId)&&String(r.nearAccountId)===String(n.account.nearAccountId)&&String(r.nearEd25519SigningKeyId)===String(n.nearEd25519SigningKeyId)&&r.signerSlot===n.signerSlot&&String(r.thresholdSessionId)===String(e.laneIdentity.thresholdSessionId));if(r.length!==1)throw Error(r.length===0?`[SigningEngine][near] Passkey public lane is unavailable`:`[SigningEngine][near] Passkey public lane is ambiguous`);return r[0]}async function rz(e){let t=e.identity.signer,n=(await e.store.listLanes()).filter(n=>String(n.walletId)===String(t.account.wallet.walletId)&&String(n.nearAccountId)===String(t.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(t.nearEd25519SigningKeyId)&&n.signerSlot===t.signerSlot&&String(n.thresholdSessionId)===String(e.identity.thresholdSessionId)&&yz(n.auth,e.identity.auth)&&g(n.materialActivation,e.materialActivation));if(n.length!==1)throw Error(n.length===0?`[SigningEngine][near] exact Ed25519 public lane is unavailable`:`[SigningEngine][near] exact Ed25519 public lane is ambiguous`);return n[0]}async function iz(e){if(e.reference.auth.kind!==R.passkey)throw Error(`[SigningEngine][near] Passkey public lane authority is required`);if(e.authorization.selectedAuthMethod.kind!==R.passkey||String(e.authorization.session.walletId)!==String(e.reference.walletId))throw Error(`[SigningEngine][near] Passkey Wallet Session authority does not match lane`);let t=await K.getWalletAuthMethodV2(e.authorization.selectedAuthMethod.walletAuthMethodId);if(!t||t.kind!==R.passkey||t.status!==`active`||String(t.walletId)!==String(e.reference.walletId)||String(t.rpId)!==String(e.reference.auth.rpId)||String(t.credentialIdB64u)!==String(e.reference.auth.credentialIdB64u))throw Error(`[SigningEngine][near] Passkey Wallet Session method does not match lane`);let n=await U({authority:{walletId:t.walletId,factor:{kind:R.passkey,credentialIdB64u:t.credentialIdB64u},verifier:{kind:`webauthn`,rpId:t.rpId},bindingId:t.walletAuthMethodId}}),r=await U({authority:e.authorization.selectedFactorAuthority});if(n.authorityDigest!==r.authorityDigest||n.walletAuthMethodId!==r.walletAuthMethodId)throw Error(`[SigningEngine][near] Passkey Wallet Session authority changed`);return n}async function az(e){if(e.reference.auth.kind!==R.passkey)throw Error(`[SigningEngine][near] Passkey public lane authority is required`);if(!ol({session:e.authorization.session,materialActivation:e.materialActivation}))throw Error(`[SigningEngine][near] Passkey Wallet Session material changed`);let t=await iz({reference:e.reference,authorization:e.authorization}),n=Ot(e.authorization.session.authorizationId);if(!n.ok||e.authorization.operationCredential.token.trim().length===0)throw Error(`[SigningEngine][near] Passkey Ed25519 Wallet Session credential is unavailable`);let r=e.material.facts,i=cs({walletId:String(e.reference.walletId),nearAccountId:String(e.reference.nearAccountId),nearEd25519SigningKeyId:String(e.reference.nearEd25519SigningKeyId),walletSessionId:e.authorization.operationCredential.walletSessionId,authorizationId:n.value,quotaId:e.authorization.session.quotaId,thresholdSessionId:e.reference.thresholdSessionId,remainingUses:e.authorization.status.remainingUses,expiresAtMs:e.authorization.status.expiresAtMs,runtimePolicyScope:r.runtimePolicyScope,signingRootId:r.signingRootId,signingRootVersion:r.signingRootVersion,routerAbNormalSigning:r.routerAbNormalSigning,walletSessionToken:e.authorization.operationCredential.token,home:e.authorization.operationCredential.home,nowMs:Date.now()});if(!i.ok)throw Error(`[SigningEngine][near] Passkey Wallet Session is unusable (${i.reason})`);return Bs({walletId:e.reference.walletId,nearAccountId:e.reference.nearAccountId,nearEd25519SigningKeyId:e.reference.nearEd25519SigningKeyId,signerSlot:e.reference.signerSlot,rpId:e.reference.auth.rpId,credentialIdB64u:e.reference.auth.credentialIdB64u,relayerUrl:e.relayerUrl,authority:t,signingWalletSession:i.value})}async function oz(e){let t=await vc(e);if(t.kind!==`resolved`)throw J(t.kind===`conflict`?`runtime_conflict`:`missing_runtime`);return t.runtime}async function sz(e){let t=await Bo(Wd({authMethod:Jt(e.laneIdentity.auth.kind),materialActivation:e.materialActivation}));if(!t||t.curve!==`ed25519`)throw Error(`[SigningEngine][near] exact persisted Ed25519 runtime is missing`);let n=fc(t);if(!n||String(n.walletId)!==String(e.walletId)||String(n.nearAccountId)!==String(e.laneIdentity.signer.account.nearAccountId)||String(n.nearEd25519SigningKeyId)!==String(e.laneIdentity.signer.nearEd25519SigningKeyId)||n.signerSlot!==e.laneIdentity.signer.signerSlot||String(n.thresholdSessionId)!==String(e.laneIdentity.thresholdSessionId)||!yz(n.auth,e.laneIdentity.auth)||!g(n.sealedRecord.ed25519Restore.materialActivation,e.materialActivation))throw Error(`[SigningEngine][near] exact persisted Ed25519 runtime identity mismatch`);return n}async function cz(e){let t=(await hs({walletId:e.walletId,filter:{authMethod:Jt(e.identity.auth.kind),curve:`ed25519`}})).filter(e=>e.curve===`ed25519`).map(fc).filter(t=>t!==null&&bz({runtime:t,identity:e.identity}));if(t.length===0)throw J(`missing_runtime`);if(t.length!==1)throw J(`runtime_conflict`);return t[0]}function lz(e){let{selection:t,authMethod:n,authority:r}=e.selected;if(t.lockState!==`unlocked`||t.walletId!==e.walletId||t.walletAuthMethodId!==n.walletAuthMethodId||n.walletId!==e.walletId||n.walletAuthorityId!==r.authorityId||r.walletId!==e.walletId)return!1;switch(e.proof.kind){case`passkey`:return n.kind===R.passkey&&e.proof.authority.walletId===e.walletId&&e.proof.authority.bindingId===n.walletAuthMethodId&&e.proof.authority.factor.credentialIdB64u===n.credentialIdB64u&&e.proof.authority.verifier.rpId===n.rpId;case`email_otp`:return n.kind===R.emailOtp&&e.proof.authorityRef.walletId===e.walletId&&e.proof.authorityRef.walletAuthMethodId===n.walletAuthMethodId;default:throw e.proof,Error(`[SigningEngine][near] unsupported operation step-up proof`)}}async function uz(e){let t=await K.resolveSelectedWalletAuthority(String(e.walletId));if(t.kind!==`resolved`){let e=t.kind===`integrity_error`?`: ${t.reason}`:``;throw Error(`[SigningEngine][near] selected Wallet Authority is ${t.kind}${e}`)}if(!lz({walletId:e.walletId,proof:e.proof,selected:t}))throw Error(`[SigningEngine][near] operation step-up authority does not match selection`);let n=await Th({selected:{authMethod:t.authMethod,authority:t.authority},operation:{kind:`near_sign`,operation:`sign`,keyFamily:`ed25519`}});if(n.kind!==`resolved`)throw Error(`[SigningEngine][near] selected Wallet Authority rejected signing (${n.reason.kind})`);let r=Ay(await q.readExactWithOperationCredential({walletId:e.walletId,authorityId:t.authority.authorityId,authMethodId:t.authMethod.walletAuthMethodId}),`[SigningEngine][near] exact Wallet Session requires a newer client`),i=r?.record.capabilitySubjects.filter(e=>e.kind===`sign`&&e.keyFamily===`ed25519`&&g(e.materialActivation,n.value.materialActivation)).length===1;if(!r||r.record.walletId!==e.walletId||r.record.authorityId!==t.authority.authorityId||r.record.authMethodId!==t.authMethod.walletAuthMethodId||r.record.authorityDigestB64u!==t.authority.authorityDigestB64u||r.record.authorityRevocationEpoch!==t.authority.revocationEpoch||r.record.expiresAtMs<=Date.now()||!i)throw Error(`[SigningEngine][near] exact Wallet Session is unavailable for operation step-up`);return r.operationCredential}async function dz(e){let t=await Hv(e.runtime.walletId,e.relayerUrl,new Ja);if(!t)throw Error(`[SigningEngine][near] active Wallet Session authorization is unavailable`);return await Qs({runtime:e.runtime,authorization:t,nowMs:Date.now()})}function fz(e){if(e.factor.kind!==R.passkey)throw J(`binding_mismatch`);return{walletId:String(e.walletId),nearAccountId:String(e.nearAccountId),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId),thresholdSessionId:String(e.thresholdSessionId),signerSlot:e.signerSlot,rpId:String(e.factor.rpId),credentialIdB64u:e.factor.credentialIdB64u,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,signingWorkerId:e.routerAbNormalSigning.signingWorkerId}}function pz(e){if(!e||e.activeClient.status().kind!==`active`)return{kind:`absent`};let t=fo(e.activeClient.metadata());return{kind:`live`,runtime:co(t),materialActivation:t}}function mz(e){return Ck(e).auth}function hz(e){return e.auth===void 0?e.materialIdentity.auth:e.auth}function gz(e){if(e.laneIdentity===void 0||e.auth===void 0)throw Error(`[SigningEngine][near] authorized lane identity is required`);return{walletId:e.walletId,nearAccountId:e.nearAccountId,laneIdentity:e.laneIdentity,auth:e.auth}}function _z(e){return{walletId:e.walletId,nearAccountId:e.nearAccountId,materialIdentity:Ck(e)}}async function vz(e){if(e.reference.auth.kind!==R.emailOtp)throw Error(`[SigningEngine][near] Email OTP public lane authority is required`);if(!ol({session:e.authorization.session,materialActivation:e.materialActivation}))throw Error(`[SigningEngine][near] Email OTP Wallet Session material changed`);let t=Ot(e.authorization.session.authorizationId);if(!t.ok||e.authorization.operationCredential.token.trim().length===0)throw Error(`[SigningEngine][near] Email OTP Ed25519 Wallet Session credential is unavailable`);let n=await U({authority:e.authorization.selectedFactorAuthority}),r=e.material.facts,i=cs({walletId:String(e.reference.walletId),nearAccountId:String(e.reference.nearAccountId),nearEd25519SigningKeyId:String(e.reference.nearEd25519SigningKeyId),walletSessionId:e.authorization.operationCredential.walletSessionId,authorizationId:t.value,quotaId:e.authorization.session.quotaId,thresholdSessionId:e.reference.thresholdSessionId,remainingUses:e.authorization.status.remainingUses,expiresAtMs:e.authorization.status.expiresAtMs,runtimePolicyScope:r.runtimePolicyScope,signingRootId:r.signingRootId,signingRootVersion:r.signingRootVersion,routerAbNormalSigning:r.routerAbNormalSigning,walletSessionToken:e.authorization.operationCredential.token,home:e.authorization.operationCredential.home,nowMs:Date.now()});if(!i.ok)throw Error(`[SigningEngine][near] Email OTP Wallet Session is unusable (${i.reason})`);return uc({walletId:e.reference.walletId,nearAccountId:e.reference.nearAccountId,nearEd25519SigningKeyId:e.reference.nearEd25519SigningKeyId,providerSubjectId:e.reference.auth.providerSubjectId,signerSlot:e.reference.signerSlot,relayerUrl:e.relayerUrl,authority:n,signingWalletSession:i.value})}function yz(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`voiceid`:return t.kind===`voiceid`&&e.walletAuthMethodId===t.walletAuthMethodId&&e.deviceKeyId===t.deviceKeyId;case R.passkey:return t.kind===R.passkey&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u;case R.emailOtp:return t.kind===R.emailOtp&&e.providerSubjectId===t.providerSubjectId;default:throw Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}}function bz(e){let t=e.identity.signer;return String(e.runtime.walletId)===String(t.account.wallet.walletId)&&String(e.runtime.nearAccountId)===String(t.account.nearAccountId)&&String(e.runtime.nearEd25519SigningKeyId)===String(t.nearEd25519SigningKeyId)&&e.runtime.signerSlot===t.signerSlot&&String(e.runtime.thresholdSessionId)===String(e.identity.thresholdSessionId)&&yz(e.runtime.auth,e.identity.auth)}function xz(e){let t=Pe(e.publicLane.runtimePolicyScope);if(!t.signingRootVersion)throw Error(`[SigningEngine][near] Email OTP lane requires a signing-root version`);return{thresholdSessionId:e.publicLane.thresholdSessionId,signer:wk(e.input),signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,routerAbNormalSigning:{kind:Xe,signingWorkerId:String(e.publicLane.materialActivation.signingWorker)},runtimePolicyScope:e.publicLane.runtimePolicyScope,relayerUrl:e.relayerUrl}}function Sz(e){let t=mz(e),n=hz(e);if(t.kind!==n.kind)throw Error(`[SigningEngine][near] prepared material factor changed`);switch(n.kind){case`voiceid`:if(t.kind!==`voiceid`||t.walletAuthMethodId!==n.walletAuthMethodId||t.deviceKeyId!==n.deviceKeyId)throw Error(`Prepared VoiceID material binding changed`);return;case R.passkey:if(t.kind!==R.passkey||t.rpId!==n.rpId||t.credentialIdB64u!==n.credentialIdB64u)throw Error(`[SigningEngine][near] prepared Passkey material binding changed`);return;case R.emailOtp:if(t.kind!==R.emailOtp||t.providerSubjectId!==n.providerSubjectId)throw Error(`[SigningEngine][near] prepared Email OTP material binding changed`);return;default:throw Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}}async function Cz(e){let t=fo(e.material.activeClient.metadata());if(!ol({session:e.authorization.session,materialActivation:t}))throw Error(`Owner Ed25519 execution-lane material changed`);Ek({material:e.material,input:e.input,expectedActivation:t});let n=await ks({runtime:e.sealedRuntime,walletAuthMethodId:e.authorization.selectedAuthMethod.walletAuthMethodId}),r=await U({authority:e.authorization.selectedFactorAuthority});if(n.walletId!==r.walletId||n.walletAuthMethodId!==r.walletAuthMethodId||n.authorityDigest!==r.authorityDigest)throw Error(`Owner Ed25519 execution-lane authority does not match sealed material`);if(pz(e.material).kind!==`live`)throw Error(`Owner Ed25519 signing requires active Yao material`)}function wz(e){let t=e.hydration.materialActivation;if(!t)throw Error(`[SigningEngine][near] prepared material has no activation`);return t}function Tz(e){let t=wz(e.preparation);if(!e.context.materialActivation||!g(e.context.materialActivation,t))throw Error(`[SigningEngine][near] prepared material boundary changed activation`);return t}function Ez(e){return xc({credential:e,firstPrfOutput:!0,secondPrfOutput:!0})}async function Dz(e,t){return e.current?await e.current.storage.loadEcdsaRoleLocalReadyRecord(t):{ok:!1,code:`unavailable`,message:`Signing runtime storage is not initialized`}}function Oz(e){let t=e.event;switch(t){case`signing_session.expired`:return`${String(e.walletId)}:${String(e.walletSessionId)}`;case`registration.near_provisioning_changed`:return`${String(e.walletId)}:${e.state.status}:${e.state.updatedAtMs}`;default:return kz(t)}}function kz(e){throw Error(`Unsupported SDK lifecycle event: ${String(e)}`)}async function Az(e){if(!K.isDisabled())return await K.getAppState(e)}async function jz(e,t){K.isDisabled()||await K.setAppState(e,t)}const Mz={readCacheEntry:Az,writeCacheEntry:jz};function Nz(e,t){switch(e){case`add_email_code`:return{title:`Enter email code to add sign-in`,body:`This one-time code confirms ${t} can unlock this wallet.`,operation:`Add email code sign-in`,warning:`Adding email code lets anyone with access to your inbox try to unlock this wallet.`};case`add_passkey`:return{title:`Enter email code to add a passkey`,body:`This code confirms you can add a new passkey to this wallet.`,operation:`Add passkey`};case`remove_auth_method`:return{title:`Enter email code to remove sign-in`,body:`This code confirms removal of a wallet authentication method.`,operation:`Remove authentication method`};case`move_wallet`:return{title:`Enter email code to move wallet`,body:`This code confirms a wallet region move.`,operation:`Move wallet`};case`recovery_status`:return{title:`Enter email code to check recovery codes`,body:`This code confirms you can view this wallet’s recovery-code status.`,operation:`Check recovery-code status`};case`recovery_unlock`:return{title:`Enter email code to prepare new recovery codes`,body:`This code unlocks your wallet seed to create a new recovery-code set.`,operation:`Prepare recovery-code rotation`};case`recovery_rotate`:return{title:`Enter email code to rotate recovery codes`,body:`This code confirms the new recovery-code set replaces the old set.`,operation:`Rotate recovery codes`};case`recovery_backup_acknowledge`:return{title:`Enter email code to confirm backup`,body:`This code confirms you saved the recovery codes shown by this wallet.`,operation:`Confirm recovery-code backup`}}}var Pz=class{touchConfirm;passkeyMpcSession;signerWorkerManager;touchIdPrompt;userPreferencesManager;nearClient;nonceCoordinator;workerBaseOrigin=``;appearance;thresholdEcdsaBootstrapQueueByWallet=new Map;thresholdEcdsaSigningQueueByKey=new Map;thresholdEd25519CommitQueueByKey=new Map;nearEd25519CapabilityRehydrationBySubject=new Map;emailOtpSessions;warmSigning;passkeyPublicDeps;warmCapabilitiesPublicDeps;sessionPublicDeps;emailOtpPublicDeps;recoveryPublicDeps;sealedRefreshStartupParityPromise;hostWarmCriticalResourcesTask=null;sealedRefreshStartupParityError=null;runtimePorts;enginePorts;ecdsaBootstrapStore;ed25519YaoPageLifecycleOwner;ed25519YaoPublicCapabilityReferences;sdkLifecycleEventListeners=new Set;deliveredSdkLifecycleEventKeys=new Set;signingSessionLifecycleSubscription;nearProvisioningUnsubscribe;walletAuthenticationState={kind:`signed_out`};voiceIdNearSessions=new Map;volatileWarmSigningMaterialCleanupInFlight=null;seamsWebConfigs;readNearEd25519SigningCandidate(e){return Bv(String(this.seamsWebConfigs.network.relayer?.url||``).trim(),new Ja,e)}async prepareVoiceIdNearSigning(e){let t=Ck(e),n=this.voiceIdNearSessions.get(e.walletId);if(t.auth.kind!==`voiceid`||!n||!yz(t.auth,n.signingLane.auth)||t.signer.account.nearAccountId!==n.signingLane.identity.signer.account.nearAccountId||t.signer.nearEd25519SigningKeyId!==n.signingLane.identity.signer.nearEd25519SigningKeyId||t.thresholdSessionId!==n.thresholdSessionId)throw Error(`Unlock with VoiceID again before signing.`);let r=await this.readNearEd25519SigningCandidate(e.walletId);if(r.kind!==`found`||r.authorization.selectedAuthMethod.kind!==`voiceid`||r.authorization.selectedAuthMethod.walletAuthMethodId!==t.auth.walletAuthMethodId||r.authorization.operationCredential.walletSessionId!==n.walletSessionId)throw Error(`The VoiceID Wallet Session is unavailable. Unlock again.`);let i=r.authorization.selectedAuthority.signerActivations.ed25519;if(!i)throw Error(`VoiceID Wallet Session has no NEAR signer.`);let a=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:i.materialActivation});if(!a)throw Error(`Unlock with VoiceID again to restore signing material.`);return Ek({material:a,input:e,expectedActivation:i.materialActivation}),await vl({hydration:oo({authority:n.authority,runtime:co(i.materialActivation),materialActivation:i.materialActivation}),requirement:t.auth,authorization:r.authorization})}readExactNearEd25519WalletSessionAuthorization(e){return Vv(String(this.seamsWebConfigs.network.relayer?.url||``).trim(),new Ja,e)}resolveActiveNearEd25519WalletSessionAuthorization(e,t){return Hv(e,String(this.seamsWebConfigs.network.relayer?.url||``).trim(),t)}listPreprocessingCapabilities;constructor(e,t,n){Is(Mz),this.seamsWebConfigs=e,this.ed25519YaoPublicCapabilityReferences=n.ed25519YaoPublicCapabilityReferences,this.appearance=e.ui.appearance,this.nearClient=t,this.ecdsaBootstrapStore=n.signingEngineStores.walletProfileAndSignerRecords.ecdsaBootstrapStore,this.sealedRefreshStartupParityPromise=Xk({configs:this.seamsWebConfigs}).catch(e=>{this.sealedRefreshStartupParityError=e instanceof Error?e:Error(String(e||`sealed refresh parity check failed`))});let r={current:null},i=Dz.bind(null,r),a=CN({resolveActiveEcdsaCapabilityRuntime:dy,resolveOperationStepUpCredential:this.resolveOperationStepUpCredential.bind(this),stores:n.managerStores,seamsWebConfigs:this.seamsWebConfigs,nearClient:this.nearClient,loadEcdsaRoleLocalReadyRecord:i,getTheme:()=>this.appearance.theme.mode,getAppearance:()=>this.appearance,thresholdEcdsaSigningQueueByKey:this.thresholdEcdsaSigningQueueByKey});this.touchIdPrompt=a.touchIdPrompt,this.userPreferencesManager=a.userPreferencesManager,this.nonceCoordinator=a.nonceCoordinator,this.signerWorkerManager=a.signerWorkerManager;let o=n.createRuntime({config:this.seamsWebConfigs,workerCtx:this.signerWorkerManager.getContext(),accountLifecycle:{accountStore:n.signingEngineStores.walletProfileAndSignerRecords.accountStore,userPreferencesManager:this.userPreferencesManager,nonceCoordinator:this.nonceCoordinator},ecdsaBootstrapStore:this.ecdsaBootstrapStore,getWarmSessionMaterialWriter:()=>this.passkeyMpcSession,getNearSigningDeps:()=>this.enginePorts.nearSigningDeps,getEvmFamilySigningDeps:()=>this.enginePorts.tempoSigningDeps});r.current=o.runtimePorts;let s=o.state.ecdsaSessions;this.runtimePorts=o.runtimePorts;let c=kR({seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,signerWorkerManager:this.signerWorkerManager,stores:n.signingEngineStores,runtimePorts:this.runtimePorts,sealedSigningSessionStore:n.sealedSigningSessionStore,baseTouchConfirm:a.touchConfirm,passkeyMpcSession:a.passkeyMpcSession,getEnginePorts:()=>this.enginePorts,thresholdEcdsaBootstrapQueueByWallet:this.thresholdEcdsaBootstrapQueueByWallet,thresholdEcdsaSigningQueueByKey:this.thresholdEcdsaSigningQueueByKey,loadWalletCustodyEd25519Material:this.loadEmailOtpWalletCustodyEd25519Material.bind(this),restoreWalletCustodyEcdsaContinuity:this.restoreWalletCustodyEcdsaContinuity.bind(this),getWarmSigning:()=>this.warmSigning,ensureSealedRefreshStartupParity:()=>this.ensureSealedRefreshStartupParity(),listActiveEcdsaCapabilityManifestsForWallet:ly});this.emailOtpSessions=c.emailOtpSessions,this.touchConfirm=c.touchConfirm,this.passkeyMpcSession=c.passkeyMpcSession,this.warmSigning=oP({resolveActiveEcdsaCapabilityRuntime:dy,resolveActiveEcdsaCapabilityRuntimeForChain:fy,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,getEmailOtpWarmSessionStatus:e=>this.emailOtpSessions.readWarmSessionStatusOnly(e),signingSessionSeal:this.seamsWebConfigs.signing.sessionSeal,ecdsaExportArtifacts:s,resolveActiveEcdsaWalletSessionAuthorization:Yv({seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,stores:n.signingEngineStores,emailOtpSessions:this.emailOtpSessions,sealedSigningSessionStore:n.sealedSigningSessionStore}),resolveActiveEd25519WalletSessionAuthorization:this.resolveActiveNearEd25519WalletSessionAuthorization.bind(this)}),this.listPreprocessingCapabilities=Jv.bind(null,{seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,stores:n.signingEngineStores,emailOtpSessions:this.emailOtpSessions,sealedSigningSessionStore:n.sealedSigningSessionStore}),this.sessionPublicDeps=wN({seamsWebConfigs:this.seamsWebConfigs,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,emailOtpSessions:this.emailOtpSessions,ed25519YaoPublicCapabilityLanes:n.ed25519YaoPublicCapabilityReferences,isEd25519YaoPublicCapabilityActive:this.isEd25519YaoPublicCapabilityActive.bind(this),readActiveWalletSessionAuthorization:Vv.bind(null,this.seamsWebConfigs.network.relayer.url),listEcdsaSigningCapabilitiesForWallet:(e,t)=>ry({seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,stores:n.signingEngineStores,emailOtpSessions:this.emailOtpSessions,sealedSigningSessionStore:n.sealedSigningSessionStore},e,t),getWalletSessionStatus:Nv({seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,stores:n.signingEngineStores,emailOtpSessions:this.emailOtpSessions,sealedSigningSessionStore:n.sealedSigningSessionStore})}),this.emailOtpPublicDeps={relayerUrl:this.seamsWebConfigs.network.relayer?.url||``,groupId:Ze,getSignerWorkerContext:()=>this.enginePorts.walletSessionActivationDeps.getSignerWorkerContext(),emailOtpSessions:this.emailOtpSessions},this.recoveryPublicDeps=Ev({seamsWebConfigs:this.seamsWebConfigs,runtimePorts:this.runtimePorts,signerWorkerManager:this.signerWorkerManager,warmSigning:this.warmSigning,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,passkeyMpcExport:a.passkeyMpcExport,emailOtpSessions:this.emailOtpSessions,thresholdEcdsaBootstrapQueueByWallet:this.thresholdEcdsaBootstrapQueueByWallet,thresholdEcdsaSigningQueueByKey:this.thresholdEcdsaSigningQueueByKey,thresholdEd25519CommitQueueByKey:this.thresholdEd25519CommitQueueByKey,getWalletSessionActivationDeps:()=>this.enginePorts.walletSessionActivationDeps,resolvePasskeyEd25519YaoExportContext:this.resolveExactPasskeyEd25519YaoExportContext.bind(this),resolveEmailOtpEd25519YaoExportContext:this.resolveEmailOtpEd25519YaoExportContext.bind(this),getSigningSessionCoordinator:()=>this.enginePorts.signingSessionCoordinator,getTheme:()=>this.appearance.theme.mode,ed25519YaoPublicCapabilityLanes:n.ed25519YaoPublicCapabilityReferences,isEd25519YaoPublicCapabilityActive:this.isEd25519YaoPublicCapabilityActive.bind(this),readActiveWalletSessionAuthorization:Vv.bind(null,this.seamsWebConfigs.network.relayer.url),listEcdsaSigningCapabilitiesForWallet:(e,t)=>ry({seamsWebConfigs:this.seamsWebConfigs,touchIdPrompt:this.touchIdPrompt,stores:n.signingEngineStores,emailOtpSessions:this.emailOtpSessions,sealedSigningSessionStore:n.sealedSigningSessionStore},e,t),resolveOwnerLaneScope:e=>this.resolveSelectedOwnerLaneScope(e)}),this.enginePorts=hy({runtimePorts:this.runtimePorts,stores:n.signingEngineStores,ed25519YaoPublicCapabilityReferences:n.ed25519YaoPublicCapabilityReferences,seamsWebConfigs:this.seamsWebConfigs,nearClient:this.nearClient,touchIdPrompt:this.touchIdPrompt,userPreferencesManager:this.userPreferencesManager,nonceCoordinator:this.nonceCoordinator,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,passkeyMpcExport:a.passkeyMpcExport,signerWorkerManager:this.signerWorkerManager,emailOtpSessions:this.emailOtpSessions,warmSigning:this.warmSigning,sealedSigningSessionStore:n.sealedSigningSessionStore,ecdsaBootstrapStore:this.ecdsaBootstrapStore,thresholdEcdsaBootstrapQueueByWallet:this.thresholdEcdsaBootstrapQueueByWallet,thresholdEcdsaSigningQueueByKey:this.thresholdEcdsaSigningQueueByKey,thresholdEd25519CommitQueueByKey:this.thresholdEd25519CommitQueueByKey,getWorkerBaseOrigin:()=>this.workerBaseOrigin,shouldPrewarmUiConfirmUi:n.shouldPrewarmUiConfirmUi,getTheme:()=>this.appearance.theme.mode,ensureSealedRefreshStartupParity:()=>this.ensureSealedRefreshStartupParity(),resolveOwnerLaneScope:e=>this.resolveSelectedOwnerLaneScope(e),getEnginePorts:()=>this.enginePorts,prepareNearEd25519YaoMaterialBoundary:this.prepareExactNearEd25519YaoMaterialBoundary.bind(this)}),this.signingSessionLifecycleSubscription=this.enginePorts.signingSessionCoordinator.subscribeLifecycle(this.publishSdkLifecycleEvent.bind(this)),this.nearProvisioningUnsubscribe=pc(this.publishNearProvisioningLifecycleEvent.bind(this)),this.ed25519YaoPageLifecycleOwner=new NF(typeof window>`u`?null:window,this.enginePorts.ed25519YaoActiveClients);let l=AR({seamsWebConfigs:this.seamsWebConfigs,stores:n.signingEngineStores,touchIdPrompt:this.touchIdPrompt,touchConfirm:this.touchConfirm,passkeyMpcSession:this.passkeyMpcSession,warmSigning:this.warmSigning,runtimePorts:this.runtimePorts,thresholdEcdsaBootstrapQueueByWallet:this.thresholdEcdsaBootstrapQueueByWallet,ensureSealedRefreshStartupParity:()=>this.ensureSealedRefreshStartupParity(),enginePorts:this.enginePorts});this.passkeyPublicDeps=l.passkeyPublicDeps,this.warmCapabilitiesPublicDeps=l.warmCapabilitiesPublicDeps,to(e=>{this.persistUpgradedWalletCustodyEnvelopeV1(e)}),n.initializeRuntime({userPreferencesManager:this.userPreferencesManager,getWorkerBaseOrigin:()=>this.workerBaseOrigin,setWorkerBaseOrigin:e=>{this.workerBaseOrigin=e,this.signerWorkerManager.setWorkerBaseOrigin(e),this.touchConfirm.setWorkerBaseOrigin?.(e),a.passkeyMpcExport.setWorkerBaseOrigin(e),this.passkeyMpcSession.setWorkerBaseOrigin(e)}})}async resolveOperationStepUpCredential(e){let t=await uz({walletId:e.walletId,proof:e.proof});return{kind:`wallet_session_opaque`,walletSessionToken:t.token,home:t.home}}async ensureSealedRefreshStartupParity(){if(await this.sealedRefreshStartupParityPromise,this.sealedRefreshStartupParityError)throw this.sealedRefreshStartupParityError}async establishWalletCustodyNearEd25519KeySet(e){let t=new Ds({routerOrigin:e.routerOrigin,routing:e.home,authorization:{kind:`bearer`,value:e.authorization},fetch:globalThis.fetch,...e.traceContext?{traceContext:e.traceContext}:{}}),n=null,r=await ls({runStep:$a(this.walletCustodyCeremonyTransportV1()),walletId:e.walletId,...e.factor,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,registrationCeremonyId:e.registrationCeremonyId,yaoAdmission:e.admissionReceipt,yaoApplication:e.admissionRequest.application_binding,participantIds:e.participantIds,runRouterRound:async r=>{let i=e.executeWithProof?await e.executeWithProof(r):null;return i===null?(n=await gI({executeRequestJson:r,transport:t}),n):(n=i,n)}});if(!n)throw Error(`the wallet custody NEAR run completed without a Router activation result`);if(!r.localMaterial)throw Error(`the wallet custody NEAR run sealed no local material`);return{recoveryCodes:r.recoveryCodes,commitPayload:r.commitPayload,activationReference:r.activationReference,localMaterial:r.localMaterial,metadata:VF({admissionRequest:e.admissionRequest,activationResultJson:n})}}async recoverWalletCustodyManifest(e){return await pI({...e,runStep:$a(this.walletCustodyCeremonyTransportV1()),workerCtx:this.signerWorkerManager.getContext()})}async createWalletRecoveryReplacementCredential(e){let t=xt(`wallet-recovery:${e.registration.challengeId}`),n=KF(Ez(await this.touchIdPrompt.generateRegistrationCredentialsInternal({kind:`wallet_recovery`,walletId:e.walletId,intendedUserName:e.walletId,recoveryRegistration:e.registration,prompt:{kind:`immediate`,requestId:t,cancellation:e.cancellation}})));return{registration:Cc(n.registration),credentialIdB64u:n.credentialIdB64u,factorSecret:n.factorSecret}}async joinWalletCustodyNearEd25519KeySet(e){let t=new Ds({routerOrigin:e.routerOrigin,routing:e.routing,authorization:{kind:`bearer`,value:e.authorization},fetch:globalThis.fetch,...e.traceContext?{traceContext:e.traceContext}:{}}),n=null,r=await Rs({runStep:$a(this.walletCustodyCeremonyTransportV1()),preparation:e.preparation,beforeRouterRound:e.beforeRouterRound,custodyJson:e.custodyJson,factorSecret:e.factorSecret,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,registrationCeremonyId:e.registrationCeremonyId,yaoAdmission:e.admissionReceipt,yaoApplication:e.admissionRequest.application_binding,participantIds:e.participantIds,runRouterRound:async e=>(n=await gI({executeRequestJson:e,transport:t}),n)});if(!n||!r.localMaterial)throw Error(`the wallet custody NEAR join produced no local signing material`);return{commitPayload:r.commitPayload,activationReference:r.activationReference,localMaterial:r.localMaterial,metadata:VF({admissionRequest:e.admissionRequest,activationResultJson:n})}}async rejoinWalletCustodyNearEd25519KeySet(e){let t=new Ds({routerOrigin:e.routerOrigin,routing:{kind:`discovery`},authorization:{kind:`bearer`,value:`Bearer ${e.walletSessionToken}`},fetch:globalThis.fetch}),n=await ZF({basis:e.recoveryBasis}),r=await QF({request:n,transport:t}),i=await Gs({runStep:$a(this.walletCustodyCeremonyTransportV1()),walletId:e.walletId,custodyJson:e.custodyJson,factorSecret:e.factorSecret,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,recoveryLifecycleId:n.scope.lifecycle_id,yaoAdmission:r.receipt,yaoApplication:r.request.application_binding,participantIds:e.recoveryBasis.participantIds,registeredPublicKeyB64u:P(Uint8Array.from(e.recoveryBasis.registeredPublicKey)),runRouterRound:e=>$F({executeRequestJson:e,transport:t}),activateRouterRecovery:e=>eI({request:n,protocolResultJson:e,transport:t})});if(!i.localMaterial)throw Error(`the wallet custody NEAR cold rejoin produced no local signing material`);return{commitPayload:i.commitPayload,activationReference:i.activationReference,localMaterial:i.localMaterial,metadata:HF({admissionRequest:n,activationResultJson:i.activationResultJson,activationReceipt:i.activationReceipt})}}async establishWalletCustodyEvmFamilyKeySet(e){return await Es({...e,runStep:$a(this.walletCustodyCeremonyTransportV1())})}async joinWalletCustodyEvmFamilyKeySet(e){return await Ao({...e,runStep:$a(this.walletCustodyCeremonyTransportV1())})}async rejoinWalletCustodyEvmFamilyKeySet(e){return await ac({...e,runStep:$a(this.walletCustodyCeremonyTransportV1())})}async restoreWalletCustodyEcdsaContinuity(e){let t=await Eo({...e,store:new ra});if(t.kind!==`committed`)throw Error(`wallet custody ECDSA import returned ${t.kind}`);let n=ii(e.publicCapability.material_activation),r=await ed({workerCtx:this.signerWorkerManager.getContext(),authority:e.authority,materialActivation:n});if(!r.ok)throw Error(`wallet custody ECDSA material open returned ${r.reason}`);return{materialActivation:n,materialRef:r.materialRef}}async persistWalletCustodyEd25519Material(e){await Do({store:this.signerWorkerManager.getContext().nearKeyMaterialStore,binding:e.binding,sealed:e.sealed})}async loadWalletCustodyEd25519Material(e){return await Co({store:this.signerWorkerManager.getContext().nearKeyMaterialStore,nearAccountId:e.nearAccountId,signerSlot:e.signerSlot,expectedRegisteredPublicKeyB64u:e.expectedRegisteredPublicKeyB64u})}async loadEmailOtpWalletCustodyEd25519Material(e){let t=await this.loadWalletCustodyEd25519Material({nearAccountId:e.nearAccountId,signerSlot:e.signerSlot,expectedRegisteredPublicKeyB64u:``});return t.kind===`found`?t:{kind:`absent`}}async deleteWalletCustodyEd25519Material(e){await wo({store:this.signerWorkerManager.getContext().nearKeyMaterialStore,nearAccountId:e.nearAccountId,signerSlot:e.signerSlot})}async assertSealedRefreshStartupParity(){await this.ensureSealedRefreshStartupParity()}async discoverPersistedSessionsForWallet(e){return await Nh(this.sessionPublicDeps,e)}isEd25519YaoPublicCapabilityActive(e){switch(e.auth.kind){case R.emailOtp:return!0;case R.passkey:case`voiceid`:return this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:e.materialActivation})!==null;default:throw e.auth,Error(`Unsupported Ed25519 public capability auth method`)}}async readPersistedAvailableSigningLanes(e,t){return await Ph(this.sessionPublicDeps,e,t)}async readOwnerScopedSigningLanes(e,t){return await Fh(this.sessionPublicDeps,e,t)}async resolveSelectedOwnerLaneScope(e){let t=_(e);if(!t.ok)throw Error(t.error.message);let n={getWalletAuthMethodV2:e=>K.getWalletAuthMethodV2(e),listWalletAuthMethodsForWallet:e=>K.listWalletAuthMethodsForWallet(e),getWalletPasskeyAuthenticator:e=>K.getWalletPasskeyAuthenticator(e),readEmailOtpProviderSubjectForWallet:e=>na(K,e)},r=await K.resolveSelectedWalletAuthority(String(t.value));if(r.kind===`resolved`){let{selection:e,authMethod:i,authority:a}=r;if(e.walletId!==t.value||e.walletAuthMethodId!==i.walletAuthMethodId||i.walletId!==t.value||i.walletAuthorityId!==a.authorityId||a.walletId!==t.value)throw Error(`[SigningEngine] selected Wallet Authority identity mismatch`);if(e.lockState!==`unlocked`)throw jf(`wallet_locked`);if(i.status!==`active`)throw jf(`method_unavailable`);if(a.state!==`active`)throw jf(`authority_unavailable`);if(a.provenance.kind===`device_link`&&i.kind===`passkey`&&a.signerActivations.ed25519)return Yp({authMethod:i,signerSlot:await ez({walletId:t.value,authMethod:i,signerMaterials:r.signerMaterials,publicLaneStore:this.ed25519YaoPublicCapabilityReferences})});if(a.provenance.kind===`device_link`&&i.kind===`passkey`&&a.signerActivations.ecdsa)return Xp({authMethod:i});if(a.provenance.kind===`device_link`&&i.kind===`email_otp`&&a.signerActivations.ecdsa){let e=Ld({walletId:t.value,materialActivation:a.signerActivations.ecdsa.materialActivation});if(!e||e.authorityId!==a.authorityId||!bi(e.factorAuthority))throw Error(`[SigningEngine] selected linked Email OTP authority has no exact ECDSA holder runtime`);let n=await U({authority:e.factorAuthority});if(n.walletId!==t.value||n.walletAuthMethodId!==i.walletAuthMethodId)throw Error(`[SigningEngine] selected linked Email OTP authority has no exact ECDSA holder runtime`);return Zp({authMethod:i,factorAuthority:e.factorAuthority,authorityRef:n})}return await $p({authMethod:i,stores:n})}let i=r.kind===`integrity_error`?`: ${r.reason}`:``;throw Error(`[SigningEngine] selected Wallet Authority is ${r.kind}${i}`)}readWalletAuthenticationState(){return this.walletAuthenticationState}async retireActiveWalletSessionAuthorizationForLock(e){let t=Date.now();(await q.retireExactActiveForWallet({walletId:e,reason:`wallet_locked`,retiredAtMs:t})).length>0&&this.destroyUnlockedWalletEd25519ExportRootCapabilitiesV1({kind:`wallet`,walletId:String(e)})}async advanceWalletLockGeneration(e){return K.advanceWalletLockGeneration({walletId:e,lockedAtMs:Date.now()})}async markWalletSelectionUnlocked(e){await K.markWalletSelectionUnlocked({walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,unlockedAtMs:Date.now()})}async markSelectedEmailOtpWalletAuthorityUnlocked(e){await this.markWalletSelectionUnlocked(e)}setWalletAuthenticated(e){let t=this.walletAuthenticationState;t.kind===`authenticated`&&String(t.walletId)!==String(e.walletId)&&this.destroyUnlockedWalletEd25519ExportRootCapabilitiesV1({kind:`wallet`,walletId:String(t.walletId)}),this.walletAuthenticationState=e,this.userPreferencesManager.setCurrentWallet(e.walletId)}clearWalletAuthentication(){this.walletAuthenticationState={kind:`signed_out`},this.destroyUnlockedWalletEd25519ExportRootCapabilitiesV1({kind:`all`})}clearWalletAuthenticationIfCurrent(e){return this.walletAuthenticationState===e?(this.clearWalletAuthentication(),!0):!1}walletCustodyCeremonyTransportV1(){let e=this.getSignerWorkerContext();return{requestOperation:Za.bind(void 0,e)}}async establishUnlockedWalletEd25519ExportRootCapabilityV1(e){try{let t=e.existingEnvelope.binding;if(!ln(t)&&t.kind!==`ed25519_yao_client_root_v1`)return;if(e.existingEnvelope.factor.kind!==`passkey`)throw Error(`unlocked export-root capability requires a passkey envelope factor`);let n=F(e.passkeyPrfFirstB64u);try{await no(this.walletCustodyCeremonyTransportV1(),{existingEnvelope:e.existingEnvelope,existingFactorSecret:n,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,walletSessionId:e.walletSessionId,expiresAtMs:e.expiresAtMs})}finally{n.fill(0)}}catch(e){console.warn(`[BrowserSigningSurface] unlocked Ed25519 export-root capability was not established:`,e instanceof Error?e.message:String(e||`unknown error`))}}async persistUpgradedWalletCustodyEnvelopeV1(e){try{let t=String(this.seamsWebConfigs.network.relayer?.url||``).trim();if(!t)return;let n=_(e.walletId);if(!n.ok)return;let r=(await Hv(n.value,t,new Ja))?.operationCredential.token;if(!r)return;let i=await MD({relayUrl:t,walletId:e.walletId,walletSessionToken:String(r),envelope:e.envelope});if(i.kind===`upgraded`||i.kind===`already_owned`)return;console.warn(`[BrowserSigningSurface] the upgraded custody envelope was not stored:`,i.message)}catch(e){console.warn(`[BrowserSigningSurface] the upgraded custody envelope was not stored:`,e instanceof Error?e.message:String(e||`unknown error`))}}async destroyUnlockedWalletEd25519ExportRootCapabilitiesV1(e){await io(this.walletCustodyCeremonyTransportV1(),e)}async runWarmCriticalResources(e){try{await this.ensureSealedRefreshStartupParity()}catch(e){if(!Od(e))throw e;console.warn(`[BrowserSigningSurface] warmCriticalResources skipped retryable sealed-refresh capability fetch failure`,e instanceof Error?e.message:String(e||`unknown error`))}return await this.enginePorts.getManagerConveniencePorts().warmCriticalResources(e)}async warmCriticalResources(e){if(Kf()&&e===void 0){let e=this.hostWarmCriticalResourcesTask;if(e)return await e;let t=this.runWarmCriticalResources();return this.hostWarmCriticalResourcesTask=t,t.catch(()=>{this.hostWarmCriticalResourcesTask===t&&(this.hostWarmCriticalResourcesTask=null)}),await t}return await this.runWarmCriticalResources(e)}prewarmNearSigner(){this.signerWorkerManager.prewarmNearSigner()}prewarmEmailOtpYao(e){return this.signerWorkerManager.prewarmEmailOtpYao(e)}prewarmEcdsaRegistrationCrypto(){return this.signerWorkerManager.prewarmEcdsaRegistrationCrypto()}getRpId(){return this.touchIdPrompt.getRpId()}getSignerWorkerContext(){return this.enginePorts.walletSessionActivationDeps.getSignerWorkerContext()}getNonceCoordinator(){return this.nonceCoordinator}setAppearance(e){this.appearance=e}setWalletIframeSurfaceMeasurementBinding(e){this.touchConfirm.getContext().surfaceMeasurementBinding=e}getWalletIframeSurfaceMeasurementBinding(){return this.touchConfirm.getContext().surfaceMeasurementBinding}getUserPreferences(){return this.userPreferencesManager}async signNearOwnerTransaction(e,t,n){let r=e.authentication.walletId,i=e.recovery.nearAccountId,a=await Ok(this.enginePorts.nearSigningDeps,this.ed25519YaoPublicCapabilityReferences,{operationId:e.recovery.operationId,walletId:r,nearAccountId:i,relayerUrl:this.seamsWebConfigs.network.relayer.url,assertCurrent:t});return await _f(a,{chain:`near`,kind:`transactionWithActions`,args:{commandSubject:{walletSession:{walletId:r,walletSessionUserId:String(r)},nearAccount:Cn(i)},transaction:e.transaction,rpcCall:{nearRpcUrl:a.nearRpcUrl,nearAccountId:i},onEvent:n}})}async signNear(e){let t=e.args.commandSubject.walletSession.walletId;try{return await _f(this.enginePorts.nearSigningDeps,e)}catch(e){throw Nf(e)&&await this.terminateWalletStateAfterSigningFailure(t),e}}async terminateWalletStateAfterSigningFailure(e){let t=this.readWalletAuthenticationState(),n=!1;try{await this.advanceWalletLockGeneration(e)}catch{}try{await this.retireActiveWalletSessionAuthorizationForLock(e)}catch{}try{n=this.clearWalletAuthenticationIfCurrent(t)}catch{}if(n){try{this.nonceCoordinator.clearAll()}catch{}try{this.clearThresholdEcdsaSigningQueue()}catch{}}try{await this.clearVolatileWarmSigningMaterial(e)}catch{}}async ensureNearEd25519YaoCapabilityForSigning(e){let t=EF(e),n=this.nearEd25519CapabilityRehydrationBySubject.get(t);if(n){let e=await n,t=await this.resolveActiveNearEd25519YaoSigningLane(e.subject);if(t)return t;throw Error(`[SigningEngine][near] joined rehydration did not publish an active lane`)}let r=this.rehydrateNearEd25519YaoCapabilityForSigning(e);this.nearEd25519CapabilityRehydrationBySubject.set(t,r);try{return(await r).material}finally{this.nearEd25519CapabilityRehydrationBySubject.get(t)===r&&this.nearEd25519CapabilityRehydrationBySubject.delete(t)}}async rehydrateExactPasskeyEd25519YaoCapabilityForSigning(e){let t=Ck(e);return await this.ensureNearEd25519YaoCapabilityForSigning(e.laneIdentity===void 0?{kind:`material_identity`,materialIdentity:t}:{kind:`exact_lane`,laneIdentity:e.laneIdentity})}async prepareMaterialIdentityNearEd25519YaoSigning(e){let t=e.materialIdentity;if(t.auth.kind===`voiceid`)return await this.prepareVoiceIdNearSigning(e);let n=this.enginePorts.ed25519YaoActiveClients.resolveForWalletAccount({walletId:t.signer.account.wallet.walletId,nearAccountId:t.signer.account.nearAccountId}),r=await XR({store:this.ed25519YaoPublicCapabilityReferences,identity:t}),i=t.auth.kind===R.passkey?await this.readNearEd25519SigningCandidate(e.walletId):null,a=i?dl(i):null;if(t.auth.kind===R.passkey&&r){let e=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.signer.account.wallet.walletId,nearAccountId:t.signer.account.nearAccountId,materialActivation:r}),n=pz(e);if(e&&n.kind===`live`){if(a?.kind===`authorized`){let e=a.authorization;if(e.selectedAuthMethod.kind!==R.passkey)throw Error(`[SigningEngine][near] active Wallet Session method is unavailable`);return await vl({hydration:oo({authority:await U({authority:e.selectedFactorAuthority}),runtime:n.runtime,materialActivation:r}),requirement:t.auth,authorization:e})}if(a?.kind!==`operation_step_up`)throw a?.kind===`full_login_required`?jf(a.reason):Error(`[SigningEngine][near] Wallet Session status is temporarily unavailable`)}}if(a?.kind===`full_login_required`)throw jf(a.reason);if(a?.kind===`temporarily_unavailable`)throw Error(`[SigningEngine][near] Wallet Session persistence is temporarily unavailable`);if(t.auth.kind===R.passkey&&a?.kind===`operation_step_up`)return gl({hydration:(await yk({access:{kind:`wallet_session`},walletId:e.walletId,identity:t,relayerUrl:this.seamsWebConfigs.network.relayer.url})).prepared.plan,requirement:t.auth});let o=t.auth.kind===R.passkey?await cz({walletId:e.walletId,identity:t}):null,s=o?.sealedRecord.ed25519Restore.materialActivation??(n?fo(n.activeClient.metadata()):r);if(!s)throw J(`missing_capability`);let c=pz(this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.signer.account.wallet.walletId,nearAccountId:t.signer.account.nearAccountId,materialActivation:s})),l;switch(t.auth.kind){case R.passkey:{if(!o)throw J(`missing_runtime`);if(a?.kind!==`authorized`)throw Error(`[SigningEngine][near] exact Passkey authorization is unavailable`);let n={kind:`found`,authorization:a.authorization},r=await Qs({runtime:o,authorization:a.authorization,nowMs:Date.now()}),i=await this.ensurePasskeyEd25519WarmSessionForSigning({runtime:o,walletSessionState:r,materialActivation:s}),u;try{u=await Rv({walletId:e.walletId,runtime:o,authorizationRead:n})}catch{throw J(`binding_mismatch`)}let d=fz(o),f=await ic({store:K,walletId:String(t.signer.account.wallet.walletId),nearAccountId:String(t.signer.account.nearAccountId),nearEd25519SigningKeyId:String(t.signer.nearEd25519SigningKeyId),signerSlot:t.signer.signerSlot,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u,authority:u}),p={kind:`available`,walletId:String(t.signer.account.wallet.walletId),nearAccountId:String(t.signer.account.nearAccountId),signerSlot:t.signer.signerSlot,materialActivation:s,authority:u};l=so({publicLocator:p,sealed:f.kind===`available`?{kind:`available`,authority:f.locator.authority,materialActivation:f.locator.materialActivation,sealedMaterial:f.locator.sealedMaterial}:{kind:`missing`},runtime:c,unlockSource:i.ok?{kind:`available`,authority:u}:{kind:`unavailable`}}),l.kind===`blocked`&&l.reason===`missing_material`&&(l=(await xk({store:K,identity:d,authority:u,publicLocator:p})).plan);break}case R.emailOtp:l=await this.resolveWalletCustodyEmailOtpHydration({walletId:e.walletId,nearAccountId:e.nearAccountId,identity:VR(t),signerSlot:t.signer.signerSlot,materialActivation:s});break;default:throw t.auth,Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}if(l.kind===`blocked`)throw l.reason===`persistence_unavailable`?Error(`[SigningEngine][near] signing material persistence is unavailable`):Mf(l.reason);return gl({hydration:l,requirement:t.auth})}async resolveWalletCustodyEmailOtpHydration(e){let t=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:e.materialActivation}),n=await this.readNearEd25519SigningCandidate(e.walletId),r;if(n.kind===`found`){if(n.authorization.selectedAuthMethod.kind!==R.emailOtp)return lo({capability:e.materialActivation.capability,reason:`missing_material`});if(r=await U({authority:n.authorization.selectedFactorAuthority}),t)return oo({authority:r,runtime:co(e.materialActivation),materialActivation:e.materialActivation})}else if(n.kind===`exhausted`){let n=await HR({walletId:e.walletId,nearAccountId:e.nearAccountId,identity:e.identity,signerSlot:e.signerSlot,materialActivation:e.materialActivation,authorizationRead:{kind:`exhausted`}});if(!n)return lo({capability:e.materialActivation.capability,reason:`missing_material`});if(r=n,t)try{Ek({material:t,input:{walletId:e.walletId,nearAccountId:e.nearAccountId,materialIdentity:e.identity},expectedActivation:e.materialActivation})}catch{return lo({capability:e.materialActivation.capability,reason:`binding_mismatch`})}}else return lo({capability:e.materialActivation.capability,reason:`missing_material`});if(t)return oo({authority:r,runtime:co(e.materialActivation),materialActivation:e.materialActivation});let i=await this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:String(e.nearAccountId),signerSlot:e.signerSlot});return i.kind===`found`&&i.material.binding.walletId===String(e.walletId)&&i.material.binding.nearAccountId===String(e.nearAccountId)&&i.material.binding.signerSlot===e.signerSlot&&String(e.materialActivation.materialOwner)===String(e.walletId)&&(n.kind===`found`||i.material.binding.nearEd25519SigningKeyId===String(e.identity.signer.nearEd25519SigningKeyId)&&i.material.binding.signingWorkerId===String(e.materialActivation.signingWorker))?go({authority:r,materialActivation:e.materialActivation,sealedMaterial:tv(JSON.stringify([i.material.binding.walletId,i.material.binding.nearAccountId,i.material.binding.signerSlot,e.materialActivation.activationId]))}):lo({capability:e.materialActivation.capability,reason:`missing_material`})}async rehydrateActiveEmailOtpEd25519YaoSessionMaterial(e){let t=gz(e.input);if(t.auth.kind!==R.emailOtp)throw Error(`[SigningEngine][near] Email OTP session restore requires Email OTP material`);let n=await tz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:t.laneIdentity,materialActivation:e.materialActivation}),r=await this.getUserBySignerSlot(t.nearAccountId,t.laneIdentity.signer.signerSlot);if(!r||String(r.walletId)!==String(t.walletId)||String(r.nearAccountId)!==String(t.nearAccountId)||r.signerSlot!==t.laneIdentity.signer.signerSlot||r.authMethod!==R.emailOtp)throw Error(`[SigningEngine][near] Email OTP signer record is unavailable`);let i=await this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:String(t.nearAccountId),signerSlot:r.signerSlot}),a=e.authorization.operationCredential;if(i.kind!==`found`)throw Error(`[SigningEngine][near] Email OTP session material is unavailable`);let o=await NR(e.authorization,e.remainingUses),s=await this.signerWorkerManager.requestWorkerOperation({kind:`emailOtp`,request:{type:`rehydrateActiveEmailOtpEd25519YaoSessionMaterial`,payload:{relayUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim(),walletId:String(t.walletId),walletAuthMethodId:String(e.authorization.selectedAuthMethod.walletAuthMethodId),orgId:n.runtimePolicyScope.orgId,providerSubjectId:t.auth.providerSubjectId,nearAccountId:String(t.nearAccountId),signerSlot:r.signerSlot,remainingUses:e.remainingUses,expectedOperationalPublicKey:r.operationalPublicKey,expectedThresholdSessionId:n.thresholdSessionId,operationCredential:a,ecdsa:o,walletCustodyEd25519Material:i}}});switch(s.ecdsa.kind){case`activated`:if(o.kind!==`required`)throw Error(`NEAR-only restore returned ECDSA activation`);await FR({walletId:t.walletId,authorization:s.walletSessionAuthorization,response:s.ecdsa.session});break;case`absent`:if(o.kind!==`absent`)throw Error(`Combined restore omitted ECDSA activation`);break;default:throw s.ecdsa,Error(`Unsupported Email OTP restore result`)}return await this.activateEmailOtpEd25519CustodyCapabilityInternal({commitQueue:`acquire`,walletSession:{walletId:t.walletId,walletSessionUserId:String(t.walletId)},providerSubject:t.auth.providerSubjectId,emailHashHex:await j(r.loginDisplayName.trim().toLowerCase()),signerSlot:r.signerSlot,expectedOperationalPublicKey:r.operationalPublicKey,expectedThresholdSessionId:String(n.thresholdSessionId),bootstrap:s.bootstrap,activeClientHandle:s.activeClientHandle,metadata:s.metadata,exactAuthorization:s.walletSessionAuthorization}),s.ecdsa.kind===`absent`&&await q.writeExactWithOperationCredential({record:s.walletSessionAuthorization.record,operationCredential:s.walletSessionAuthorization.operationCredential}),oo({authority:await U({authority:e.authorization.selectedFactorAuthority}),runtime:co(e.materialActivation),materialActivation:e.materialActivation})}async prepareExactNearEd25519YaoSigning(e){if(e.auth?.kind===`voiceid`||e.materialIdentity?.auth.kind===`voiceid`)return await this.prepareVoiceIdNearSigning(e);if(e.laneIdentity!==void 0&&e.auth?.kind===R.emailOtp){let t=await this.prepareMaterialIdentityNearEd25519YaoSigning(_z(e)),n=await this.readNearEd25519SigningCandidate(e.walletId);if(n.kind!==`found`||n.authorization.selectedAuthMethod.kind!==R.emailOtp)return t;let r=n.authorization;switch(t.hydration.kind){case`use_live_runtime`:break;case`rehydrate_material_activation`:t=gl({hydration:await this.rehydrateActiveEmailOtpEd25519YaoSessionMaterial({input:e,materialActivation:t.hydration.materialActivation,authorization:r,remainingUses:r.status.remainingUses}),requirement:e.auth});break;case`reauthorize_public_anchor`:case`blocked`:return t;default:throw t.hydration,Error(`[SigningEngine][near] unsupported Email OTP hydration state`)}let i=await this.readNearEd25519SigningCandidate(e.walletId);return i.kind!==`found`||i.authorization.selectedAuthMethod.kind!==R.emailOtp?t:await vl({hydration:t.hydration,requirement:e.auth,authorization:i.authorization})}if(e.laneIdentity===void 0)return await this.prepareMaterialIdentityNearEd25519YaoSigning(e);let t=await this.readNearEd25519SigningCandidate(e.walletId);switch(t.kind){case`found`:{let n=t.authorization;if(n.selectedAuthMethod.kind!==e.auth.kind)return await this.prepareMaterialIdentityNearEd25519YaoSigning(_z(e));let r=await vc({walletId:e.walletId,laneIdentity:e.laneIdentity});if(r.kind===`missing`&&e.auth.kind===R.passkey){let t=await nz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:e.laneIdentity}),r=t.materialActivation,i=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:r});if(!i)throw Error(`[SigningEngine][near] active Passkey Ed25519 material is unavailable`);let a=Ek({material:i,input:e,expectedActivation:r}),o=await az({reference:t,material:a,authorization:n,materialActivation:r,relayerUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim()}),s=pz(a);if(s.kind!==`live`)throw Error(`[SigningEngine][near] active Passkey Ed25519 material is unavailable`);return await vl({hydration:oo({authority:o.authority,runtime:s.runtime,materialActivation:r}),requirement:e.auth,authorization:n})}if(r.kind!==`resolved`)throw Error(`[SigningEngine][near] exact persisted Ed25519 runtime is ${r.kind}`);let i=r.runtime,a=i.sealedRecord.ed25519Restore.materialActivation,o=await Qs({runtime:i,authorization:n,nowMs:Date.now()}),s=o.signingLane.identity.signer,c={kind:`available`,walletId:String(s.account.wallet.walletId),nearAccountId:String(s.account.nearAccountId),signerSlot:s.signerSlot,materialActivation:a},l=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:s.account.wallet.walletId,nearAccountId:s.account.nearAccountId,materialActivation:a}),u=e.auth.kind===R.passkey?await this.passkeyMpcSession.claimWarmSessionMaterial({thresholdSessionId:i.thresholdSessionId,purpose:{curve:`ed25519`,materialActivation:a},consume:!1}):null,d={kind:`unavailable`};u?.ok===!0&&(d={kind:`available`,passkeyPrfFirstB64u:u.prfFirstB64u});let f=await this.resolveExactNearEd25519YaoSigningHydration({args:e,walletSessionState:o,publicLocator:c,runtime:pz(l),unlockSource:d});if(f.kind===`use_live_runtime`){if(!l)throw Error(`[SigningEngine][near] live Ed25519 material is unavailable`);await Cz({input:e,authorization:n,sealedRuntime:i,material:l})}return await vl({hydration:f,requirement:e.auth,authorization:n})}case`missing`:case`expired`:case`exhausted`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:case`unavailable`:return await this.prepareMaterialIdentityNearEd25519YaoSigning(_z(e));case`upgrade_required`:throw new Ra(`[SigningEngine][near] Wallet Session authorization requires a newer client`);case`corrupt`:case`persistence_unavailable`:throw Error(`[SigningEngine][near] Wallet Session authorization is ${t.kind}`);default:throw Error(`[SigningEngine][near] unsupported Wallet Session authorization state`)}}async prepareExactNearEd25519YaoMaterialBoundary(e){Sz(e);let t=await this.prepareExactNearEd25519YaoSigning(e),n={input:e,materialActivation:t.hydration.materialActivation||null};return{preparation:t,executor:{resolveSigningKeyMaterial:this.resolveExactNearEd25519SigningKeyMaterial.bind(this,n),resolve:this.resolveExactNearEd25519YaoPreparedMaterial.bind(this,n),resolveWalletSessionState:this.resolveExactNearEd25519YaoWalletSessionState.bind(this,n),resolveFundingSession:this.resolveExactNearEd25519FundingSession.bind(this,n),preparePasskeyOperationStepUp:this.prepareExactNearEd25519YaoOperationStepUpAtBoundary.bind(this,n),prepareEmailOtpOperationStepUp:this.prepareExactNearEmailOtpEd25519YaoOperationStepUpAtBoundary.bind(this,n)}}}async resolveExactNearEd25519SigningKeyMaterial(e){let t=Ck(e.input),n=t.signer,r=t.auth,i=e.materialActivation;if(!i)throw Error(`[SigningEngine][near] prepared material has no activation`);if(String(n.account.wallet.walletId)!==String(e.input.walletId)||String(n.account.nearAccountId)!==String(e.input.nearAccountId))throw Error(`[SigningEngine][near] selected Ed25519 lane identity changed`);let a=await K.resolveSelectedWalletAuthority(String(e.input.walletId));if(a.kind!==`resolved`){let e=a.kind===`integrity_error`?`: ${a.reason}`:``;throw Error(`[SigningEngine][near] selected Wallet Authority is ${a.kind}${e}`)}let{selection:o,authMethod:s,authority:c,signerMaterials:l}=a,u;switch(r.kind){case`voiceid`:u=s.kind===`voiceid`&&s.walletAuthMethodId===r.walletAuthMethodId&&s.deviceKeyId===r.deviceKeyId;break;case R.passkey:u=s.kind===R.passkey&&String(s.rpId)===String(r.rpId)&&s.credentialIdB64u===r.credentialIdB64u;break;case R.emailOtp:u=s.kind===R.emailOtp;break;default:throw Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}if(o.lockState!==`unlocked`||c.state!==`active`||s.status!==`active`||String(o.walletId)!==String(e.input.walletId)||o.walletAuthMethodId!==s.walletAuthMethodId||s.walletAuthorityId!==c.authorityId||String(s.walletId)!==String(e.input.walletId)||!u)throw Error(`[SigningEngine][near] selected Wallet Authority does not match the lane`);let d=await Th({selected:{authMethod:s,authority:c},operation:{kind:`near_sign`,operation:`sign`,keyFamily:`ed25519`}});if(d.kind!==`resolved`)throw Error(`[SigningEngine][near] selected Wallet Authority rejected signing (${d.reason.kind})`);let f=d.value;if(f.keyFamily!==`ed25519`||String(f.walletId)!==String(e.input.walletId)||f.authMethodId!==s.walletAuthMethodId||!g(f.materialActivation,i))throw Error(`[SigningEngine][near] selected Wallet Authority activation changed`);if(c.signerActivations.keyFamilies[0]!==`ed25519`||c.signerActivations.ed25519===void 0||!g(c.signerActivations.ed25519.materialActivation,i)||c.signerActivations.ed25519.signer.registeredPublicKeyB64u!==f.registeredPublicKeyB64u)throw Error(`[SigningEngine][near] selected Ed25519 authority activation changed`);let p=F(f.registeredPublicKeyB64u);if(p.byteLength!==32)throw Error(`[SigningEngine][near] selected Ed25519 public key is invalid`);let m=i.signingWorker,h=[1,2],_=null;if(c.provenance.kind===`device_link`){await rz({store:this.ed25519YaoPublicCapabilityReferences,identity:t,materialActivation:i});for(let e of l)if(!(!QR(e)||e.authorityId!==c.authorityId||e.walletAuthMethodId!==s.walletAuthMethodId||!g(e.materialActivation,i))){if(_)throw Error(`[SigningEngine][near] linked Ed25519 signer material is ambiguous`);_=e}if(!_)throw Error(`[SigningEngine][near] linked Ed25519 signer material is unavailable`);let a=_.publicFacts.applicationBinding,o=_.publicFacts.targetBinding,u=o.lifecycle,d=_.targetFactor,p;switch(r.kind){case`voiceid`:throw Error(`VoiceID unlock requires owner custody on this device.`);case R.passkey:p=d.kind===R.passkey&&d.walletAuthMethodId===s.walletAuthMethodId&&String(d.rpId)===String(r.rpId)&&d.credentialIdB64u===r.credentialIdB64u;break;case R.emailOtp:p=d.kind===R.emailOtp&&s.kind===R.emailOtp&&d.walletAuthMethodId===s.walletAuthMethodId&&d.emailHashHex===s.emailHashHex;break;default:throw Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}if(a.wallet_id!==String(e.input.walletId)||a.near_ed25519_signing_key_id!==String(n.nearEd25519SigningKeyId)||a.key_creation_signer_slot!==n.signerSlot||u.account_id!==String(e.input.walletId)||u.session_id!==String(t.thresholdSessionId)||u.selected_server_id!==String(m)||!g(ii(o.material_activation),i)||!g(ii(_.publicFacts.activationReceipt.material_activation),i)||P(Uint8Array.from(_.publicFacts.activationReceipt.registered_public_key))!==f.registeredPublicKeyB64u||!p)throw Error(`[SigningEngine][near] linked Ed25519 signer identity changed`);h=_.publicFacts.participantIds}let v=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.input.walletId,nearAccountId:e.input.nearAccountId,materialActivation:i});if(v){let r=Ek({material:v,input:e.input,expectedActivation:i}),a=r.activeClient.metadata(),o=r.facts;if(P(a.registeredPublicKey)!==f.registeredPublicKeyB64u||a.participantIds[0]!==h[0]||a.participantIds[1]!==h[1]||a.applicationBinding.wallet_id!==String(e.input.walletId)||a.applicationBinding.near_ed25519_signing_key_id!==String(n.nearEd25519SigningKeyId)||a.applicationBinding.key_creation_signer_slot!==n.signerSlot||a.scope.account_id!==String(e.input.walletId)||a.scope.threshold_session_id!==String(t.thresholdSessionId)||a.scope.signing_worker_id!==String(m)||o.routerAbNormalSigning.signingWorkerId!==String(m)||o.signingRootId!==a.applicationBinding.signing_root_id||o.signingRootVersion!==a.scope.root_share_epoch)throw Error(`[SigningEngine][near] active Ed25519 public material changed`);if(_){let e=_.publicFacts.applicationBinding,t=_.publicFacts.targetBinding.lifecycle;if(a.applicationBinding.wallet_id!==e.wallet_id||a.applicationBinding.near_ed25519_signing_key_id!==e.near_ed25519_signing_key_id||a.applicationBinding.signing_root_id!==e.signing_root_id||a.applicationBinding.key_creation_signer_slot!==e.key_creation_signer_slot||a.scope.lifecycle_id!==t.lifecycle_id||a.scope.root_share_epoch!==t.root_share_epoch||a.scope.account_id!==t.account_id||a.scope.threshold_session_id!==t.session_id||a.scope.signing_worker_id!==t.selected_server_id)throw Error(`[SigningEngine][near] linked Ed25519 runtime identity changed`)}}let y=`ed25519:${tn(p)}`;return{nearAccountId:e.input.nearAccountId,signerSlot:n.signerSlot,kind:`threshold_ed25519_v1`,publicKey:y,relayerKeyId:m,keyVersion:da,participants:ce({clientParticipantId:h[0],relayerParticipantId:h[1],relayerKeyId:m,clientShareDerivation:`prf_first_v1`}),timestamp:c.activatedAtMs}}async resolveExactNearEd25519YaoPreparedMaterial(e,t){let n=Tz({context:e,preparation:t});switch(t.hydration.kind){case`use_live_runtime`:{let t=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.input.walletId,nearAccountId:e.input.nearAccountId,materialActivation:n});if(!t)throw Error(`[SigningEngine][near] active Ed25519 Yao capability is unavailable`);return Ek({material:t,input:e.input,expectedActivation:n})}case`rehydrate_material_activation`:{let t=gz(e.input);switch(t.auth.kind){case`voiceid`:throw Error(`Unlock with VoiceID again to restore signing material.`);case R.passkey:{let e=await this.rehydrateExactPasskeyEd25519YaoCapabilityForSigning(t);try{let r=await this.readNearEd25519SigningCandidate(t.walletId);if(r.kind!==`found`||r.authorization.selectedAuthMethod.kind!==R.passkey)throw Error(`[SigningEngine][near] Wallet Session authorization is ${r.kind}`);let i=await oz({walletId:t.walletId,laneIdentity:t.laneIdentity});return await Cz({input:t,authorization:r.authorization,sealedRuntime:i,material:e}),Ek({material:e,input:t,expectedActivation:n})}catch(t){throw e.activeClient.dispose(),t}}case R.emailOtp:throw Error(`[SigningEngine][near] Email OTP custody cache is unavailable; link the device before signing`);default:throw t.auth,Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}}case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired material requires reauthorization`);case`blocked`:throw Error(`[SigningEngine][near] prepared material is blocked: ${t.hydration.reason}`);default:throw t.hydration,Error(`[SigningEngine][near] unsupported prepared material hydration`)}}async resolveExactNearEd25519YaoWalletSessionState(e){let t=gz(e.input);if(t.auth.kind===`voiceid`){let e=this.voiceIdNearSessions.get(t.walletId);if(!e||e.walletSessionId!==t.laneIdentity.walletSessionId)throw Error(`Unlock with VoiceID again before signing.`);return e}if(t.auth.kind===R.emailOtp){if(!e.materialActivation)throw Error(`[SigningEngine][near] prepared material has no activation`);let n=await tz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:t.laneIdentity,materialActivation:e.materialActivation}),r=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.walletId,nearAccountId:t.nearAccountId,materialActivation:e.materialActivation});if(!r)throw Error(`[SigningEngine][near] active Email OTP Ed25519 material is unavailable`);let i=await this.readNearEd25519SigningCandidate(t.walletId);if(i.kind!==`found`||i.authorization.selectedAuthMethod.kind!==R.emailOtp)throw Error(`[SigningEngine][near] Wallet Session authorization is ${i.kind}`);return await vz({reference:n,material:Ek({material:r,input:t,expectedActivation:e.materialActivation}),authorization:i.authorization,materialActivation:e.materialActivation,relayerUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim()})}let n=await vc({walletId:t.walletId,laneIdentity:t.laneIdentity});if(n.kind===`missing`&&t.auth.kind===R.passkey){if(!e.materialActivation)throw Error(`[SigningEngine][near] prepared material has no activation`);let n=await nz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:t.laneIdentity});if(!g(n.materialActivation,e.materialActivation))throw Error(`[SigningEngine][near] Passkey public lane activation changed`);let r=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.walletId,nearAccountId:t.nearAccountId,materialActivation:e.materialActivation});if(!r)throw Error(`[SigningEngine][near] active Passkey Ed25519 material is unavailable`);let i=Ek({material:r,input:t,expectedActivation:e.materialActivation}),a=await this.readNearEd25519SigningCandidate(t.walletId);if(a.kind!==`found`||a.authorization.selectedAuthMethod.kind!==R.passkey)throw Error(`[SigningEngine][near] Wallet Session authorization is ${a.kind}`);return await az({reference:n,material:i,authorization:a.authorization,materialActivation:e.materialActivation,relayerUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim()})}if(n.kind!==`resolved`)throw Error(`[SigningEngine][near] exact persisted Ed25519 runtime is ${n.kind}`);let r=n.runtime,i=await this.readNearEd25519SigningCandidate(t.walletId);if(i.kind!==`found`)throw Error(`[SigningEngine][near] Wallet Session authorization is ${i.kind}`);return await Qs({runtime:r,authorization:i.authorization,nowMs:Date.now()})}async resolveExactNearEd25519FundingSession(e){let t=Ck(e.input),n=await this.readExactNearEd25519WalletSessionAuthorization(t.signer.account.wallet.walletId);if(n.kind!==`found`||n.authorization.selectedAuthMethod.kind!==t.auth.kind)throw Error(`[SigningEngine][near] authenticated funding session is unavailable`);if(!e.materialActivation)throw Error(`[SigningEngine][near] funding session material activation is unavailable`);if(!ol({session:n.authorization.session,materialActivation:e.materialActivation}))throw Error(`[SigningEngine][near] authenticated funding session material changed`);let r=n.authorization.operationCredential.token;if(n.authorization.session.walletId!==t.signer.account.wallet.walletId||n.authorization.selectedAuthMethod.kind!==t.auth.kind||!n.authorization.operationCredential.walletSessionId||!n.authorization.session.quotaId)throw Error(`[SigningEngine][near] funding session identity does not match`);return{kind:`near_ed25519_funding_session`,signer:t.signer,thresholdSessionId:t.thresholdSessionId,walletSessionToken:r}}async prepareExactNearEd25519YaoOperationStepUpAtBoundary(e,t){if(hz(e.input).kind!==R.passkey)throw Error(`[SigningEngine][near] Email OTP material cannot use Passkey rehydration`);let n=Tz({context:e,preparation:t}),r=await this.prepareExactPasskeyEd25519YaoOperationStepUpForSigning(e.input);if(!g(n,r.materialActivation))throw Error(`[SigningEngine][near] operation step-up changed material activation`);return r}async prepareExactNearEmailOtpEd25519YaoOperationStepUpAtBoundary(e,t){let n=Ck(e.input);if(n.auth.kind!==R.emailOtp)throw Error(`[SigningEngine][near] Passkey material cannot use Email OTP rehydration`);let r=Tz({context:e,preparation:t});switch(t.hydration.kind){case`use_live_runtime`:return{kind:`live`,materialActivation:r,material:await this.resolveExactNearEd25519YaoPreparedMaterial(e,t)};case`rehydrate_material_activation`:{let t=await tz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:n,materialActivation:r}),i=await this.getUserBySignerSlot(e.input.nearAccountId,n.signer.signerSlot);if(!i||String(i.walletId)!==String(e.input.walletId)||String(i.nearAccountId)!==String(e.input.nearAccountId)||i.signerSlot!==n.signer.signerSlot||i.authMethod!==R.emailOtp)throw Error(`[SigningEngine][near] Email OTP signer record is unavailable`);let a=await this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:String(e.input.nearAccountId),signerSlot:i.signerSlot});if(a.kind!==`found`)throw Error(`[SigningEngine][near] Email OTP custody material is unavailable`);if(`ed25519:${tn(F(a.material.binding.registeredPublicKeyB64u))}`!==i.operationalPublicKey||a.material.binding.walletId!==String(e.input.walletId)||a.material.binding.nearAccountId!==String(e.input.nearAccountId)||a.material.binding.signerSlot!==i.signerSlot||a.material.binding.signingWorkerId!==String(r.signingWorker))throw Error(`[SigningEngine][near] Email OTP custody material binding changed`);let o=this.seamsWebConfigs.network.relayer?.url||``;if(!o)throw Error(`[SigningEngine][near] Email OTP recovery requires a relay URL`);let s={input:e.input,materialActivation:r,facts:xz({input:e.input,publicLane:t,relayerUrl:o}),publicLane:t,sealedMaterial:a.material,operationalPublicKey:i.operationalPublicKey,emailHashHex:await j(i.loginDisplayName.trim().toLowerCase())};return{kind:`sealed`,materialActivation:r,facts:s.facts,authorizeAndRehydrate:this.authorizeAndRehydrateEmailOtpEd25519OperationMaterial.bind(this,s)}}case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired Email OTP material cannot sign`);case`blocked`:throw Error(`[SigningEngine][near] Email OTP operation material is blocked: ${t.hydration.reason}`);default:throw t.hydration,Error(`[SigningEngine][near] unsupported Email OTP operation material`)}}async authorizeAndRehydrateEmailOtpEd25519OperationMaterial(e,t){let n=Ck(e.input);if(n.auth.kind!==R.emailOtp||t.proof.providerSubjectId!==n.auth.providerSubjectId)throw Error(`[SigningEngine][near] Email OTP operation authority changed`);let r=await uz({walletId:e.input.walletId,proof:t.proof}),i={kind:`exact_ed25519_export_material`,signer:n.signer,auth:n.auth,thresholdSessionId:n.thresholdSessionId},a=await RP({subject:i,expectedMaterialActivation:e.materialActivation,authorization:await this.readExactEmailOtpEd25519ExportAuthorization({subject:i,expectedMaterialActivation:e.materialActivation}),source:{signingWorkerId:e.sealedMaterial.binding.signingWorkerId,participantIds:e.sealedMaterial.binding.participantIds,registeredPublicKeyB64u:e.sealedMaterial.binding.registeredPublicKeyB64u},relayerUrl:e.facts.relayerUrl,fetch:globalThis.fetch.bind(globalThis)}),o=await XP({workerCtx:this.signerWorkerManager.getContext(),payload:{relayUrl:e.facts.relayerUrl,walletId:String(e.input.walletId),orgId:e.publicLane.runtimePolicyScope.orgId,providerSubjectId:n.auth.providerSubjectId,nearAccountId:String(e.input.nearAccountId),signerSlot:e.publicLane.signerSlot,expectedOperationalPublicKey:e.operationalPublicKey,expectedThresholdSessionId:e.publicLane.thresholdSessionId,expectedMaterialActivation:e.materialActivation,ed25519YaoRecovery:{kind:Yr,signerSlot:e.publicLane.signerSlot,remainingUses:xe,orgId:e.publicLane.runtimePolicyScope.orgId},walletCustodyEd25519Material:{kind:`found`,material:e.sealedMaterial},bootstrap:a,normalSigningRequest:t.normalSigningRequest,displayDigest:t.displayDigest,proof:t.proof,operationCredential:r}});if(o.walletCustodyEd25519Material)try{await this.persistWalletCustodyEd25519Material(o.walletCustodyEd25519Material)}catch(e){throw await Fy({workerContext:this.signerWorkerManager.getContext(),activeClientHandle:o.activeClientHandle}).catch(()=>void 0),e}let s=new Iy(this.signerWorkerManager.getContext(),o.activeClientHandle,o.metadata),c;try{c=Ek({material:{activeClient:s,facts:e.facts},input:e.input,expectedActivation:e.materialActivation})}catch(e){throw s.dispose(),e}return{material:c,issuedAuthorization:{kind:o.issuedAuthorization.kind,authorization:o.issuedAuthorization.authorization,expiresAtMs:o.issuedAuthorization.expiresAtMs}}}async resolveExactNearEd25519YaoSigningHydration(e){let t=gz(e.args);switch(t.auth.kind){case`voiceid`:throw Error(`Unlock with VoiceID again before signing.`);case R.passkey:{let n=await this.resolvePasskeyEd25519YaoHydration({walletSessionState:e.walletSessionState,credentialIdB64u:t.auth.credentialIdB64u,publicLocator:e.publicLocator,unlockSource:e.unlockSource}),r;switch(n.kind){case`live`:case`blocked`:r=n.plan;break;case`rehydrated`:n.activeClient.dispose(),r=n.plan;break;default:throw Error(`[SigningEngine][near] unsupported Passkey hydration result`)}return r.kind===`blocked`&&r.reason===`missing_material`?(await Qo({store:K,identity:_s(e.walletSessionState,t.auth.rpId,t.auth.credentialIdB64u),authority:e.walletSessionState.authority,publicLocator:e.publicLocator})).plan:r}case R.emailOtp:if(e.publicLocator.kind!==`available`)throw Error(`[SigningEngine][near] Email OTP custody locator is unavailable`);return await this.resolveWalletCustodyEmailOtpHydration({walletId:t.walletId,nearAccountId:t.nearAccountId,identity:VR(Ck(t)),signerSlot:t.laneIdentity.signer.signerSlot,materialActivation:e.publicLocator.materialActivation});default:throw t.auth,Error(`[SigningEngine][near] unsupported Ed25519 material authority`)}}async prepareExactPasskeyEd25519YaoOperationStepUpForSigning(e){let t=Ck(e);if(t.auth.kind!==R.passkey)throw Error(`[SigningEngine][near] Passkey operation step-up requires Passkey material`);if(!await this.resolveNearEd25519YaoSigningLane({...e.laneIdentity===void 0?{kind:`material_identity`,materialIdentity:t}:{kind:`exact_lane`,laneIdentity:e.laneIdentity}}))throw Error(`[SigningEngine][near] sealed Ed25519 operation lane is unavailable`);let n=await yk({access:{kind:`wallet_session`},walletId:e.walletId,identity:t,relayerUrl:this.seamsWebConfigs.network.relayer.url});return{materialActivation:n.prepared.plan.materialActivation,facts:n.facts,participantIds:[...n.participantIds],rehydrate:Dk.bind(null,{access:{kind:`wallet_session`},input:e,identity:n.localIdentity,facts:n.facts,authority:n.authority,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u,publicLocator:n.publicLocator,materialActivation:n.prepared.plan.materialActivation})}}async resolveExactPasskeyEd25519YaoExportContext(e){let t=String(this.seamsWebConfigs.network.relayer?.url||``).trim();if(!t)throw Error(`[SigningEngine][ed25519-export] passkey export requires relayerUrl`);let n=V(String(e.laneIdentity.signer.account.wallet.walletId));if(!await Bo(Wd({authMethod:e.laneIdentity.auth.kind,materialActivation:e.materialActivation})))return await this.resolveLinkedPasskeyEd25519YaoExportContext({...e,walletId:n,relayerUrl:t});let r=await sz({walletId:n,laneIdentity:e.laneIdentity,materialActivation:e.materialActivation}),i=e.laneIdentity.thresholdSessionId,a=await Hv(r.walletId,t,new Ja);if(a){let t=await Qs({runtime:r,authorization:a,nowMs:Date.now()});(await this.ensurePasskeyEd25519WarmSessionForSigning({runtime:r,walletSessionState:t,materialActivation:e.materialActivation})).ok&&(i=t.thresholdSessionId)}return await lF({subject:{kind:`owner_sealed_runtime`,walletId:V(String(e.laneIdentity.signer.account.wallet.walletId)),nearAccountId:String(e.laneIdentity.signer.account.nearAccountId),nearEd25519SigningKeyId:String(e.laneIdentity.signer.nearEd25519SigningKeyId),signerSlot:e.laneIdentity.signer.signerSlot,thresholdSessionId:i,materialActivation:e.materialActivation},relayerUrl:t,fetch:KR},{readExactEd25519SealedSession:Bo,readPasskeyCustodySessionEnvelope:zs,resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),readExactWalletSessionAuthorization:q.readExactActiveForWallet.bind(q),resolveExactPasskeyWalletAuthAuthorityRef:vk,nowMs:this.runtimePorts.clock.nowMs})}async resolveLinkedPasskeyEd25519YaoExportContext(e){if(e.laneIdentity.auth.kind!==R.passkey)throw Error(`[SigningEngine][ed25519-export] linked export requires a Passkey lane`);let t=await K.resolveSelectedWalletAuthority(String(e.walletId));if(t.kind!==`resolved`){let e=t.kind===`integrity_error`?`: ${t.reason}`:``;throw Error(`[SigningEngine][ed25519-export] selected Wallet Authority is ${t.kind}${e}`)}let{selection:r,authMethod:i,authority:a,signerMaterials:o,exportRoot:s}=t;if(r.lockState!==`unlocked`||i.kind!==R.passkey||i.status!==`active`||a.state!==`active`||a.provenance.kind!==`device_link`||String(i.walletId)!==String(e.walletId)||i.walletAuthorityId!==a.authorityId||i.walletAuthMethodId!==r.walletAuthMethodId||String(i.rpId)!==String(e.laneIdentity.auth.rpId)||i.credentialIdB64u!==e.laneIdentity.auth.credentialIdB64u)throw Error(`[SigningEngine][ed25519-export] selected linked Passkey authority is unavailable`);let c=a.signerActivations.ed25519;if(!a.permissions.includes(`export_keys`)||!c||!g(c.materialActivation,e.materialActivation)||!s)throw Error(`[SigningEngine][ed25519-export] selected authority has no exact Ed25519 export capability`);let l=null;for(let t of o)if(!(!QR(t)||t.authorityId!==a.authorityId||t.walletAuthMethodId!==i.walletAuthMethodId||!g(t.materialActivation,e.materialActivation))){if(l)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 material is ambiguous`);l=t}if(!l)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 material is unavailable`);let u=l.targetFactor;if(u.kind!==R.passkey||u.walletAuthMethodId!==i.walletAuthMethodId||u.rpId!==i.rpId||u.credentialIdB64u!==i.credentialIdB64u)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 factor binding changed`);let d=Ay(await q.readExactWithOperationCredential({walletId:e.walletId,authorityId:a.authorityId,authMethodId:i.walletAuthMethodId}),`[SigningEngine][ed25519-export] exact linked Wallet Session requires a newer client`),f=!1;if(d){for(let t of d.record.capabilitySubjects)if(t.kind===`export_keys`&&t.keyFamily===`ed25519`&&g(t.materialActivation,e.materialActivation)){f=!0;break}}if(!d||!f||d.record.authorityDigestB64u!==a.authorityDigestB64u||d.record.authorityRevocationEpoch!==a.revocationEpoch||d.record.expiresAtMs<=Date.now())throw Error(`[SigningEngine][ed25519-export] exact linked Wallet Session is unavailable`);let p=await nz({store:this.ed25519YaoPublicCapabilityReferences,laneIdentity:e.laneIdentity});if(!g(p.materialActivation,e.materialActivation))throw Error(`[SigningEngine][ed25519-export] linked public lane activation changed`);let m=await U({authority:{walletId:i.walletId,factor:{kind:R.passkey,credentialIdB64u:i.credentialIdB64u},verifier:{kind:`webauthn`,rpId:i.rpId},bindingId:i.walletAuthMethodId}});if(m.walletAuthMethodId!==i.walletAuthMethodId)throw Error(`[SigningEngine][ed25519-export] Passkey Wallet Session authority changed`);let h=this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e.walletId,nearAccountId:e.laneIdentity.signer.account.nearAccountId,materialActivation:e.materialActivation});if(!h||h.activeClient.status().kind!==`active`)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 runtime is unavailable`);let _=h.activeClient.metadata(),v=fo(_),y=h.facts,b=e.laneIdentity.signer,x=l.publicFacts.applicationBinding,S=P(_.registeredPublicKey),C=Number(_.stateEpoch),w=n(_.scope.threshold_session_id),T=y.runtimePolicyScope,E=p.runtimePolicyScope;if(!w.ok||!Number.isSafeInteger(C)||C<1||!g(v,e.materialActivation)||String(y.thresholdSessionId)!==String(e.laneIdentity.thresholdSessionId)||String(y.signer.account.wallet.walletId)!==String(e.walletId)||String(y.signer.account.nearAccountId)!==String(b.account.nearAccountId)||String(y.signer.nearEd25519SigningKeyId)!==String(b.nearEd25519SigningKeyId)||y.signer.signerSlot!==b.signerSlot||x.wallet_id!==String(e.walletId)||x.near_ed25519_signing_key_id!==String(b.nearEd25519SigningKeyId)||x.key_creation_signer_slot!==b.signerSlot||_.applicationBinding.wallet_id!==x.wallet_id||_.applicationBinding.near_ed25519_signing_key_id!==x.near_ed25519_signing_key_id||_.applicationBinding.signing_root_id!==x.signing_root_id||_.applicationBinding.key_creation_signer_slot!==x.key_creation_signer_slot||_.scope.lifecycle_id!==l.publicFacts.targetBinding.lifecycle.lifecycle_id||_.scope.root_share_epoch!==l.publicFacts.targetBinding.lifecycle.root_share_epoch||_.scope.account_id!==String(e.walletId)||_.scope.threshold_session_id!==String(e.laneIdentity.thresholdSessionId)||_.scope.signing_worker_id!==y.routerAbNormalSigning.signingWorkerId||y.signingRootId!==x.signing_root_id||y.signingRootVersion!==_.scope.root_share_epoch||T.orgId!==E.orgId||T.projectId!==E.projectId||T.envId!==E.envId||T.signingRootVersion!==E.signingRootVersion||l.publicFacts.participantIds[0]!==_.participantIds[0]||l.publicFacts.participantIds[1]!==_.participantIds[1]||P(Uint8Array.from(l.publicFacts.activationReceipt.registered_public_key))!==S||c.signer.registeredPublicKeyB64u!==S)throw Error(`[SigningEngine][ed25519-export] linked Ed25519 runtime identity changed`);let D={authority:m,walletId:b.account.wallet.walletId,nearAccountId:b.account.nearAccountId,nearEd25519SigningKeyId:String(b.nearEd25519SigningKeyId),signerSlot:b.signerSlot,operationalPublicKey:`ed25519:${tn(_.registeredPublicKey)}`,relayerKeyId:_.scope.signing_worker_id,credentialIdB64u:i.credentialIdB64u,capability:{materialActivation:v,activeCapabilityBinding:[..._.activeCapabilityBinding],registeredPublicKey:[..._.registeredPublicKey],nearAccountId:b.account.nearAccountId,applicationBinding:_.applicationBinding,participantIds:_.participantIds,runtimePolicyScope:y.runtimePolicyScope,lifecycle:{lifecycleId:_.scope.lifecycle_id,rootShareEpoch:_.scope.root_share_epoch,accountId:_.scope.account_id,thresholdSessionId:w.value,signerSetId:_.scope.signer_set_id,signingWorkerId:_.scope.signing_worker_id},stateEpoch:C}};return{kind:`ready`,context:{kind:`passkey_ed25519_yao_export_context_v1`,selectedLaneMaterialActivation:e.materialActivation,material:D,authorization:d,relayerUrl:e.relayerUrl,rpId:i.rpId,walletCustodyEnvelope:s.envelope}}}readExactEmailOtpEd25519ExportAuthorization(e){return GR({subject:e.subject,relayerUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim()})}async activateRecoveredEmailOtpEd25519ExportCapability(e,t){let n=t.activation;await this.activateEmailOtpEd25519CustodyCapabilityWithExactCredential({commitQueue:`acquire`,walletSession:{walletId:e.signer.account.wallet.walletId,walletSessionUserId:String(e.signer.account.wallet.walletId)},providerSubject:e.auth.providerSubjectId,emailHashHex:n.emailHashHex,signerSlot:e.signer.signerSlot,expectedOperationalPublicKey:`ed25519:${tn(n.metadata.registeredPublicKey)}`,expectedThresholdSessionId:String(e.thresholdSessionId),bootstrap:n.bootstrap,activeClientHandle:n.activeClientHandle,metadata:n.metadata,credentialExpectation:{kind:`expect_exact_operation_credential`,operationCredential:t.operationCredential}})}async resolveEmailOtpEd25519YaoExportContext(e){return await WP({subject:e.laneIdentity,expectedMaterialActivation:e.materialActivation,readExactWalletSessionAuthorization:this.readExactEmailOtpEd25519ExportAuthorization.bind(this),resolveActiveCapability:(e,t,n)=>this.enginePorts.ed25519YaoActiveClients.resolve({walletId:e,nearAccountId:B(t),materialActivation:n}),resolveEd25519YaoClientRootEnvelope:async({subject:e,capability:t,selectedMaterialActivation:n})=>$R({selected:await K.resolveSelectedWalletAuthority(String(e.signer.account.wallet.walletId)),subject:e,expectedMaterialActivation:n,activeCapability:t}),loadWalletCustodyMaterial:()=>this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:String(e.laneIdentity.signer.account.nearAccountId),signerSlot:e.laneIdentity.signer.signerSlot}),relayerUrl:this.seamsWebConfigs.network.relayer?.url||``,fetch:KR,activateRecoveredCapability:this.activateRecoveredEmailOtpEd25519ExportCapability.bind(this,e.laneIdentity)})}async resolveActiveNearEd25519YaoSigningLane(e){if(!await this.resolveNearEd25519YaoSigningLane(e))return null;let t=wF(e),n=e.kind===`export_exact_lane`?this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.signer.account.wallet.walletId,nearAccountId:t.signer.account.nearAccountId,materialActivation:e.materialActivation}):this.enginePorts.ed25519YaoActiveClients.resolveForWalletAccount({walletId:t.signer.account.wallet.walletId,nearAccountId:t.signer.account.nearAccountId});return n?.activeClient.status().kind===`active`?n:null}async resolveNearEd25519YaoSigningLane(e){let t=wF(e).signer.account.wallet.walletId,n=await this.readPersistedAvailableSigningLanes({walletId:t,ownerScope:await this.resolveSelectedOwnerLaneScope(t)},new Ja),r=[];for(let t of n.candidates.ed25519.near)TF(t,e)&&(!Jd(t)||t.curve!==`ed25519`||r.push(t));if(r.length>1)throw Error(`[SigningEngine][near] local Ed25519 material lane is ambiguous`);return r[0]||null}async ensurePasskeyEd25519WarmSessionForSigning(e){let t=await YR({...e,claimWarmSessionMaterial:this.passkeyMpcSession.claimWarmSessionMaterial.bind(this.passkeyMpcSession),rehydrateWarmSessionMaterial:this.passkeyMpcSession.rehydrateWarmSessionMaterial.bind(this.passkeyMpcSession)});return t.ok&&e.runtime.factor.kind===`passkey`&&String(e.runtime.thresholdSessionId)!==String(e.walletSessionState.thresholdSessionId)&&await ds({persistence:this,session:e.walletSessionState,prfFirstB64u:t.prfFirstB64u,ed25519Restore:es({rpId:e.runtime.factor.rpId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,relayerKeyId:e.runtime.relayerKeyId,participantIds:e.runtime.participantIds,runtimePolicyScope:e.runtime.runtimePolicyScope,signerSlot:e.runtime.signerSlot,routerAbNormalSigning:e.runtime.routerAbNormalSigning,credentialIdB64u:e.runtime.factor.credentialIdB64u,materialActivation:e.materialActivation}),materialActivation:e.materialActivation}),t}async rehydrateNearEd25519YaoCapabilityForSigning(e){let t=wF(e),n=await this.resolveNearEd25519YaoSigningLane(e);if(!n)throw Error(`[SigningEngine][near] local Ed25519 material lane is unavailable`);let r;if(e.kind===`export_exact_lane`)r=await sz({walletId:t.signer.account.wallet.walletId,laneIdentity:e.laneIdentity,materialActivation:e.materialActivation});else{let i=e.kind===`exact_lane`?e.laneIdentity:bF(n);r=await oz({walletId:t.signer.account.wallet.walletId,laneIdentity:i})}let i=await dz({runtime:r,relayerUrl:String(this.seamsWebConfigs.network.relayer?.url||``).trim()});if(r.factor.kind!==`passkey`)throw Error(`[SigningEngine][near] persisted Ed25519 credential is unavailable`);let a=r.factor.credentialIdB64u,o=r.sealedRecord.ed25519Restore.materialActivation;if(!g(o,n.materialActivation))throw Error(`[SigningEngine][near] persisted Ed25519 material activation mismatch`);let s=await this.ensurePasskeyEd25519WarmSessionForSigning({runtime:r,walletSessionState:i,materialActivation:o}),c={kind:`available`,walletId:String(i.signingLane.identity.signer.account.wallet.walletId),nearAccountId:String(i.signingLane.identity.signer.account.nearAccountId),signerSlot:i.signingLane.identity.signer.signerSlot,materialActivation:o},l=await this.resolvePasskeyEd25519YaoHydration({walletSessionState:i,credentialIdB64u:a,publicLocator:c,unlockSource:s.ok?{kind:`available`,passkeyPrfFirstB64u:s.prfFirstB64u}:{kind:`unavailable`}});if(l.kind===`live`){let t=await this.resolveActiveNearEd25519YaoSigningLane(e);if(!t)throw Error(`[SigningEngine][near] local material rehydration did not publish a lane`);return{subject:e,material:t}}if(l.kind===`rehydrated`){if(!s.ok)throw l.activeClient.dispose(),Error(`[SigningEngine][near] local material rehydration lost the PRF secret`);try{await ds({persistence:this,session:i,prfFirstB64u:s.prfFirstB64u,ed25519Restore:es({rpId:r.factor.rpId,nearAccountId:r.nearAccountId,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,relayerKeyId:r.relayerKeyId,participantIds:r.participantIds,runtimePolicyScope:r.runtimePolicyScope,signerSlot:r.signerSlot,routerAbNormalSigning:r.routerAbNormalSigning,credentialIdB64u:a,materialActivation:o}),materialActivation:o}),await this.enginePorts.ed25519YaoActiveClients.activate({activeClient:l.activeClient,facts:nc(i)});let t=qR({subject:e,walletSessionState:i}),n=await this.resolveActiveNearEd25519YaoSigningLane(t);if(!n)throw Error(`[SigningEngine][near] local material rehydration did not publish an active lane`);return{subject:t,material:n}}catch(e){throw l.activeClient.dispose(),e}}throw l.plan.reason===`missing_material`?Error(`[SigningEngine][near] local threshold Ed25519 material requires Passkey reauthorization`):Error(`[SigningEngine][near] local threshold Ed25519 hydration blocked: ${l.plan.reason}`)}async resolvePasskeyEd25519YaoHydration(e){let t=e.walletSessionState.signingLane.identity.signer;return xs({store:K,identity:_s(e.walletSessionState,this.getRpId(),e.credentialIdB64u),authority:e.walletSessionState.authority,publicLocator:e.publicLocator,unlockSource:e.unlockSource,liveMaterial:e.publicLocator.kind===`available`?this.enginePorts.ed25519YaoActiveClients.resolve({walletId:t.account.wallet.walletId,nearAccountId:t.account.nearAccountId,materialActivation:e.publicLocator.materialActivation}):null})}async signEvmFamily(e){return await Dd(this.enginePorts.tempoSigningDeps,e)}async reportTempoBroadcastAccepted(e){await Ed(this.enginePorts.tempoSigningDeps,e)}async reportTempoBroadcastRejected(e){await kd(this.enginePorts.tempoSigningDeps,e)}async reportTempoFinalized(e){await gd(this.enginePorts.tempoSigningDeps,e)}async reportTempoDroppedOrReplaced(e){await Cd(this.enginePorts.tempoSigningDeps,e)}async reconcileTempoNonceLane(e){return await Ad(this.enginePorts.tempoSigningDeps,e)}storeUserData(e){return Zc(this.enginePorts.registrationAccountLifecycleDeps,e)}async storeNearThresholdKeyMaterial(e){await Jg({clientDB:K,keyMaterialStore:K},e)}getAllUsers(){return Bc(this.enginePorts.registrationAccountLifecycleDeps)}getUserBySignerSlot(e,t){return Gc(this.enginePorts.registrationAccountLifecycleDeps,e,t)}getLastUser(){return Ic(this.enginePorts.registrationAccountLifecycleDeps)}nearAuthenticatorsByAccount(e){return Uc(this.enginePorts.registrationAccountLifecycleDeps,e)}setLastUser(e,t){return Yc(this.enginePorts.registrationAccountLifecycleDeps,e,t)}activateAuthenticatedWalletState(e){return Jc(this.enginePorts.registrationAccountLifecycleDeps,e)}async upsertEd25519YaoPublicCapabilityReference(e){await this.ed25519YaoPublicCapabilityReferences.upsert(e)}async upsertEd25519YaoPublicCapabilityLaneReference(e){await sa(this.ed25519YaoPublicCapabilityReferences,e)}setWalletNearProvisioningState(e){return Qc(this.enginePorts.registrationAccountLifecycleDeps,e)}getWalletNearProvisioningState(e){return qc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeAuthenticator(e){return Lc(this.enginePorts.registrationAccountLifecycleDeps,e)}rollbackUserRegistration(e){return zc(this.enginePorts.registrationAccountLifecycleDeps,e)}hasPasskeyCredential(e){return Rc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEd25519RegistrationData(e){return Pc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletMixedRegistrationData(e){return Ec(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEd25519RecoveryRegistrationData(e){return Xc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEmailOtpEd25519RegistrationData(e){return jc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEmailOtpMixedRegistrationData(e){return Hc(this.enginePorts.registrationAccountLifecycleDeps,e)}finalizeWalletEd25519SignerRegistration(e){return Kc(this.enginePorts.registrationAccountLifecycleDeps,e)}rollbackWalletEd25519SignerRegistration(e){return Fc(this.enginePorts.registrationAccountLifecycleDeps,e)}createRouterAbEcdsaRegistrationCeremony(e){return this.runtimePorts.signerCrypto.createRouterAbEcdsaRegistrationCeremony(e)}verifyRouterAbEcdsaRegistrationClientProofs(e){return this.runtimePorts.signerCrypto.verifyRouterAbEcdsaRegistrationClientProofs(e)}persistInitialCanonicalEcdsaActivation(e){return this.runtimePorts.signerCrypto.persistInitialCanonicalEcdsaActivation(e)}finalizeRouterAbEcdsaRegistrationActivation(e){return this.runtimePorts.signerCrypto.finalizeRouterAbEcdsaRegistrationActivation(e)}closeRouterAbEcdsaRegistrationCeremony(e){return this.runtimePorts.signerCrypto.closeRouterAbEcdsaRegistrationCeremony(e)}finalizeWalletRegistrationEcdsaSessions(e){return mP(e)}storeWalletEcdsaSignerRecords(e){return Dc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEcdsaRecoverySignerRecords(e){return Nc(this.enginePorts.registrationAccountLifecycleDeps,e)}storeWalletEmailOtpEcdsaSignerRecords(e){return Oc(this.enginePorts.registrationAccountLifecycleDeps,e)}finalizeWalletEcdsaRegistration(e){return Wc(this.enginePorts.registrationAccountLifecycleDeps,e)}async activateVerifiedNearEd25519YaoMaterial(e){return await this.enginePorts.ed25519YaoActiveClients.activate(e)}async installAuthMethodSession(e,t){return await Ik({engine:this,relayerUrl:this.seamsWebConfigs.network.relayer.url,nearClient:this.nearClient,transport:this.walletCustodyCeremonyTransportV1(),rememberNearSession:this.voiceIdNearSessions.set.bind(this.voiceIdNearSessions,t.walletSession.walletId)},e,t)}async withExactEd25519MaterialOwner(e){return await Pf({queueByKey:this.thresholdEd25519CommitQueueByKey,queueKey:Yd({materialActivation:e.materialActivation}),nearAccountId:e.nearAccountId,enabled:!0,task:e.task})}storeWalletEmailOtpEcdsaRegistrationData(e){return kc(this.enginePorts.registrationAccountLifecycleDeps,e)}requestWorkerOperation=e=>this.signerWorkerManager.getContext().requestWorkerOperation(e);prepareSigningSessionHydration(e){return this.passkeyMpcSession.prepareSigningSessionHydration(e)}readPreparedSigningSessionHydration(e){return this.passkeyMpcSession.readPreparedSigningSessionHydration(e)}discardSigningSessionHydration(e){return this.passkeyMpcSession.discardSigningSessionHydration(e)}hydrateSigningSession(e){return jF(this.warmCapabilitiesPublicDeps,e)}persistSigningSessionSealForThresholdSession(e){return this.passkeyMpcSession.persistSigningSessionSealForThresholdSession(e)}async requestEmailOtpOwnerConfirmation(e){let t=Nz(e.purpose,e.emailAddress),n=e.onResend,r=e.challengeId,i={challengeId:e.challengeId,...e.emailHint?{emailHint:e.emailHint}:{},title:e.confirmerText?.title||t.title,body:e.confirmerText?.body||t.body,helperText:`Enter the 6-digit code sent to your email`,...n?{onResend:async()=>{let e=await n();return r=e.challengeId,{challengeId:e.challengeId,...e.emailHint?{emailHint:e.emailHint}:{},delivery:{mode:`email_provider`}}}}:{}},a=await this.touchConfirm.requestUserConfirmation({requestId:ve(`wallet-owner-email-otp`,32,`Wallet owner Email OTP UI ids`),type:Y.SIGN_INTENT_DIGEST,summary:{type:e.purpose===`add_email_code`||e.purpose===`add_passkey`?`add_auth_method`:`wallet_owner_confirmation`,operation:t.operation,title:i.title,body:i.body,...t.warning?{warning:t.warning}:{}},payload:{signingSubject:{kind:`evm_wallet`,walletId:e.walletId},challengeB64u:e.challengeId,signingAuthPlan:{kind:Of.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:i},emailOtpPrompt:i},intentDigest:`wallet-owner-email-otp:${e.purpose}:${e.walletId}`,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}});if(!a.confirmed)throw Error(a.error||`Email code confirmation was cancelled`);let o=String(a.otpCode||``).replace(/\D/g,``).slice(0,6);if(o.length!==6)throw Error(`Email code confirmation requires a 6-digit code`);return{challengeId:String(a.emailOtpChallengeId||r).trim(),otpCode:o}}requestRegistrationCredentialConfirmation(e){return hP(this.enginePorts.registrationSessionDeps,e)}openRegistrationPreparationModal(e){return this.touchConfirm.openRegistrationPreparationModal(e)}closeRegistrationPreparationModal(){this.touchConfirm.closeRegistrationPreparationModal()}startPreparedPasskeyRegistrationCredential(e){if(this.touchIdPrompt.getRpId()!==e.expectedRpId)throw Error(`Prepared registration rpId does not match the wallet runtime`);return this.touchIdPrompt.generateRegistrationCredentialsInternal({kind:`wallet_registration`,walletId:e.walletId,challengeB64u:e.challengeB64u,signerSlot:e.signerSlot,intendedUserName:e.walletId,prompt:{kind:`reserved`,reservation:e.reservation,owner:e.owner,cancellation:e.cancellation}}).then(Ez)}getAuthenticationCredentialsSerialized(e){return e.cancellation?this.touchIdPrompt.getAuthenticationCredentialsSerializedForChallengeB64u(e):gP(this.enginePorts.registrationSessionDeps,e)}async exportKeypairWithUI(e){return await uP(this.recoveryPublicDeps,e)}async resolveExactKeyExportLane(e){return await dP(this.recoveryPublicDeps,e)}async connectEd25519Session(e){return await vF(this.passkeyPublicDeps,e)}async bootstrapEcdsaSession(e){return await yF(this.passkeyPublicDeps,e)}async loginWithEmailOtpEcdsaCapabilityInternal(e){return await AP(this.emailOtpPublicDeps,e)}async resolveEmailOtpEd25519CustodyProjectionInternal(e){let t=String(e.walletSession.walletId),n;switch(e.selector.kind){case`material_activation`:n=e.selector.materialActivation;break;case`wallet_auth_method`:{let r=await K.resolveWalletAuthorityForMethod(t,e.selector.walletAuthMethodId);n=r.kind===`resolved`&&r.authority.state===`active`?r.authority.signerActivations.ed25519?.materialActivation:void 0;break}case`selected_wallet_authority`:{let e=await K.resolveSelectedWalletAuthority(t);n=e.kind===`resolved`&&e.authority.state===`active`?e.authority.signerActivations.ed25519?.materialActivation:void 0;break}default:e.selector}return n?await WF({listPublicCapabilityReferences:this.ed25519YaoPublicCapabilityReferences.list.bind(this.ed25519YaoPublicCapabilityReferences),listUsers:this.getAllUsers.bind(this)},e.walletSession,e.providerSubjectId,n):null}async resolveOwnerAuthorityEd25519UnlockRequestInternal(e){let t=await this.resolveEmailOtpEd25519CustodyProjectionInternal({walletSession:e.walletSession,providerSubjectId:e.providerSubjectId,selector:{kind:`wallet_auth_method`,walletAuthMethodId:e.walletAuthMethodId}});if(!t)return null;let n=t.user.signerSlot;return{kind:`owner_authority`,signerSlot:n,remainingUses:e.remainingUses,recovery:{ed25519YaoRecovery:{kind:Yr,signerSlot:n,remainingUses:e.remainingUses,orgId:t.identity.runtimePolicyScope.orgId},providerSubject:t.providerSubject,nearAccountId:String(t.identity.nearAccountId),expectedOperationalPublicKey:t.user.operationalPublicKey,expectedThresholdSessionId:String(t.identity.thresholdSessionId),walletCustodyEd25519Material:await this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:String(t.identity.nearAccountId),signerSlot:n})}}}async activateOwnerAuthorityEd25519RuntimeInternal(e){let t=await this.resolveEmailOtpEd25519CustodyProjectionInternal({walletSession:e.walletSession,providerSubjectId:e.providerSubjectId,selector:{kind:`wallet_auth_method`,walletAuthMethodId:e.walletAuthMethodId}});if(!t)throw Error(`Owner Email OTP Ed25519 activation has no signer projection`);await this.activateEmailOtpEd25519CustodyCapabilityInternal({walletSession:e.walletSession,providerSubject:t.providerSubject,emailHashHex:e.emailHashHex,signerSlot:t.user.signerSlot,expectedOperationalPublicKey:t.user.operationalPublicKey,expectedThresholdSessionId:String(t.identity.thresholdSessionId),bootstrap:e.bootstrap,activeClientHandle:e.activeClientHandle,metadata:e.metadata,authority:e.authority,commitQueue:`acquire`})}async activateEmailOtpEd25519RegistrationMaterialInternal(e){let t=await this.signerWorkerManager.requestWorkerOperation({kind:`emailOtp`,request:{type:`activateEmailOtpEd25519YaoRegistrationMaterial`,payload:{material:e.material,bootstrap:e.bootstrap,envelope:e.envelope,factorSecret32:e.factorSecret32},transfer:[e.factorSecret32]}});try{let n=await this.activateEmailOtpEd25519CustodyCapabilityInternal({commitQueue:`acquire`,walletSession:e.walletSession,providerSubject:e.providerSubject,emailHashHex:e.emailHashHex,signerSlot:e.signerSlot,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,bootstrap:e.bootstrap,activeClientHandle:t.activeClientHandle,metadata:t.metadata});return await UR({walletId:e.walletSession.walletId,emailHashHex:e.emailHashHex,providerSubject:e.providerSubject,bootstrap:e.bootstrap}),n}catch(n){try{await JP({worker:this.signerWorkerManager.getContext(),target:{kind:`ed25519_yao`,thresholdSessionId:e.bootstrap.session.thresholdSessionId,materialActivation:t.metadata.materialActivation}})}catch{}try{await Fy({workerContext:this.signerWorkerManager.getContext(),activeClientHandle:t.activeClientHandle})}catch{}throw n}}async activateEmailOtpEd25519CustodyCapabilityInternal(e){return await this.activateEmailOtpEd25519CustodyCapabilityWithExactCredential({...e,credentialExpectation:{kind:`resolve_exact_operation_credential`}})}async activateEmailOtpEd25519CustodyCapabilityWithExactCredential(e){let t=await UR({walletId:e.walletSession.walletId,emailHashHex:e.emailHashHex,providerSubject:e.providerSubject,bootstrap:e.bootstrap,...e.authority?{verifiedAuthority:e.authority}:{},...e.exactAuthorization?{exactAuthorization:e.exactAuthorization}:{}});if(e.credentialExpectation.kind===`expect_exact_operation_credential`&&(e.credentialExpectation.operationCredential.walletSessionId!==t.operationCredential.walletSessionId||e.credentialExpectation.operationCredential.token!==t.operationCredential.token))throw Error(`[SigningEngine][near] expected Email OTP operation credential changed`);return await Pf({queueByKey:this.thresholdEd25519CommitQueueByKey,queueKey:Yd({materialActivation:e.metadata.materialActivation}),nearAccountId:B(e.bootstrap.session.nearAccountId),enabled:e.commitQueue===`acquire`,task:async()=>{let n=await BF({walletSession:e.walletSession,nearAccountId:e.bootstrap.session.nearAccountId,providerSubject:e.providerSubject,relayerUrl:this.seamsWebConfigs.network.relayer?.url||``,authority:t.authority,signerSlot:e.signerSlot,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,bootstrap:e.bootstrap,operationCredential:t.operationCredential,activeClientHandle:e.activeClientHandle,metadata:e.metadata,workerContext:this.signerWorkerManager.getContext(),activateCapability:this.enginePorts.ed25519YaoActiveClients.activate.bind(this.enginePorts.ed25519YaoActiveClients)}),r=n.walletSessionState;if(await this.upsertEd25519YaoPublicCapabilityLaneReference(ZR({walletSessionState:r,materialActivation:n.material.activeClient.metadata().materialActivation})),!this.enginePorts.ed25519YaoActiveClients.resolve({walletId:r.signingLane.identity.signer.account.wallet.walletId,nearAccountId:r.signingLane.identity.signer.account.nearAccountId,materialActivation:n.material.activeClient.metadata().materialActivation}))throw Error(`[SigningEngine][near] wallet custody activation was superseded`);return r.signingLane.identity.signer}})}async loginWithEmailOtpWalletCustodyEd25519Internal(e){if(e.authoritySelector.kind!==`wallet_auth_method`)throw Error(`Email OTP Ed25519 unlock requires an exact wallet auth method`);let t=e.authoritySelector.walletAuthMethodId,n=e.ed25519Selection,r=await Go({walletSession:e.walletSession,authoritySelector:e.authoritySelector,relayUrl:this.seamsWebConfigs.network.relayer?.url||``,groupId:Ze,verification:{kind:`otp`,challengeId:e.challengeId,otpCode:e.otpCode},routePlan:rc({freshRouteFamily:`login`,operation:Ht}),workerCtx:this.signerWorkerManager.getContext(),providerSubject:e.providerSubjectId,signerSlot:n.signerSlot,remainingUses:e.remainingUses,orgId:n.runtimePolicyScope.orgId,nearAccountId:n.nearAccountId,expectedOperationalPublicKey:n.operationalPublicKey,expectedThresholdSessionId:n.thresholdSessionId,walletCustodyEd25519Material:await this.loadEmailOtpWalletCustodyEd25519Material({nearAccountId:n.nearAccountId,signerSlot:n.signerSlot})});if(r.kind===`wallet_custody_cache_absent`)throw Error(`Email OTP wallet custody material is unavailable; recover with a recovery code`);try{await _I({walletId:String(e.walletSession.walletId),walletAuthMethodId:t,projection:r.recovery.verifiedAuthorityProjection});let i=await vI({walletId:String(e.walletSession.walletId),walletAuthMethodId:t,providerSubject:e.providerSubjectId,emailHashHex:e.emailHashHex,projection:r.recovery.verifiedAuthorityProjection});r.walletCustodyEd25519Material&&await this.persistWalletCustodyEd25519Material(r.walletCustodyEd25519Material),await q.replaceExactActive({active:r.walletSessionAuthorization.record,operationCredential:r.walletSessionAuthorization.operationCredential});let a=await this.activateEmailOtpEd25519CustodyCapabilityInternal({commitQueue:`acquire`,walletSession:e.walletSession,providerSubject:e.providerSubjectId,emailHashHex:e.emailHashHex,signerSlot:n.signerSlot,expectedOperationalPublicKey:n.operationalPublicKey,expectedThresholdSessionId:n.thresholdSessionId,bootstrap:r.ed25519YaoCapability,activeClientHandle:r.activeClientHandle,metadata:r.metadata,authority:i,exactAuthorization:r.walletSessionAuthorization});return await no(this.walletCustodyCeremonyTransportV1(),{existingEnvelope:r.ed25519ExportRootCustody.existingEnvelope,existingFactorSecret:r.ed25519ExportRootCustody.factorSecret32,walletId:String(e.walletSession.walletId),walletAuthMethodId:String(r.walletSessionAuthorization.record.authMethodId),walletSessionId:String(r.walletSessionAuthorization.operationCredential.walletSessionId),expiresAtMs:r.walletSessionAuthorization.record.expiresAtMs}),a}catch(e){throw await Fy({workerContext:this.signerWorkerManager.getContext(),activeClientHandle:r.activeClientHandle}).catch(()=>void 0),e}finally{r.ed25519ExportRootCustody.factorSecret32.fill(0)}}async prepareEmailOtpRegistrationEnrollmentMaterialInternal(e){return await jP(this.emailOtpPublicDeps,e)}async getWarmThresholdEd25519SessionStatus(e){let t=V(e.walletId),n=await gc({walletId:t,nearAccountId:B(e.nearAccountId),nearEd25519SigningKeyId:Oi(e.nearEd25519SigningKeyId)});if(n.kind===`missing`)return null;if(n.kind!==`resolved`)throw Error(`[WarmSessionStore] Ed25519 sealed runtime is ${n.kind}`);let r=await this.readExactNearEd25519WalletSessionAuthorization(t);return await kF(this.warmCapabilitiesPublicDeps,{runtime:n.runtime,authorization:r.kind===`found`?r.authorization:null,nowMs:Date.now()})}async scheduleRouterAbEcdsaDerivationLoginPresignaturePrefill(e,t){let n=await this.listPreprocessingCapabilities({walletId:e.walletId,chainTargets:[e.chainTarget]},t),r=n.length===1?n[0]:null;return r?await AF(this.warmCapabilitiesPublicDeps,{capability:r,waitForPoolReady:e.waitForPoolReady}):{status:`skipped`,reason:`exact_wallet_session_unavailable`,walletSessionId:null}}async clearVolatileWarmSigningMaterial(e){let t=this.clearVolatileWarmSigningMaterialInternal(e);this.volatileWarmSigningMaterialCleanupInFlight=t;try{await t}finally{this.volatileWarmSigningMaterialCleanupInFlight===t&&(this.volatileWarmSigningMaterialCleanupInFlight=null)}}async clearVolatileWarmSigningMaterialInternal(e){e?this.voiceIdNearSessions.delete(e):this.voiceIdNearSessions.clear();try{e?this.enginePorts.ed25519YaoActiveClients.disposeWallet(e):this.enginePorts.ed25519YaoActiveClients.dispose()}finally{try{await MF(this.warmCapabilitiesPublicDeps,e)}finally{try{e===void 0?await this.clearLinkedEcdsaHolderMaterials():await this.clearLinkedEcdsaHolderMaterialsForWallet(e)}finally{await this.signerWorkerManager.clearEcdsaClientWorkerState(e===void 0?{kind:`all`}:{kind:`wallet`,walletId:e})}}}}onSdkLifecycleEvent(e){return this.sdkLifecycleEventListeners.add(e),this.removeSdkLifecycleEventListener.bind(this,e)}publishSdkLifecycleEvent(e){let t=Oz(e);if(!this.deliveredSdkLifecycleEventKeys.has(t)){this.deliveredSdkLifecycleEventKeys.add(t);for(let t of Array.from(this.sdkLifecycleEventListeners))t(e)}}publishNearProvisioningLifecycleEvent(e,t){this.publishSdkLifecycleEvent(Ki({walletId:e,state:t}))}removeSdkLifecycleEventListener(e){this.sdkLifecycleEventListeners.delete(e)}dispose(){this.signingSessionLifecycleSubscription.unsubscribe(),this.nearProvisioningUnsubscribe(),this.sdkLifecycleEventListeners.clear(),this.deliveredSdkLifecycleEventKeys.clear(),this.ed25519YaoPageLifecycleOwner.dispose()}clearThresholdEcdsaSigningQueue(){Zd(this.thresholdEcdsaSigningQueueByKey)}async clearLinkedEcdsaHolderMaterials(){await rd({workerCtx:this.signerWorkerManager.getContext()}),Fd()}async clearLinkedEcdsaHolderMaterialsForWallet(e){let t=Ud(e),n;for(let e of t)try{await Gu({holderHandleIds:[e.holderHandleId],workerCtx:this.signerWorkerManager.getContext()}),Id(e)}catch(e){n??=e}if(n!==void 0)throw n}};function Fz(e){return Array.isArray(e)?e.filter(e=>[`ble`,`hybrid`,`internal`,`nfc`,`smart-card`,`usb`].includes(String(e))):[]}function Iz(e){let t=new Set;for(let n of e.authMethods)n.kind===`passkey`&&n.status===`active`&&n.walletId===e.walletId&&t.add(n.credentialIdB64u);let n=[];for(let r of e.authenticators){let i=String(r.credentialId||``).trim();!i||i===e.excludeCredentialIdB64u||!t.has(i)||n.push({id:i,type:`public-key`,transports:Fz(r.transports)})}return n}async function Lz(e){let[t,n]=await Promise.all([K.listProfileAuthenticators(String(e.walletId)),K.listWalletAuthMethodsV2ForWallet(String(e.walletId))]);return Iz({walletId:e.walletId,authenticators:t,authMethods:n,excludeCredentialIdB64u:e.excludeCredentialIdB64u})}async function Rz(e){let t=await e.context.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(e.walletId),challengeB64u:e.operationFingerprintDigest,allowCredentials:e.allowCredentials,includeSecondPrfOutput:!1}),n=Tl(t);if(!n||!e.allowCredentials.some(e=>e.id===n))throw Error(`registration.removeAuthMethod used a credential outside the wallet`);return{kind:`webauthn_assertion`,rpId:e.rpId,credential:Tc(t),expectedChallengeDigestB64u:e.operationFingerprintDigest}}async function zz(e){let[t,...n]=(await K.listWalletAuthMethodsForWallet(String(e.walletId))).filter(t=>t.kind===`email_otp`&&t.status===`active`&&String(t.walletId)===String(e.walletId)&&String(t.authority.bindingId)!==String(e.targetWalletAuthMethodId)&&(e.source.kind===`surviving_method`||String(t.authority.bindingId)===String(e.source.walletAuthMethodId)));if(!t||n.length>0||t.kind!==`email_otp`)throw Error(`registration.removeAuthMethod needs exactly one other active method to authorize with`);let r=String(t.authority.bindingId),i=async()=>await Ys({relayUrl:e.relayerUrl,walletId:String(e.walletId),walletAuthMethodId:r,operation:Wt,operationFingerprintDigest:Pt(e.operationFingerprintDigest)}),a=await i(),o=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:`remove_auth_method`,walletId:String(e.walletId),emailAddress:String(a.emailHint||``),challengeId:a.challengeId,...a.emailHint?{emailHint:a.emailHint}:{},onResend:async()=>{let e=await i();return e.emailHint?{challengeId:e.challengeId,emailHint:e.emailHint}:{challengeId:e.challengeId}}});return{kind:`email_otp`,challengeId:o.challengeId,otpCode:o.otpCode,ownerProofBindingDigest:a.ownerProofBindingDigest}}async function Bz(e,t,n){let r=String(e.configs.network.relayer.url||``).trim();if(!r)throw Error(`registration.removeAuthMethod requires relayer.url`);let i=o(String(e.signingEngine.getRpId()||``).trim());if(!i.ok)throw Error(`registration.removeAuthMethod ${i.error.message}`);let a=Date.now(),s=await wi({walletId:n.walletId,targetWalletAuthMethodId:n.walletAuthMethodId,requestedAtMs:a}),c=await K.getWalletAuthMethodV2(n.walletAuthMethodId),l=c&&c.kind===`passkey`?String(c.credentialIdB64u):null,u=await Lz({walletId:n.walletId,excludeCredentialIdB64u:l});if(t.kind===`selected_method`){let e=await K.getWalletAuthMethodV2(t.walletAuthMethodId);if(!e||e.status!==`active`||e.walletId!==n.walletId||e.walletAuthMethodId===n.walletAuthMethodId)throw Error(`Removal requires a different active method on this wallet`);if(u=e.kind===`passkey`?u.filter(t=>t.id===e.credentialIdB64u):[],e.kind===`passkey`&&u.length===0)throw Error(`Selected passkey is unavailable for removal authorization`)}let d;d=u.length>0?R.passkey:R.emailOtp;let f;switch(d){case R.passkey:f=await Rz({context:e,walletId:n.walletId,rpId:i.value,operationFingerprintDigest:String(s),allowCredentials:u});break;case R.emailOtp:f=await zz({context:e,relayerUrl:r,walletId:n.walletId,targetWalletAuthMethodId:n.walletAuthMethodId,source:t,operationFingerprintDigest:String(s)});break;default:throw Error(`registration.removeAuthMethod encountered an unsupported source method`)}return{relayerUrl:r,requestedAtMs:a,sourceProof:f}}async function Vz(e){let{relayerUrl:t,requestedAtMs:n,sourceProof:r}=await Bz(e.context,{kind:`surviving_method`},{walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId}),i=await mo({relayerUrl:t,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,requestedAtMs:n,sourceProof:r});if(!i.ok||i.authMethod.status!==`revoked`)throw Error(`registration.removeAuthMethod did not revoke the method`);let a=await K.getWalletAuthMethodV2(e.walletAuthMethodId);if(a&&a.status!==`revoked`){let e=Date.now(),t=a.status===`active`?a.activatedAtMs:e,n=Ti({...a,status:`revoked`,activatedAtMs:t,revokedAtMs:e,updatedAtMs:e});n&&await K.upsertWalletAuthMethodV2(n)}return{ok:!0,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,authMethod:i.authMethod}}async function Hz(e){let t=ki(String(e.walletId||``).trim()),n=r(String(e.walletAuthMethodId||``).trim());if(!n.ok)throw Error(`registration.removeAuthMethod requires a wallet auth method id`);try{return await Vz({context:e.context,walletId:t,walletAuthMethodId:n.value})}catch(e){throw I(e)}}const Uz=`/wallet/device-linking/v1/sessions`,Wz=4e3,Gz=[`ok`,`outcome`,`session`],Kz=[`ok`,`outcome`,`session`,`targetCredential`],qz=[`ok`,`code`,`message`],Jz=[`ok`,`outcome`,`code`,`message`],Yz=[`ok`,`outcome`,`expectedRevision`,`actualRevision`,`session`],Xz=[`ok`,`outcome`,`session`],Zz=[`ok`,`outcome`,`state`,`session`],Qz=[`ok`,`outcome`,`reason`,`session`];function $z(e,t){let n=Math.min(e,Wz),r=Math.min(Math.max(t,0),5),i=Math.min(Wz,n*2**r),a=Math.max(1,Math.min(n,i/4)),o=Math.floor(Math.random()*a);return Math.min(Wz,i+o)}async function eB(e){let t=e.options.nowMs()+6e4,n=0;for(;e.options.nowMs()<t;){let t=await cB({options:e.options,baseUrl:e.baseUrl,method:`GET`,canonicalPath:xB(e.linkSessionId,`approval`),linkSessionId:e.linkSessionId});if(t.status!==204)return Bn(t.body);let r=$z(e.options.pollIntervalMs,n);await new Promise(e=>setTimeout(e,r)),n+=1}throw Error(`committed authority packages were not ready before the activation deadline`)}function tB(e){let t=yB(e.relayerUrl);if(!Number.isSafeInteger(e.pollIntervalMs)||e.pollIntervalMs<=0)throw Error(`linked-device session poll interval must be a positive integer`);return{...rB(e),...nB(e),createUnclaimedSessionV1:async n=>{await sB({options:e,baseUrl:t,method:`POST`,canonicalPath:Uz,linkSessionId:n.payload.linkSessionId,body:{kind:`linked_device_session_create_request_v1`,payload:n.payload}})},getSessionV1:async({linkSessionId:n})=>await oB({options:e,baseUrl:t,linkSessionId:n}),getApprovalV1:async({linkSessionId:n})=>Wn((await cB({options:e,baseUrl:t,method:`GET`,canonicalPath:xB(n,`approval`),linkSessionId:n})).body).approval,getTargetPreparationV1:async({linkSessionId:n,deliveryRecipientPublicKey65B64u:r})=>{let i=Ln({kind:`linked_device_target_preparation_request_v1`,linkSessionId:n,deliveryRecipientPublicKey65B64u:r});return Xn((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n,`target-preparation`),linkSessionId:n,body:i})).body)},startTargetEmailOtpChallengeV1:async({request:n})=>{let r=Un(n);return Hn((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(r.linkSessionId,`email-otp/challenge`),linkSessionId:r.linkSessionId,body:r})).body)},resendTargetEmailOtpChallengeV1:async({request:n})=>{let r=fr(n);return Hn((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(r.linkSessionId,`email-otp/challenge/resend`),linkSessionId:r.linkSessionId,body:r})).body)},verifyTargetEmailOtpChallengeV1:async({request:n})=>{let r=Gn(n);return Vn((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(r.linkSessionId,`email-otp/challenge/verify`),linkSessionId:r.linkSessionId,body:r})).body)},registerTargetCredentialV1:async({registration:n})=>fB((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n.linkSessionId,`credential`),linkSessionId:n.linkSessionId,body:n})).body),registerEd25519ExportRootRecipientV1:async({recipient:n})=>{let r=aB(n.linkSessionId);await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(r,`ed25519-export-root-recipient`),linkSessionId:r,body:n})},getEd25519ExportRootPackageV1:async({linkSessionId:n})=>{let r=await cB({options:e,baseUrl:t,method:`GET`,canonicalPath:xB(n,`ed25519-export-root`),linkSessionId:n});return r.status===204?null:$n(r.body)},retryCommittedDeliveryV1:async({request:n})=>{await sB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n.linkSessionId,`retry`),linkSessionId:n.linkSessionId,body:n})},cancelSessionV1:async({request:n})=>{await sB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n.linkSessionId,`cancel`),linkSessionId:n.linkSessionId,body:n})},subscribeSessionV1:async({linkSessionId:n,onEvent:r})=>await uB({options:e,baseUrl:t,linkSessionId:n,onEvent:r})}}function nB(e){let t=yB(e.relayerUrl);return{acknowledgeLocalAuthorityActivationWithWalletSessionV1:async({acknowledgement:n,operationCredential:r})=>{let i=mr(n),a=ze(r);if(a.walletSessionId!==i.walletSessionId)throw Error(`linked-device acknowledgement credential does not match Wallet Session`);await lB({options:e,baseUrl:t,linkSessionId:i.linkSessionId,token:a.token,body:i})}}}function rB(e){let t=yB(e.relayerUrl);return{receiveCommittedAuthorityPackagesV1:async({linkSessionId:n})=>await eB({options:e,baseUrl:t,linkSessionId:n}),activateInstalledAuthorityV1:async({linkSessionId:n,receipt:r})=>{let i=xr(r);return ar((await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n,`receipt`),linkSessionId:n,body:i})).body)},acknowledgeLocalAuthorityActivationV1:async({acknowledgement:n})=>{let r=mr(n);await cB({options:e,baseUrl:t,method:`POST`,canonicalPath:xB(n.linkSessionId,`receipt`),linkSessionId:n.linkSessionId,body:r})}}}function iB(e){return{...e.owner,createAuthenticatedSessionTransportV1:({keyMaterial:t,devicePublicKeyB64u:n})=>tB({http:e.http,relayerUrl:e.relayerUrl,publishableKey:e.publishableKey,projectEnvironmentId:e.projectEnvironmentId,keyMaterial:e.keyMaterial,keyMaterialHandle:t,devicePublicKeyB64u:n,nowMs:e.nowMs,pollIntervalMs:e.pollIntervalMs})}}function aB(e){let t=S(e);if(!t.ok)throw Error(t.error.message);return t.value}async function oB(e){return dB((await cB({options:e.options,baseUrl:e.baseUrl,method:`GET`,canonicalPath:bB(e.linkSessionId),linkSessionId:e.linkSessionId})).body).session}async function sB(e){return dB((await cB(e)).body)}async function cB(e){let t=e.options.publishableKey.trim(),n=e.options.projectEnvironmentId.trim();if(!t||!n)throw Error(`linked-device Passkey ceremony requires registration API credentials`);let r=await Nt(vB(e.body)),i=e.options.nowMs();if(!Number.isSafeInteger(i)||i<=0)throw Error(`linked-device request clock is invalid`);let a=i+yr,o=_e(32,`linked-device request proof nonce`),s=await dr(e.options.devicePublicKeyB64u),c=await e.options.keyMaterial.signDeviceSessionRequestV1({handle:e.options.keyMaterialHandle,linkSessionId:e.linkSessionId,method:e.method,canonicalPath:e.canonicalPath,bodyDigestB64u:r,devicePublicKeyDigestB64u:s,challengeB64u:o,issuedAtMs:i,expiresAtMs:a}),l={kind:`linked_device_request_proof_v1`,linkSessionId:e.linkSessionId,devicePublicKeyDigestB64u:s,requestNonceB64u:o,method:e.method,canonicalPath:e.canonicalPath,bodyDigestB64u:r,issuedAtMs:i,expiresAtMs:a,signatureB64u:c.signatureB64u},u=P(new TextEncoder().encode(JSON.stringify(l))),d=await e.options.http.request({method:e.method,url:`${e.baseUrl}${e.canonicalPath}`,headers:{Accept:`application/json`,Authorization:`Bearer ${t}`,"Content-Type":`application/json`,"X-Seams-Environment-Id":n,[gr]:u},...e.body===void 0?{}:{body:e.body}});if(!d.ok)throw Error(`linked-device request failed: ${d.message}`);if(d.value.status<200||d.value.status>=300)throw Error(mB(d.value));return d.value}async function lB(e){let t=e.token.trim(),n=e.options.projectEnvironmentId.trim();if(!t||!n)throw Error(`linked-device Wallet Session acknowledgement requires session credentials`);let r=await e.options.http.request({method:`POST`,url:`${e.baseUrl}${xB(e.linkSessionId,`receipt`)}`,headers:{Accept:`application/json`,Authorization:`Bearer ${t}`,"Content-Type":`application/json`,"X-Seams-Environment-Id":n},body:e.body});if(!r.ok)throw Error(`linked-device request failed: ${r.message}`);if(r.value.status<200||r.value.status>=300)throw Error(mB(r.value))}async function uB(e){let t=!1,n,r=null,i=!0,a=0,o=null,s=async()=>{if(!t)try{let t=await oB({...e});r===null||t.revision!==r?(r=t.revision,a=0,e.onEvent(Nn({kind:`linked_device_session_event_v1`,linkSessionId:t.linkSessionId,state:t.state,emittedAtMs:t.updatedAtMs}))):a+=1}catch(e){if(i)throw t=!0,e;a+=1}finally{i=!1,t||(n=setTimeout(()=>{o=s()},$z(e.options.pollIntervalMs,Math.max(0,a-1))))}};return await(o=s()),{close:async()=>{t=!0,n!==void 0&&clearTimeout(n),await o?.catch(()=>void 0)}}}function dB(e){let t=hB(e);if(t===null)throw Error(`linked-device response must be an object`);if(!_B(t,Gz))throw Error(`linked-device response contains invalid fields`);if(t.ok!==!0)throw Error(`linked-device response outcome is invalid`);switch(t.outcome){case`applied`:return{ok:!0,outcome:`applied`,session:Pn(t.session)};case`replayed`:return{ok:!0,outcome:`replayed`,session:Pn(t.session)};default:throw Error(`linked-device response outcome is invalid`)}}function fB(e){let t=hB(e);if(t===null)throw Error(`linked-device target credential response must be an object`);if(!_B(t,Kz))throw Error(`linked-device target credential response contains invalid fields`);if(t.ok!==!0)throw Error(`linked-device target credential response outcome is invalid`);switch(t.outcome){case`applied`:return pB(t,`applied`);case`replayed`:return pB(t,`replayed`);default:throw Error(`linked-device target credential response outcome is invalid`)}}function pB(e,t){let n=Pn(e.session),r=Zn(e.targetCredential);if(r.outcome!==t)throw Error(`linked-device target credential response outcome does not match its result`);if(r.linkSessionId!==n.linkSessionId)throw Error(`linked-device target credential response session identity differs`);return r}function mB(e){let t=hB(e.body);if(t===null||t.ok!==!1)return`linked-device request failed with HTTP ${e.status}`;if(_B(t,qz)&&typeof t.code==`string`&&typeof t.message==`string`&&t.message.trim()||_B(t,Jz)&&typeof t.outcome==`string`&&typeof t.code==`string`&&typeof t.message==`string`&&t.message.trim())return`linked-device request failed: ${t.message}`;switch(t.outcome){case`conflict`:if(_B(t,Yz))return`linked-device request failed: conflict`;break;case`expired`:if(_B(t,Xz))return`linked-device request failed: expired`;break;case`invalid_state`:if(_B(t,Zz))return`linked-device request failed: invalid_state`;break;case`integrity_error`:if(_B(t,Qz))return`linked-device request failed: integrity_error`;break;default:break}return`linked-device request failed with HTTP ${e.status}`}function hB(e){return gB(e)?e:null}function gB(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return!1}}function _B(e,t){try{return vo(e,t)}catch{return!1}}function vB(e){if(e===void 0)return new Uint8Array;let t=JSON.stringify(e);if(typeof t!=`string`)throw Error(`linked-device request body is not JSON serializable`);return new TextEncoder().encode(t)}function yB(e){let t=e.trim().replace(/\/+$/,``);if(!t)throw Error(`linked-device relayer URL is required`);return t}function bB(e){return`${Uz}/${String(e)}`}function xB(e,t){return`${bB(e)}/${t}`}function SB(e){return e?String(e.linkSessionId):`link-device-scan`}function CB(e){return new X(e,Z.INVALID_QR_DATA,`authorization`)}function wB(e,t){try{e?.(t)}catch{}}function TB(e,t,n){e?.(Gi({flowId:SB(t),...n,data:{role:`scanner`,...n.data??{}}}))}function EB(e,t){if(e.walletSessionId!==t.walletSessionId||e.authorizationId!==t.authorizationId)throw Error(`wallet-session authorization source changed during linking`)}function DB(e){if(e instanceof X)return e;let t=L(e)||`Device linking failed`;return/expired|expiry/i.test(t)?new X(t,Z.SESSION_EXPIRED,`authorization`):new X(t,Z.REGISTRATION_FAILED,`registration`)}function OB(e){let t;try{t=Qn(e)}catch(e){throw CB(L(e)||`Invalid linked-device QR payload`)}let n=Date.now();if(t.issuedAtMs>n+6e4)throw CB(`QR payload was issued in the future`);if(t.expiresAtMs<=n)throw new X(`QR code expired`,Z.SESSION_EXPIRED,`authorization`);return t}async function kB(e,t,n,r,i){let a=null,o=null;TB(n.onEvent,a,{phase:Zi.STEP_02_QR_SCAN_STARTED,status:`started`,message:`Review the device link`,interaction:{kind:`qr_scan`,overlay:`show`}});try{a=OB(t);let e=await r.ownerAuthorization.authenticateOwnerForLinkingV1({payload:a,requestedAtMs:Date.now()});EB(e.ownerAuthorization,e.authentication.source),TB(n.onEvent,a,{phase:Zi.STEP_02_QR_SCAN_STARTED,status:`started`,message:`Linking the approved device`,interaction:{kind:`qr_scan`,overlay:`hide`}});let s=await r.transport.claimSessionV1({request:Jn(a),authentication:e.authentication});if(s.linkSessionId!==a.linkSessionId||s.devicePublicKeyB64u!==a.devicePublicKeyB64u||s.walletId!==e.walletId)throw Error(`linked-device claim does not match the scanned QR payload`);o={linkSessionId:s.linkSessionId,expectedRevision:s.sessionRevision,authentication:e.authentication},i?.(o);let c=await jB({targetFactor:a.targetFactor,targetEmail:a.targetFactor.kind===`email_otp`?a.targetEmail:void 0,linkSessionId:s.linkSessionId,sessionRevision:s.sessionRevision,transport:r.transport,authentication:e.authentication,onEmailOtpBaseFactorRequired:n.onEmailOtpBaseFactorRequired}),l=wr({linkSessionId:s.linkSessionId,walletId:s.walletId,enrollmentId:s.enrollmentId,deviceId:s.deviceId,linkPublicKeyB64u:a.linkPublicKeyB64u,devicePublicKeyB64u:s.devicePublicKeyB64u,targetFactor:c,permission:a.requestedPermission,ownerAuthorization:e.ownerAuthorization,approvedAtMs:Date.now(),expiresAtMs:Math.min(e.expiresAtMs,s.claimExpiresAtMs)});IB(await r.transport.recordOwnerApprovalV1({approval:l,authentication:e.authentication})),o=null,await HB({transport:r.transport,linkSessionId:s.linkSessionId,walletId:s.walletId,enrollmentId:s.enrollmentId,deviceId:s.deviceId,expiresAtMs:Math.min(e.expiresAtMs,s.claimExpiresAtMs),exportRootRequirement:e.exportRootRequirement,ed25519ExportRootCapability:e.exportRootRequirement===`required`?e.ed25519ExportRootCapability:void 0,ed25519ExportRoot:r.ed25519ExportRoot,authentication:e.authentication}),await LB({transport:r.transport,sourceContribution:r.sourceContribution,ed25519ExportRootCapability:e.exportRootRequirement===`required`?e.ed25519ExportRootCapability:void 0,initialApproval:l,authentication:e.authentication,expiresAtMs:Math.min(e.expiresAtMs,s.claimExpiresAtMs)});let u={success:!0,kind:`approval_recorded`,walletId:s.walletId,enrollmentId:s.enrollmentId,deviceId:s.deviceId};return TB(n.onEvent,a,{phase:Zi.STEP_02_QR_SCAN_STARTED,status:`succeeded`,message:`Device-link approval recorded`,walletId:String(s.walletId),data:{enrollmentId:String(s.enrollmentId)},interaction:{kind:`qr_scan`,overlay:`hide`}}),await n.afterCall?.(!0,u),u}catch(e){o&&(await AB(r.transport,o),i?.(null));let t=DB(e);throw TB(n.onEvent,a,{phase:Zi.FAILED,status:`failed`,message:t.message,interaction:{kind:`qr_scan`,overlay:`hide`},error:{code:t.code,message:t.message,retryable:t.code!==Z.SESSION_EXPIRED}}),wB(n.onError,t),await n.afterCall?.(!1,void 0,t),t}}async function AB(e,t){t&&await e.cancelClaimedSessionV1(t).catch(()=>void 0)}async function jB(e){if(e.targetFactor.kind===`passkey_prf`)return{kind:`passkey_prf`};let t=PB(e.targetEmail),n=await e.transport.resolveEmailOtpBaseFactorV1({linkSessionId:e.linkSessionId,request:{kind:`resolve`,expectedRevision:e.sessionRevision},authentication:e.authentication});switch(NB(n,e.sessionRevision),n.resolution.kind){case`selected`:return{kind:`email_otp`,targetEmail:t,enrollment:{kind:`existing_enrollment`},baseWalletAuthMethodId:n.resolution.choice.baseWalletAuthMethodId};case`selection_required`:return await MB(e,n.resolution.choices);case`unavailable`:return{kind:`email_otp`,targetEmail:t,enrollment:{kind:`new_enrollment`}}}}async function MB(e,t){if(!e.onEmailOtpBaseFactorRequired)throw Error(`Choose the Email OTP method to use for the linked device`);let n=await e.onEmailOtpBaseFactorRequired(t);if(!FB(t,n))throw Error(`The selected Email OTP method is unavailable for this linked device`);let r=await e.transport.resolveEmailOtpBaseFactorV1({linkSessionId:e.linkSessionId,request:{kind:`select`,expectedRevision:e.sessionRevision,baseWalletAuthMethodId:n},authentication:e.authentication});if(NB(r,e.sessionRevision),r.resolution.kind!==`selected`||r.resolution.choice.baseWalletAuthMethodId!==n)throw Error(`The selected Email OTP method is unavailable for this linked device`);return{kind:`email_otp`,targetEmail:PB(e.targetEmail),enrollment:{kind:`existing_enrollment`},baseWalletAuthMethodId:n}}function NB(e,t){if(e.revision!==t)throw e.resolution.kind===`unavailable`?Error(`linked-device Email OTP target-factor resolution failed: ${e.resolution.reason}`):Error(`linked-device Email OTP target-factor resolution changed the session`)}function PB(e){if(!e)throw Error(`Email OTP linked-device QR omitted its target email`);return e}function FB(e,t){for(let n of e)if(n.baseWalletAuthMethodId===t)return!0;return!1}function IB(e){switch(e.outcome){case`pending`:return;case`replayed`:if(e.replay.state===`pending`)return;throw Error(`linked-device approval replay returned an unsupported session state`);default:{let t=e;throw Error(`unsupported linked-device approval result: ${String(t)}`)}}}async function LB(e){let t=null,n=0;for(;Date.now()<e.expiresAtMs&&(t=await e.transport.getSourceContributionPreparationV1({linkSessionId:e.initialApproval.linkSessionId,authentication:e.authentication}),!t);)await GB(n),n+=1;if(!t)throw new X(`Device-link approval expired before target source preparation was published`,Z.SESSION_EXPIRED,`registration`);let r=await zB({preparation:t,ports:e.sourceContribution,ed25519ExportRootCapability:e.ed25519ExportRootCapability,authentication:e.authentication}),i=RB(e.initialApproval,r);VB(await e.transport.recordSourceContributionV1({approval:i,authentication:e.authentication}))}function RB(e,t){return e.targetFactor.kind,wr({linkSessionId:e.linkSessionId,walletId:e.walletId,enrollmentId:e.enrollmentId,deviceId:e.deviceId,linkPublicKeyB64u:e.linkPublicKeyB64u,devicePublicKeyB64u:e.devicePublicKeyB64u,targetFactor:e.targetFactor,permission:e.permission,ownerAuthorization:e.ownerAuthorization,approvedAtMs:e.approvedAtMs,expiresAtMs:e.expiresAtMs,sourceContribution:t})}async function zB(e){let t=e.preparation[0];if(!t)throw Error(`source contribution preparation is empty`);if(BB(t)){if(!e.ed25519ExportRootCapability)throw Error(`Ed25519 export-root capability is required for source contribution`);let n=await e.ports.ed25519.produceSourceContributionV1({preparation:t,capability:e.ed25519ExportRootCapability,authentication:e.authentication}),r=e.preparation[1];if(!r)return[n];if(BB(r))throw Error(`source contribution preparation repeats Ed25519`);return[n,await e.ports.ecdsa.produceSourceContributionV1({preparation:r})]}if(e.preparation.length!==1)throw Error(`ECDSA source contribution preparation is out of order`);return[await e.ports.ecdsa.produceSourceContributionV1({preparation:t})]}function BB(e){return`kind`in e}function VB(e){if(e.state.state!==`authority_pending_local_install`&&e.state.state!==`active`)throw Error(`source contribution acknowledgement did not commit the linked device`)}async function HB(e){if(e.exportRootRequirement===`not_required`)return;if(!e.ed25519ExportRootCapability)throw Error(`Ed25519 export-root capability is required for this authority`);let t=null,n=0;for(;Date.now()<e.expiresAtMs;){if(!t){let n=await e.transport.getEd25519ExportRootRecipientV1({linkSessionId:e.linkSessionId,authentication:e.authentication});if(n){if(String(n.linkSessionId)!==String(e.linkSessionId)||String(n.walletId)!==String(e.walletId)||String(n.enrollmentId)!==String(e.enrollmentId)||String(n.deviceId)!==String(e.deviceId))throw Error(`Ed25519 export-root recipient differs from the approved linked-device session`);t=await e.ed25519ExportRoot.sealForLinkedDeviceV1({recipient:n,capability:e.ed25519ExportRootCapability,sealedAtMs:Date.now()})}}if(t)try{await e.transport.submitEd25519ExportRootPackageV1({submission:{kind:`linked_device_ed25519_export_root_submission_v1`,linkSessionId:e.linkSessionId,package:t},authentication:e.authentication});return}catch(e){let t=UB(e);if(t!==null&&t!==408&&t!==429&&t<500)throw e}await GB(n),n+=1}throw new X(`Device-link approval expired before the export root recipient was published`,Z.SESSION_EXPIRED,`registration`)}function UB(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`status`);return typeof t==`number`&&Number.isSafeInteger(t)?t:null}function WB(e,t){setTimeout(e,$z(250,t))}async function GB(e){await new Promise(t=>WB(t,e))}async function KB(e){let t=await e.ed25519ExportRoot.createRecipientV1({identity:e.identity,registeredAtMs:e.registeredAtMs});try{await e.transport.registerEd25519ExportRootRecipientV1({recipient:t.registration})}catch(n){throw await JB(e.ed25519ExportRoot,t),n}return t}async function qB(e){let t=e.nowMs??Date.now,n=await YB({transport:e.transport,recipient:e.recipient.registration,expiresAtMs:e.expiresAtMs,assertCurrentRun:e.assertCurrentRun,waitForPollV1:e.waitForPollV1,now:t});return await e.ed25519ExportRoot.acceptTransferV1({recipient:e.recipient,transferPackage:n,replacementEnvelope:e.replacementEnvelope,replacementFactorSecret:e.replacementFactorSecret})}async function JB(e,t){try{await e.discardRecipientV1(t)}catch{}}async function YB(e){let t=S(e.recipient.linkSessionId);if(!t.ok)throw Error(t.error.message);let n=0;for(;e.now()<e.expiresAtMs;){e.assertCurrentRun();let r=await e.transport.getEd25519ExportRootPackageV1({linkSessionId:t.value});if(r){if(!XB(r,e.recipient))throw new X(`Device-link Ed25519 export-root package is addressed to another device`,Z.REGISTRATION_FAILED,`registration`);return r}await e.waitForPollV1(n),n+=1}throw new X(`Device-link session expired before the Ed25519 export root was sealed`,Z.SESSION_EXPIRED,`registration`)}function XB(e,t){return e.linkSessionId===t.linkSessionId&&e.walletId===t.walletId&&e.walletKeyId===t.walletKeyId&&e.enrollmentId===t.enrollmentId&&e.deviceId===t.deviceId&&e.applicationBindingDigestB64u===t.applicationBindingDigestB64u&&e.registeredPublicKeyB64u===t.registeredPublicKeyB64u&&e.targetFactor.kind===t.targetFactor.kind&&e.revocationEpoch===t.revocationEpoch&&e.recipientPublicKeyB64u===t.recipientPublicKeyB64u}function ZB(e){if(e.binding.kind!==`ed25519_yao_client_root_v1`)throw Error(`Ed25519 export-root replacement binding has the wrong custody kind`);if(!Number.isSafeInteger(e.createdAtMs)||e.createdAtMs<0)throw Error(`Ed25519 export-root replacement timestamp is invalid`);return{envelopeId:e.envelopeId,walletId:e.walletId,ownership:e.ownership,binding:e.binding,factor:e.factor,createdAtMs:e.createdAtMs}}function QB(e){return{async createRecipientV1(t){let n=nV(await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`createLinkedDeviceEd25519ExportRootRecipient`,payload:{}}}),`Ed25519 export-root recipient`);return{recipientHandleId:rV(n.recipientHandleId),registration:Kn({kind:`linked_device_ed25519_export_root_recipient_v1`,linkSessionId:t.identity.linkSessionId,walletId:t.identity.walletId,walletKeyId:t.identity.walletKeyId,enrollmentId:t.identity.enrollmentId,deviceId:t.identity.deviceId,transferAlg:zn,applicationBindingDigestB64u:t.identity.applicationBindingDigestB64u,registeredPublicKeyB64u:t.identity.registeredPublicKeyB64u,targetFactor:t.identity.targetFactor,revocationEpoch:t.identity.revocationEpoch,recipientPublicKeyB64u:tr(n.recipientPublicKeyB64u),registeredAtMs:t.registeredAtMs})}},async sealForLinkedDeviceV1(t){let n=t.recipient;if(t.capability.walletId!==String(n.walletId))throw Error(`Ed25519 export-root capability names another wallet`);let r=er({linkSessionId:n.linkSessionId,walletId:n.walletId,walletKeyId:n.walletKeyId,targetFactor:n.targetFactor,enrollmentId:n.enrollmentId,deviceId:n.deviceId,revocationEpoch:n.revocationEpoch,applicationBindingDigestB64u:n.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,recipientPublicKeyB64u:n.recipientPublicKeyB64u}),i=nV(await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`sealEd25519ExportRootForLinkedDevice`,payload:{capability:t.capability,transferBindingJson:kn(r)}}}),`Ed25519 export-root seal`);return{kind:`linked_device_ed25519_export_root_package_v1`,linkSessionId:n.linkSessionId,walletId:n.walletId,walletKeyId:n.walletKeyId,enrollmentId:n.enrollmentId,deviceId:n.deviceId,transferAlg:zn,applicationBindingDigestB64u:n.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,targetFactor:n.targetFactor,revocationEpoch:n.revocationEpoch,recipientPublicKeyB64u:n.recipientPublicKeyB64u,ephemeralPublicKeyB64u:tr(i.ephemeralPublicKeyB64u,`Ed25519 export-root ephemeralPublicKeyB64u`),nonceB64u:Ve(i.nonceB64u,`Ed25519 export-root nonceB64u`),sealedExportRootB64u:Me(i.sealedExportRootB64u,`Ed25519 export-root sealedExportRootB64u`),bindingDigestB64u:De(i.bindingDigestB64u,`Ed25519 export-root bindingDigestB64u`),ciphertextDigestB64u:De(i.ciphertextDigestB64u,`Ed25519 export-root ciphertextDigestB64u`),sealedAtMs:t.sealedAtMs}},async acceptTransferV1(t){let n=t.recipient.registration,r=t.transferPackage;if(!$B(r,n))throw Error(`Ed25519 export-root package is addressed to another device`);let i=er({linkSessionId:n.linkSessionId,walletId:n.walletId,walletKeyId:n.walletKeyId,targetFactor:n.targetFactor,enrollmentId:n.enrollmentId,deviceId:n.deviceId,revocationEpoch:n.revocationEpoch,applicationBindingDigestB64u:n.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,recipientPublicKeyB64u:n.recipientPublicKeyB64u}),a=t.replacementEnvelope;if(a.walletId!==n.walletId||a.binding.kind!==`ed25519_yao_client_root_v1`||a.binding.walletKeyId!==n.walletKeyId||a.binding.linkSessionId!==n.linkSessionId||a.binding.enrollmentId!==n.enrollmentId||a.binding.deviceId!==n.deviceId||a.binding.applicationBindingDigestB64u!==n.applicationBindingDigestB64u||a.binding.registeredPublicKeyB64u!==n.registeredPublicKeyB64u||a.binding.revocationEpoch!==n.revocationEpoch||!eV(n.targetFactor,a.factor))throw Error(`Ed25519 export-root replacement envelope identity is invalid`);let o=gn({walletId:a.walletId,envelopeId:a.envelopeId,factor:a.factor,envelopeRevision:Te(1),binding:a.binding,ownership:a.ownership}),s=t.replacementFactorSecret.slice();try{let n=nV(await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`acceptLinkedDeviceEd25519ExportRoot`,payload:{recipientHandleId:t.recipient.recipientHandleId,transferBindingJson:kn(i),ephemeralPublicKeyB64u:String(r.ephemeralPublicKeyB64u),nonceB64u:String(r.nonceB64u),sealedExportRootB64u:String(r.sealedExportRootB64u),bindingDigestB64u:String(r.bindingDigestB64u),ciphertextDigestB64u:String(r.ciphertextDigestB64u),replacementEnvelopeBindingJson:o,replacementFactorSecret:s.buffer},transfer:[s.buffer]}}),`Ed25519 export-root acceptance`);return{envelope:vn(fn({envelopeId:a.envelopeId,walletId:a.walletId,ownership:a.ownership,binding:a.binding,factor:a.factor,envelopeRevision:Te(1),nonceB64u:Ve(n.nonceB64u,`Ed25519 export-root resealed nonceB64u`),sealedCustodySecretB64u:Me(n.sealedExportRootB64u,`Ed25519 export-root resealed ciphertext`),aadHashB64u:De(n.aadHashB64u,`Ed25519 export-root resealed aadHashB64u`),ciphertextDigestB64u:De(n.ciphertextDigestB64u,`Ed25519 export-root resealed ciphertextDigestB64u`),lifecycle:un({activatedAtMs:a.createdAtMs}),createdAtMs:a.createdAtMs,updatedAtMs:a.createdAtMs}))}}finally{s.byteLength>0&&s.fill(0)}},async discardRecipientV1(t){await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`discardLinkedDeviceEd25519ExportRootRecipient`,payload:{recipientHandleId:t.recipientHandleId}}})}}}function $B(e,t){return e.linkSessionId===t.linkSessionId&&e.walletId===t.walletId&&e.walletKeyId===t.walletKeyId&&e.enrollmentId===t.enrollmentId&&e.deviceId===t.deviceId&&e.applicationBindingDigestB64u===t.applicationBindingDigestB64u&&e.registeredPublicKeyB64u===t.registeredPublicKeyB64u&&e.targetFactor.kind===t.targetFactor.kind&&e.revocationEpoch===t.revocationEpoch&&e.recipientPublicKeyB64u===t.recipientPublicKeyB64u}function eV(e,t){switch(e.kind){case`passkey_prf`:return t.kind===`passkey`;case`email_otp`:return t.kind===`email_otp`}return tV(e)}function tV(e){throw Error(`Unsupported linked-device target factor kind: ${String(e)}`)}function nV(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} returned no result`);return e}function rV(e){if(typeof e!=`string`||!e||e.trim()!==e)throw Error(`Ed25519 export-root recipient handle is invalid`);return e}const iV=`linked_device_committed_resume_v1`,aV=`linked_device_pending_ack_v1`,oV=`device-linking/committed-resume/v1/`,sV=`device-linking/pending-ack/v1/`,cV=[`kind`,`acknowledgement`],lV=[`kind`,`linkSessionId`,`walletId`,`enrollmentId`,`authorityId`,`authMethodId`,`deviceId`,`targetFactorKind`,`targetFactorVerificationDigestB64u`,`authorityDigestB64u`,`signerActivationSetDigestB64u`,`signerActivations`,`packageSetDigestB64u`,`committedAtMs`];function uV(e){return`${oV}${String(e)}`}function dV(e){return`${sV}${String(e)}`}function fV(e){return{kind:aV,acknowledgement:mr(e)}}function pV(e){let t=vV(e);if(t===null||!vo(t,cV)||t.kind!==aV)return null;try{return{kind:aV,acknowledgement:mr(t.acknowledgement)}}catch{return null}}function mV(e){let t=e.committed.authority;if(t.provenance.kind!==`device_link`)throw Error(`committed link authority provenance is invalid`);if(t.provenance.linkSessionId!==e.linkSessionId)throw Error(`committed link session identity differs from authority provenance`);if(e.committed.authMethod.walletAuthMethodId!==e.targetFactor.authMethod.walletAuthMethodId)throw Error(`committed link auth method differs from target factor`);if(!Number.isSafeInteger(e.committedAtMs)||e.committedAtMs<=0)throw Error(`committed link resume timestamp is invalid`);return{kind:iV,linkSessionId:e.linkSessionId,walletId:t.walletId,enrollmentId:t.provenance.enrollmentId,authorityId:t.authorityId,authMethodId:e.committed.authMethod.walletAuthMethodId,deviceId:t.principal.deviceId,targetFactorKind:e.targetFactor.kind,targetFactorVerificationDigestB64u:e.targetFactor.verificationDigestB64u,authorityDigestB64u:t.authorityDigestB64u,signerActivationSetDigestB64u:t.signerActivationSetDigestB64u,signerActivations:t.signerActivations,packageSetDigestB64u:e.committed.packageSetDigestB64u,committedAtMs:e.committedAtMs}}function hV(e){let t=mV({linkSessionId:e.linkSessionId,committed:e.committed,targetFactor:e.targetFactor,committedAtMs:e.resume.committedAtMs});return e.resume.authorityId===t.authorityId?e.resume.linkSessionId!==t.linkSessionId||e.resume.enrollmentId!==t.enrollmentId?{kind:`package_set_digest_mismatch`,expectedPackageSetDigestB64u:e.resume.packageSetDigestB64u,actualPackageSetDigestB64u:t.packageSetDigestB64u}:e.resume.walletId===t.walletId?e.resume.authMethodId===t.authMethodId?e.resume.deviceId===t.deviceId?e.resume.targetFactorKind!==t.targetFactorKind||e.resume.targetFactorVerificationDigestB64u!==t.targetFactorVerificationDigestB64u?{kind:`installation_receipt_mismatch`,field:`targetFactorVerificationDigestB64u`}:e.resume.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u?e.resume.authorityDigestB64u!==t.authorityDigestB64u||e.resume.packageSetDigestB64u!==t.packageSetDigestB64u?{kind:`package_set_digest_mismatch`,expectedPackageSetDigestB64u:e.resume.packageSetDigestB64u,actualPackageSetDigestB64u:t.packageSetDigestB64u}:bV(e.resume.signerActivations,t.signerActivations)?null:{kind:`installation_receipt_mismatch`,field:`installedActivationRefs`}:{kind:`installation_receipt_mismatch`,field:`installedActivationRefs`}:{kind:`installation_receipt_mismatch`,field:`deviceId`}:{kind:`installation_receipt_mismatch`,field:`authMethodId`}:{kind:`installation_receipt_mismatch`,field:`walletId`}:{kind:`authority_id_mismatch`,expectedAuthorityId:e.resume.authorityId,actualAuthorityId:t.authorityId}}function gV(e){let t=vV(e);if(t===null||!vo(t,lV)||t.kind!==iV)return null;let n=S(t.linkSessionId),i=_(t.walletId),a=f(t.enrollmentId),o=s(t.authorityId),c=r(t.authMethodId),l=Dt(t.deviceId);if(!n.ok||!i.ok||!a.ok||!o.ok||!c.ok||!l.ok||t.targetFactorKind!==`verified_passkey_target_v1`&&t.targetFactorKind!==`verified_email_otp_target_v1`)return null;let u=zr(t.signerActivations);if(!u.ok)return null;let d=t.committedAtMs;if(typeof d!=`number`||!Number.isSafeInteger(d)||d<=0)return null;try{return{kind:iV,linkSessionId:n.value,walletId:i.value,enrollmentId:a.value,authorityId:o.value,authMethodId:c.value,deviceId:l.value,targetFactorKind:t.targetFactorKind,targetFactorVerificationDigestB64u:Pt(t.targetFactorVerificationDigestB64u),authorityDigestB64u:Pt(t.authorityDigestB64u),signerActivationSetDigestB64u:Pt(t.signerActivationSetDigestB64u),signerActivations:u.value,packageSetDigestB64u:Pt(t.packageSetDigestB64u),committedAtMs:d}}catch{return null}}async function _V(e){let[t,n]=await Promise.all([e.installation.listCommittedDeliveryResumesV1(),e.installation.listPendingActivationAcknowledgementsV1()]),r=t.filter(t=>t.authorityId===e.authorityId),i=n.filter(t=>t.authorityId===e.authorityId);if(i.length===0)return{kind:`none`};for(let t of i){let n=r.find(e=>e.linkSessionId===t.linkSessionId&&e.packageSetDigestB64u===t.packageSetDigestB64u);if(!n)throw Error(`durable linked-device acknowledgement has no matching resume`);if(n.walletId!==e.walletId||n.authMethodId!==e.authMethodId)throw Error(`durable linked-device acknowledgement identity changed`);await e.transport.acknowledgeLocalAuthorityActivationWithWalletSessionV1({acknowledgement:t,operationCredential:e.operationCredential}),await e.installation.clearPendingActivationAcknowledgementV1({authorityId:t.authorityId}),await e.installation.clearCommittedDeliveryResumeV1({authorityId:t.authorityId})}return{kind:`replayed`}}function vV(e){return yV(e)?e:null}function yV(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}catch{return!1}}function bV(e,t){let n=Wr(e),r=Wr(t);return n.length===r.length&&n.every((e,t)=>e===r[t])}function xV(e,t){let n=String(e.walletId);switch(e.kind){case`passkey`:{let t=String(e.credentialIdB64u);return{profile:{profileId:n,defaultSignerSlot:1,passkeyCredential:{id:t,rawId:t}},authenticator:{profileId:n,signerSlot:1,credentialId:t,credentialPublicKey:F(e.credentialPublicKeyB64u),registered:new Date(e.createdAtMs).toISOString(),syncedAt:new Date(e.updatedAtMs).toISOString()},localAuthMethod:null}}case`email_otp`:{if(t.kind!==`verified_email_otp_target_v1`||t.authMethod.walletAuthMethodId!==e.walletAuthMethodId||t.authMethod.walletId!==e.walletId||t.authMethod.emailHashHex!==e.emailHashHex||t.authMethod.registrationAuthorityId!==e.registrationAuthorityId)throw Error(`linked Email OTP target factor does not match the committed auth method`);let r=di({walletId:e.walletId,provider:t.enrollment.kind===`existing_enrollment`?`google`:`email`,providerUserId:t.providerUserId,emailHashHex:e.emailHashHex});return{profile:{profileId:n,defaultSignerSlot:1},authenticator:null,localAuthMethod:{version:`wallet_auth_method_v1`,kind:`email_otp`,status:`active`,localStatus:`synced`,walletId:e.walletId,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId,authority:{walletId:r.walletId,factor:r.factor,verifier:r.verifier,bindingId:e.walletAuthMethodId},createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs}}}default:{let t=e;throw Error(`Unsupported linked-device auth method: ${String(t)}`)}}}function SV(e){return{...CV({indexedDB:e.indexedDB}),persistCommittedDeliveryResumeV1:async t=>{let n=mV(t);await e.indexedDB.setAppState(uV(n.authorityId),n)},readCommittedDeliveryResumeV1:async({authorityId:t})=>gV(await e.indexedDB.getAppState(uV(t))),persistPendingActivationAcknowledgementV1:async({acknowledgement:t})=>{let n=fV(t);await e.indexedDB.setAppState(dV(t.authorityId),n)},readPendingActivationAcknowledgementV1:async({authorityId:t})=>pV(await e.indexedDB.getAppState(dV(t)))?.acknowledgement??null,readLocalAuthorityInstallationReceiptV1:async({authorityId:t})=>await e.indexedDB.getLocalAuthorityInstallationReceipt(t),installLocalAuthorityV1:t=>wV({...t,...e}),publishLocalAuthorityActivationV1:({active:t,expectedLockGeneration:n})=>TV({indexedDB:e.indexedDB,active:t,expectedLockGeneration:n}),finalizeLocalAuthorityActivationV1:({active:t,operationCredential:n,expectedLockGeneration:r})=>EV({indexedDB:e.indexedDB,active:t,operationCredential:n,expectedLockGeneration:r})}}function CV(e){return{listCommittedDeliveryResumesV1:async()=>(await e.indexedDB.listAppStateEntriesByPrefix(oV)).flatMap(e=>{if(e.value===null)return[];let t=gV(e.value);if(!t||uV(t.authorityId)!==e.key)throw Error(`durable linked-device delivery resume is corrupt`);return[t]}),listPendingActivationAcknowledgementsV1:async()=>(await e.indexedDB.listAppStateEntriesByPrefix(sV)).flatMap(e=>{if(e.value===null)return[];let t=pV(e.value);if(!t||dV(t.acknowledgement.authorityId)!==e.key)throw Error(`durable linked-device acknowledgement is corrupt`);return[t.acknowledgement]}),clearCommittedDeliveryResumeV1:async({authorityId:t})=>{await e.indexedDB.setAppState(uV(t),null)},clearPendingActivationAcknowledgementV1:async({authorityId:t})=>{await e.indexedDB.setAppState(dV(t),null)}}}async function wV(e){let t=await e.indexedDB.getLocalAuthorityInstallationReceipt(e.committed.authority.authorityId);if(t)return NV({committed:e.committed,targetFactor:e.targetFactor,receipt:t}),t;let n=await e.sealing.sealCommittedAuthorityPackagesV1({committed:e.committed,targetFactor:e.targetFactor,keyMaterial:e.keyMaterial,resealedExportRoot:e.resealedExportRoot});MV({committed:e.committed,sealed:n});let r=xV(e.committed.authMethod,e.targetFactor),i=e.nowMs();if(!Number.isSafeInteger(i)||i<=0)throw Error(`local authority installation clock is invalid`);let a={kind:`local_authority_installation_receipt_v1`,authorityId:e.committed.authority.authorityId,walletId:e.committed.authority.walletId,authMethodId:e.committed.authMethod.walletAuthMethodId,deviceId:e.committed.authority.principal.deviceId,packageSetDigestB64u:e.committed.packageSetDigestB64u,installedActivationRefs:e.committed.authority.signerActivations,installedRecordSetDigestB64u:n.installedRecordSetDigestB64u,targetFactorVerificationDigestB64u:e.targetFactor.verificationDigestB64u,installedAtMs:i},o=await e.indexedDB.installLocalAuthority({authority:e.committed.authority,authMethod:e.committed.authMethod,profile:r.profile,authenticator:r.authenticator,localAuthMethod:r.localAuthMethod,signerMaterials:n.signerMaterials,exportRoot:n.exportRoot,receipt:a,expectedLockGeneration:e.expectedLockGeneration});switch(o.kind){case`installed`:case`idempotent_replay`:return o.receipt;case`stale_lock_generation`:throw Error(`local authority installation lock generation is stale (expected ${o.expectedLockGeneration}, actual ${o.actualLockGeneration})`);case`integrity_error`:throw Error(`local authority installation integrity error: ${o.reason}`)}}async function TV(e){let t=await e.indexedDB.publishLocalAuthorityActivation({authority:e.active.authority,authMethod:e.active.authMethod,expectedLockGeneration:e.expectedLockGeneration});switch(t.kind){case`published`:return;case`stale_lock_generation`:throw Error(`local authority activation lock generation is stale (expected ${t.expectedLockGeneration}, actual ${t.actualLockGeneration})`);case`wallet_locked`:throw Error(`local authority activation refused while wallet is locked at generation ${t.lockGeneration}`);default:throw Error(`local authority activation publication returned an unknown result`)}}async function EV(e){let t={authority:e.active.authority,authMethod:e.active.authMethod,walletSession:e.active.walletSession,operationCredential:e.operationCredential,expectedLockGeneration:e.expectedLockGeneration},n=await e.indexedDB.finalizeLocalAuthorityActivation(t);switch(n.kind){case`finalized`:return;case`stale_lock_generation`:throw Error(`local authority activation lock generation is stale (expected ${n.expectedLockGeneration}, actual ${n.actualLockGeneration})`);case`wallet_locked`:throw Error(`local authority activation refused while wallet is locked at generation ${n.lockGeneration}`);default:throw Error(`local authority activation returned an unknown result`)}}async function DV(e){let t=kV({committed:e.committed,sessionState:e.sessionState});if(t)return t;let n=await e.installation.readCommittedDeliveryResumeV1({authorityId:e.committed.authority.authorityId});if(n){let t=hV({resume:n,linkSessionId:e.linkSessionId,committed:e.committed,targetFactor:e.targetFactor});if(t)return{kind:`integrity_error`,reason:t}}else await e.installation.persistCommittedDeliveryResumeV1({linkSessionId:e.linkSessionId,committed:e.committed,targetFactor:e.targetFactor,committedAtMs:e.nowMs()});let r=await e.installation.installLocalAuthorityV1({committed:e.committed,targetFactor:e.targetFactor,keyMaterial:e.keyMaterial,resealedExportRoot:e.resealedExportRoot,expectedLockGeneration:e.expectedLockGeneration}),i=await e.transport.activateInstalledAuthorityV1({linkSessionId:e.linkSessionId,receipt:r});switch(i.kind){case`pending_local_install`:return{kind:`pending_local_install`,authorityId:i.authorityId,packageSetDigestB64u:r.packageSetDigestB64u};case`integrity_error`:return i;case`active`:{let t=AV({active:i,receipt:r});if(t)return t;await e.installation.publishLocalAuthorityActivationV1({active:i,expectedLockGeneration:e.expectedLockGeneration}),await or(i.sealedDelivery),await jV({active:i,receipt:r,linkSessionId:e.linkSessionId,deliveryRecipientPublicKey65B64u:e.deliveryRecipientPublicKey65B64u}),await e.installation.persistPendingActivationAcknowledgementV1({acknowledgement:await OV({active:i,receipt:r,linkSessionId:e.linkSessionId,acknowledgedAtMs:e.nowMs()})});let n=await e.keyMaterialPort.openWalletSessionCredentialDeliveryV1({keyMaterial:e.keyMaterial,delivery:i.sealedDelivery,expected:{linkSessionId:e.linkSessionId,walletId:i.walletSession.walletId,authorityId:i.walletSession.authorityId,walletAuthMethodId:i.walletSession.authMethodId,authorizationId:i.walletSession.authorizationId,walletSessionId:i.sealedDelivery.aad.walletSessionId,quotaId:i.walletSession.quotaId,deliveryBinding:i.deliveryBinding,credentialDigestB64u:i.sealedDelivery.aad.credentialDigestB64u,installationReceiptDigestB64u:i.sealedDelivery.installationReceiptDigestB64u,recipientPublicKey65B64u:e.deliveryRecipientPublicKey65B64u,issuedAtMs:i.walletSession.issuedAtMs,expiresAtMs:i.walletSession.expiresAtMs}});return await e.installation.finalizeLocalAuthorityActivationV1({active:i,operationCredential:n,expectedLockGeneration:e.expectedLockGeneration}),{kind:`active`,session:i.walletSession,operationCredential:n}}}}async function OV(e){if(!Number.isSafeInteger(e.acknowledgedAtMs)||e.acknowledgedAtMs<=0)throw Error(`linked-device acknowledgement clock is invalid`);return{kind:`local_authority_activation_final_ack_v1`,linkSessionId:e.linkSessionId,authorityId:e.active.authority.authorityId,packageSetDigestB64u:e.receipt.packageSetDigestB64u,authorizationId:e.active.sealedDelivery.aad.authorizationId,walletSessionId:e.active.sealedDelivery.aad.walletSessionId,credentialDigestB64u:e.active.sealedDelivery.aad.credentialDigestB64u,installationReceiptDigestB64u:await _r(e.receipt),acknowledgedAtMs:e.acknowledgedAtMs}}function kV(e){return e.sessionState.state===`provisioning`?null:e.committed.authority.authorityId===e.sessionState.authorityId?e.sessionState.state!==`active`&&e.committed.packageSetDigestB64u!==e.sessionState.packageSetDigestB64u?{kind:`integrity_error`,reason:{kind:`package_set_digest_mismatch`,expectedPackageSetDigestB64u:e.sessionState.packageSetDigestB64u,actualPackageSetDigestB64u:e.committed.packageSetDigestB64u}}:null:{kind:`integrity_error`,reason:{kind:`authority_id_mismatch`,expectedAuthorityId:e.sessionState.authorityId,actualAuthorityId:e.committed.authority.authorityId}}}function AV(e){return e.active.authority.authorityId===e.receipt.authorityId?e.active.authority.walletId!==e.receipt.walletId||e.active.walletSession.walletId!==e.receipt.walletId?{kind:`integrity_error`,reason:{kind:`installation_receipt_mismatch`,field:`walletId`}}:e.active.authMethod.walletAuthMethodId!==e.receipt.authMethodId||e.active.walletSession.authMethodId!==e.receipt.authMethodId?{kind:`integrity_error`,reason:{kind:`installation_receipt_mismatch`,field:`authMethodId`}}:null:{kind:`integrity_error`,reason:{kind:`authority_id_mismatch`,expectedAuthorityId:e.receipt.authorityId,actualAuthorityId:e.active.authority.authorityId}}}async function jV(e){let t=e.active.sealedDelivery.aad,n=e.active.deliveryBinding,r=e.active.sealedDelivery.installationReceiptDigestB64u,i=await _r(e.receipt);if(n.namespace!==t.namespace||n.orgId!==t.orgId||n.projectId!==t.projectId||n.envId!==t.envId||n.tenantId!==t.tenantId||n.principalId!==t.principalId||t.linkSessionId!==e.linkSessionId||t.walletId!==e.receipt.walletId||t.authorityId!==e.receipt.authorityId||t.walletAuthMethodId!==e.receipt.authMethodId||t.authorizationId!==e.active.walletSession.authorizationId||t.quotaId!==e.active.walletSession.quotaId||String(t.principalId)!==`linked-device:${String(e.active.authority.principal.deviceId)}`||t.recipientPublicKey65B64u!==e.deliveryRecipientPublicKey65B64u||t.issuedAtMs!==e.active.walletSession.issuedAtMs||t.expiresAtMs!==e.active.walletSession.expiresAtMs||r!==i)throw Error(`linked-device Wallet Session credential delivery identity changed`)}function MV(e){let t=e.committed.authority,n=e.committed.authMethod,r=IV(t.signerActivations);if(e.sealed.signerMaterials.length!==r.length)throw Error(`sealed signer material count does not match committed authority`);for(let i=0;i<r.length;i+=1){let a=r[i],o=e.sealed.signerMaterials[i];if(!o||o.authorityId!==t.authorityId||o.walletAuthMethodId!==n.walletAuthMethodId||o.keyFamily!==a.keyFamily||o.activationId!==a.materialActivation.activationId||o.materialActivation.activationId!==a.materialActivation.activationId)throw Error(`sealed signer material identity does not match committed authority`)}if((FV(t.signerActivations)&&t.permissions.includes(`export_keys`))!==(e.sealed.exportRoot!==null))throw Error(`sealed Ed25519 export root presence does not match committed authority`);if(e.sealed.exportRoot&&(e.sealed.exportRoot.authorityId!==t.authorityId||e.sealed.exportRoot.walletAuthMethodId!==n.walletAuthMethodId))throw Error(`sealed export root identity does not match committed authority`);Pt(e.sealed.installedRecordSetDigestB64u)}function NV(e){if(e.receipt.authorityId!==e.committed.authority.authorityId||e.receipt.walletId!==e.committed.authority.walletId||e.receipt.authMethodId!==e.committed.authMethod.walletAuthMethodId||e.receipt.deviceId!==e.committed.authority.principal.deviceId||e.receipt.packageSetDigestB64u!==e.committed.packageSetDigestB64u||e.receipt.targetFactorVerificationDigestB64u!==e.targetFactor.verificationDigestB64u||!PV(e.receipt.installedActivationRefs,e.committed.authority.signerActivations))throw Error(`stored local authority receipt does not match committed packages`)}function PV(e,t){let n=Wr(e),r=Wr(t);if(n.byteLength!==r.byteLength)return!1;for(let e=0;e<n.byteLength;e+=1)if(n[e]!==r[e])return!1;return!0}function FV(e){return e.keyFamilies.length===2||e.keyFamilies[0]===`ed25519`}function IV(e){if(e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`){if(!e.ed25519)throw Error(`Ed25519 activation is missing`);return[{keyFamily:`ed25519`,materialActivation:e.ed25519.materialActivation}]}if(e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`){if(!e.ecdsa)throw Error(`ECDSA activation is missing`);return[{keyFamily:`ecdsa_secp256k1`,materialActivation:e.ecdsa.materialActivation}]}if(e.keyFamilies.length===2){if(!e.ed25519||!e.ecdsa)throw Error(`combined signer activations are incomplete`);return[{keyFamily:`ed25519`,materialActivation:e.ed25519.materialActivation},{keyFamily:`ecdsa_secp256k1`,materialActivation:e.ecdsa.materialActivation}]}throw Error(`committed signer activation families are invalid`)}function LV(e,t){switch(t.targetFactor.kind){case`verified_passkey_target_v1`:return{kind:`authenticated`,walletId:e.walletId,authMethod:R.passkey};case`verified_email_otp_target_v1`:return{kind:`authenticated`,walletId:e.walletId,authMethod:R.emailOtp};default:return t.targetFactor}}function RV(){let e=S(ve(`link-session`,32));if(!e.ok)throw Error(e.error.message);return e.value}function zV(){return ve(`link-flow`,16)}function BV(e,t){try{e?.(t)}catch{}}function VV(e){console.info(`[Device2Linking]`,{flowId:e.flowId,linkSessionId:e.linkSessionId,stage:e.stage,...e.details})}function HV(e){console.error(`[Device2Linking] failed`,{flowId:e.flowId,linkSessionId:e.linkSessionId,state:e.state,error:L(e.error)})}function UV(e,t){setTimeout(e,$z(250,t))}async function WV(e){await new Promise(t=>UV(t,e))}function GV(e){switch(e.state){case`displaying_qr`:case`expired`:case`cancelled`:return Zi.STEP_01_QR_PREPARE_STARTED;case`claimed`:case`awaiting_target_factor`:case`awaiting_source_contribution`:case`provisioning`:case`authority_pending_local_install`:case`active`:return Zi.STEP_02_QR_SCAN_STARTED;case`failed_before_commit`:return Zi.FAILED;default:return sr(e)}}function KV(e,t){return e instanceof X?e:new X(L(e)||`Device linking failed`,Z.REGISTRATION_FAILED,t)}function qV(e){let t=L(e).toLowerCase();return t.includes(`device-linking key handle is unknown or discarded`)||t.includes(`recipient handle lost`)?`recipient_private_handle_lost`:t.includes(`linked-device wallet session credential delivery is expired`)?`sealed_delivery_expired`:null}function JV(e){switch(e){case`recipient_private_handle_lost`:case`sealed_delivery_expired`:return`The linked device is ready. Return to sign in and unlock the new method to finish setup.`;default:return e}}var YV=class extends Error{constructor(){super(`Device-link flow was cancelled or reset`),this.name=`LinkDeviceFlowSupersededError`}};async function XV(t){let n;try{n=await import(`./browser-CKS7Tq2r.js`).then(t=>e(t.default,1))}catch{throw new X(`Device-link QR generation requires the optional qrcode package`,Z.UNSUPPORTED,`generation`)}return await n.toDataURL(t,{errorCorrectionLevel:`M`,margin:2})}function ZV(e){let t=Oe();return e.target.targetFactor.kind===`email_otp`?Sr({linkSessionId:e.linkSessionId,linkPublicKeyB64u:e.linkPublicKeyB64u,devicePublicKeyB64u:e.devicePublicKeyB64u,requestedPermission:t,targetFactor:{kind:`email_otp`},targetEmail:op(e.target.targetEmail),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs}):Sr({linkSessionId:e.linkSessionId,linkPublicKeyB64u:e.linkPublicKeyB64u,devicePublicKeyB64u:e.devicePublicKeyB64u,requestedPermission:t,targetFactor:{kind:`passkey_prf`},issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs})}function QV(e){return e.targetFactor.kind===`passkey_prf`}function $V(e){return e.targetFactor.kind===`email_otp`}function eH(e){return{event:e.event,state:e.state,runEpoch:e.runEpoch,deviceId:e.deviceId,preparation:e.preparation,ordinarySignerMaterialRecipientRequests:e.ordinarySignerMaterialRecipientRequests,exportRoot:e.exportRoot}}function tH(e){if(e.kind!==`completed`||!e.factorSecret||typeof e.providerUserId!=`string`)throw Error(`linked-device Email OTP factor runtime is unavailable`);return{kind:`completed`,runEpoch:e.runEpoch,enrollment:e.enrollment,factorSecret:e.factorSecret,providerUserId:e.providerUserId}}function nH(e){throw Error(`Unknown Email OTP target activation state: ${String(e)}`)}function rH(e){throw Error(`Unknown target credential activation state: ${String(e)}`)}function iH(e){switch(e.targetFactor.kind){case`verified_passkey_target_v1`:{let t=e.targetCredentialActivationState;if(t.kind!==`factor_ready`||t.runEpoch!==e.runEpoch)throw Error(`linked-device Passkey factor runtime is unavailable`);return{factor:{kind:`passkey`,walletId:e.walletId},factorSecret32:t.factorSecret}}case`verified_email_otp_target_v1`:{let t=tH(e.emailOtpTargetActivationState);if(t.runEpoch!==e.runEpoch)throw Error(`linked-device Email OTP factor runtime is unavailable`);return{factor:{kind:`email_otp`,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,emailHashHex:e.targetFactor.authMethod.emailHashHex,providerIdentity:{provider:sH(t.enrollment),providerSubjectId:t.providerUserId}},factorSecret32:t.factorSecret}}default:return aH(e.targetFactor)}}function aH(e){throw Error(`Unknown verified target factor kind: ${String(e)}`)}function oH(e){e.byteLength>0&&e.fill(0)}function sH(e){return e.kind===`existing_enrollment`?`google`:`email`}function cH(e){return e.passkeyCreationOptions.rpId}function lH(e){if(!$V(e))throw Error(`linked-device Email OTP preparation is unavailable`);return e}function uH(){let e=T(ve(`linked-device-ed25519-export-root-envelope`,24,`export-root envelope ids`));if(!e.ok)throw Error(e.error.message);return e.value}function dH(){return crypto.getRandomValues(new Uint8Array(32))}async function fH(e){let t=e.factorSecret.slice();try{let n=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:String(e.context.configs.network.relayer.url||``).trim(),walletId:e.walletId,userId:e.targetEmail,clientSecret32:t});if(n.emailOtpSessionHandle.kind!==`not_requested`)throw Error(`Strict linked-device Email OTP enrollment received obsolete ECDSA material`);return{enrollmentId:n.enrollmentId,enrollment:n.emailOtpEnrollment}}finally{oH(t)}}function pH(e){if(!e)throw Error(`new linked-device Email OTP enrollment material is unavailable`);return e}var mH=class{pendingActivationCompletion=null;options;ports;getAuthenticationContext;flowId;session=null;keyMaterialHandle=null;deliveryRecipientPublicKey65B64u=null;resealedExportRoot=null;targetCredentialRegistrationResult=null;committedAuthorityPackages=null;deliveryRecoveryReason=null;ordinarySignerMaterialRecipientPreparation=null;authenticatedTransport=null;subscription=null;error;cancelled=!1;runEpoch=0;generationInProgress=!1;discardInProgress=null;targetCredentialActivationState={kind:`idle`};emailOtpTargetActivationState={kind:`idle`};handledStates=new Set;sessionEventQueue=Promise.resolve();constructor(e,t,n=null){this.options=e,this.flowId=zV(),this.ports=t,this.getAuthenticationContext=n}async generateQR(){if(this.generationInProgress||this.keyMaterialHandle||this.subscription||this.session&&!this.cancelled)throw Error(`Device-link QR flow is already running`);let e=this.startRun(),t=this.ports;this.emit({phase:Zi.STEP_01_QR_PREPARE_STARTED,status:`started`,message:`Preparing device link`,data:{role:`display`},interaction:{kind:`qr_display`,overlay:`show`}});try{let n=await t.keyMaterial.createBootstrapKeyMaterialV1();if(!this.isCurrentRun(e))throw this.keyMaterialHandle=n.handle,await this.discardKeyMaterial(),new YV;this.keyMaterialHandle=n.handle,this.deliveryRecipientPublicKey65B64u=n.deliveryRecipientPublicKey65B64u;let r=Date.now(),i=RV(),a=ZV({linkSessionId:i,linkPublicKeyB64u:n.linkPublicKeyB64u,devicePublicKeyB64u:n.devicePublicKeyB64u,target:this.options,issuedAtMs:r,expiresAtMs:r+900*1e3}),o={state:`displaying_qr`},s=t.transport.createAuthenticatedSessionTransportV1({keyMaterial:n.handle,devicePublicKeyB64u:n.devicePublicKeyB64u});this.authenticatedTransport=s,this.session={linkSessionId:i,state:o,qrData:a},VV({flowId:this.flowId,linkSessionId:i,stage:`session_create_started`}),await s.createUnclaimedSessionV1({payload:a,state:o}),this.assertCurrentRun(e);let c=await s.subscribeSessionV1({linkSessionId:i,onEvent:this.handleSessionTransportEvent.bind(this)});if(!this.isCurrentRun(e))throw await c.close(),new YV;this.subscription=c,VV({flowId:this.flowId,linkSessionId:i,stage:`session_subscription_ready`});let l=await XV(In(a));this.assertCurrentRun(e);let u={qrData:a,qrCodeDataURL:l};return this.emit({phase:Zi.STEP_01_QR_PREPARE_STARTED,status:`succeeded`,message:`Device-link QR ready`,data:{role:`display`},interaction:{kind:`qr_display`,overlay:`show`}}),await this.options.options?.afterCall?.(!0,u),u}catch(e){try{await this.cleanupLocalResources()}catch{}if(e instanceof YV)throw e;this.session=null,this.authenticatedTransport=null,this.handledStates.clear();let t=KV(e,`generation`);throw this.error=t,this.emitFailure(t,`generation`),BV(this.options.options?.onError,t),await this.options.options?.afterCall?.(!1,void 0,t),t}finally{this.generationInProgress=!1}}getState(){return{phase:this.session?GV(this.session.state):Zi.STEP_01_QR_PREPARE_STARTED,session:this.session,...this.error?{error:this.error}:{},cancelled:this.cancelled}}async cancel(){if(this.hasCommittedDeliveryState())throw Error(`Device-link authority delivery is committed and must be resumed`);if(this.cancelled){await this.cleanupLocalResources();return}this.cancelled=!0,this.runEpoch+=1;let e=this.session,t=this.keyMaterialHandle,n=this.authenticatedTransport;try{if(e&&t&&n){let t=Date.now();switch(e.state.state){case`displaying_qr`:await n.cancelSessionV1({request:Cr({linkSessionId:e.linkSessionId,requestedAtMs:t})}),this.session={...e,state:{state:`cancelled`,cancelledAtMs:t}};break;case`claimed`:case`awaiting_target_factor`:case`awaiting_source_contribution`:case`provisioning`:await this.cancelClaimedSessionV1(n,e.linkSessionId,t),this.session={...e,state:{state:`cancelled`,cancelledAtMs:t}};break;case`authority_pending_local_install`:break;case`active`:case`expired`:case`cancelled`:case`failed_before_commit`:break;default:sr(e.state)}}}finally{await this.cleanupLocalResources()}this.emit({phase:Zi.CANCELLED,status:`cancelled`,message:`Device-link flow cancelled`,interaction:{kind:`qr_display`,overlay:`hide`}})}async resolveLinkIdentityV1(e){let t=this.targetCredentialRegistrationResult;if(t&&t.linkSessionId===e)return{enrollmentId:t.enrollmentId,deviceId:t.deviceId};let n=await this.requireAuthenticatedTransport().getTargetPreparationV1({linkSessionId:e,deliveryRecipientPublicKey65B64u:this.requireDeliveryRecipientPublicKey65B64u()});return{enrollmentId:n.enrollmentId,deviceId:n.deviceId}}async cancelClaimedSessionV1(e,t,n){let r=await this.resolveLinkIdentityV1(t);await e.cancelSessionV1({request:ir({linkSessionId:t,enrollmentId:r.enrollmentId,deviceId:r.deviceId,reason:`user_cancelled`,requestedAtMs:n})})}async handleSessionEvent(e){if(this.cancelled||this.deliveryRecoveryReason!==null||!this.session||e.linkSessionId!==this.session.linkSessionId)return;VV({flowId:this.flowId,linkSessionId:e.linkSessionId,stage:`session_event_received`,details:{state:e.state.state,emittedAtMs:e.emittedAtMs,runEpoch:this.runEpoch}});let t=this.runEpoch;if(this.handledStates.has(e.state.state)){VV({flowId:this.flowId,linkSessionId:e.linkSessionId,stage:`session_event_already_handled`,details:{state:e.state.state}});return}switch(this.session={...this.session,state:e.state},this.handledStates.add(e.state.state),e.state.state){case`displaying_qr`:return;case`claimed`:this.emit({phase:Zi.STEP_02_QR_SCAN_STARTED,status:`running`,message:`Device link claimed by owner`,data:{role:`display`},interaction:{kind:`qr_display`,overlay:`show`}});return;case`awaiting_target_factor`:await this.prepareTargetCredentialActivation(e,t);return;case`awaiting_source_contribution`:return;case`provisioning`:case`authority_pending_local_install`:{let n=await this.activateAuthorityForStateV1(e.state,t);if(n.kind===`pending_local_install`)return;if(n.kind===`integrity_error`)throw new X(`Linked-device authority installation failed: ${n.reason}`,Z.REGISTRATION_FAILED,`registration`);if(n.kind===`failed_before_commit`)throw new X(`Linked-device authority activation cannot continue`,Z.REGISTRATION_FAILED,`registration`);await this.finishActiveAuthorityV1(e.state,n.session,n.operationCredential,t);return}case`active`:await this.replayCommittedAuthorityV1(e.state,t);return;case`expired`:{let e=new X(`Device-link session expired`,Z.SESSION_EXPIRED,`registration`);this.error=e,this.emitFailure(e,`registration`),BV(this.options.options?.onError,e),this.runEpoch+=1,await this.cleanupLocalResources();return}case`cancelled`:this.cancelled=!0,this.emit({phase:Zi.CANCELLED,status:`cancelled`,message:`The other device cancelled this linking request.`,interaction:{kind:`qr_display`,overlay:`show`}}),this.runEpoch+=1,await this.cleanupLocalResources();return;case`failed_before_commit`:this.cancelled=!0,this.runEpoch+=1,await this.cleanupLocalResources();return;default:return sr(e.state)}}async prepareTargetCredentialActivation(e,t){if(e.state.state!==`awaiting_target_factor`)throw Error(`target passkey activation requires an awaiting session`);let n=e.state;if(!this.keyMaterialHandle||!this.session)throw Error(`device-link key material is unavailable`);let r=this.requireAuthenticatedTransport();this.assertCurrentRun(t);let i=await r.getTargetPreparationV1({linkSessionId:e.linkSessionId,deliveryRecipientPublicKey65B64u:this.requireDeliveryRecipientPublicKey65B64u()});this.assertCurrentRun(t),this.assertTargetPreparationMatchesSession({preparation:i,state:n,linkSessionId:e.linkSessionId});let a=i.deviceId;if(this.ordinarySignerMaterialRecipientPreparation=await this.ports.keyMaterial.createOrdinarySignerMaterialRecipientRequestsV1({keyMaterial:this.keyMaterialHandle,requirements:i.ordinarySignerMaterialRecipientRequirements}),this.assertCurrentRun(t),this.requireSessionTargetFactorV1().kind===`email_otp`){await this.prepareTargetEmailOtpActivation({event:e,state:n,runEpoch:t,deviceId:a,preparation:i});return}if(!QV(i))throw Error(`Passkey session returned a non-Passkey target preparation`);let o=this.options.options?.onTargetFactorRequired;if(!o)throw new X(`Confirm passkey creation on Device 2 to continue linking`,Z.UNSUPPORTED,`registration`);o({kind:`linked_device_target_passkey_activation_v1`,createPasskey:this.activateTargetCredential.bind(this,{event:e,state:n,runEpoch:t,deviceId:a,preparation:i})})}async prepareTargetEmailOtpActivation(e){if(!$V(e.preparation))throw Error(`Email OTP session returned a non-Email OTP target preparation`);if(!this.keyMaterialHandle||!this.session||!this.deliveryRecipientPublicKey65B64u)throw Error(`Email OTP target key material is unavailable`);if(!this.options.options?.onTargetFactorRequired)throw new X(`Enter the Email OTP on Device 2 to continue linking`,Z.UNSUPPORTED,`registration`);let t=this.requireAuthenticatedTransport(),n=e.preparation.ed25519ExportRoot,r=n===null?{kind:`not_required`}:{kind:`required`,recipient:await KB({ed25519ExportRoot:this.ports.ed25519ExportRoot,transport:t,identity:{linkSessionId:e.event.linkSessionId,walletId:e.preparation.walletId,walletKeyId:n.walletKeyId,enrollmentId:e.preparation.enrollmentId,deviceId:e.deviceId,applicationBindingDigestB64u:n.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,targetFactor:e.preparation.targetFactor,revocationEpoch:n.revocationEpoch},registeredAtMs:Date.now()})};this.assertCurrentRun(e.runEpoch);let i={event:e.event,state:e.state,runEpoch:e.runEpoch,deviceId:e.deviceId,preparation:e.preparation,ordinarySignerMaterialRecipientRequests:this.requireOrdinarySignerMaterialRecipientPreparationV1().recipientRequests,exportRoot:r};this.emailOtpTargetActivationState={kind:`available`,context:i},await this.startTargetEmailOtpChallengeV1(i)}notifyEmailOtpActivationV1(e){let t=this.options.options?.onTargetFactorRequired;t&&t({kind:`linked_device_target_email_otp_activation_v1`,state:e,sendCode:this.sendTargetEmailOtpCodeV1.bind(this),submitCode:this.submitTargetEmailOtpCodeV1.bind(this),resendCode:this.resendTargetEmailOtpCodeV1.bind(this)})}sendTargetEmailOtpCodeV1(){let e=this.emailOtpTargetActivationState;switch(e.kind){case`available`:{let t=this.startTargetEmailOtpChallengeV1(e.context);return this.emailOtpTargetActivationState={kind:`starting`,context:e.context,promise:t},t}case`starting`:return e.promise;case`resending`:return e.promise;case`awaiting_code`:case`submitting`:case`completed`:return Promise.resolve();case`failed`:return Promise.reject(Error(e.message));case`idle`:return Promise.reject(Error(`Email OTP activation is unavailable`));default:return nH(e)}}async startTargetEmailOtpChallengeV1(e){try{this.assertCurrentRun(e.runEpoch);let t=this.deliveryRecipientPublicKey65B64u;if(!t)throw Error(`Email OTP factor-release recipient is unavailable`);let n=await this.requireAuthenticatedTransport().startTargetEmailOtpChallengeV1({request:{kind:`linked_device_email_otp_challenge_start_request_v1`,linkSessionId:e.event.linkSessionId,workerEphemeralPublicKey65B64u:t}});this.assertCurrentRun(e.runEpoch),this.awaitTargetEmailOtpCodeV1(e,n)}catch(t){throw this.isCurrentRun(e.runEpoch)&&(this.emailOtpTargetActivationState={kind:`available`,context:e},this.notifyEmailOtpActivationV1({kind:`unavailable`,message:L(t)})),t}}awaitTargetEmailOtpCodeV1(e,t){this.emailOtpTargetActivationState={kind:`awaiting_code`,context:{...eH(e),challenge:t}},this.notifyEmailOtpActivationV1({kind:`code_input`,maskedEmailHint:t.maskedEmailHint,expiresAtMs:t.expiresAtMs,resendAvailableAtMs:t.resendAvailableAtMs})}resendTargetEmailOtpCodeV1(){let e=this.emailOtpTargetActivationState;if(e.kind===`resending`)return e.promise;if(e.kind!==`awaiting_code`)return Promise.reject(Error(`Email OTP challenge is not ready to resend`));try{this.assertCurrentRun(e.context.runEpoch)}catch(e){return Promise.reject(e)}let t=this.runTargetEmailOtpResendV1(e.context);return this.emailOtpTargetActivationState={kind:`resending`,context:e.context,promise:t},this.notifyEmailOtpActivationV1({kind:`resending`,maskedEmailHint:e.context.challenge.maskedEmailHint}),t}async runTargetEmailOtpResendV1(e){try{let t=await this.requireAuthenticatedTransport().resendTargetEmailOtpChallengeV1({request:{kind:`linked_device_email_otp_challenge_resend_request_v1`,linkSessionId:e.event.linkSessionId,challengeId:e.challenge.challengeId}});this.assertCurrentRun(e.runEpoch),this.awaitTargetEmailOtpCodeV1(e,t)}catch(t){if(this.isCurrentRun(e.runEpoch)){let n=L(t)||`Email OTP resend is unavailable`;this.emailOtpTargetActivationState={kind:`available`,context:eH(e)},this.notifyEmailOtpActivationV1({kind:`unavailable`,message:n})}throw t}}submitTargetEmailOtpCodeV1(e){let t=this.emailOtpTargetActivationState;if(t.kind!==`awaiting_code`)return Promise.reject(Error(`Email OTP challenge is not ready for verification`));this.assertCurrentRun(t.context.runEpoch);let n=this.completeTargetEmailOtpActivationV1(t.context,e);return this.emailOtpTargetActivationState={kind:`submitting`,context:t.context,promise:n},this.notifyEmailOtpActivationV1({kind:`submitting`,maskedEmailHint:t.context.challenge.maskedEmailHint,expiresAtMs:t.context.challenge.expiresAtMs,resendAvailableAtMs:t.context.challenge.resendAvailableAtMs}),n}async completeTargetEmailOtpActivationV1(e,t){let n;try{n=await this.requireAuthenticatedTransport().verifyTargetEmailOtpChallengeV1({request:{kind:`linked_device_email_otp_challenge_verify_request_v1`,linkSessionId:e.event.linkSessionId,challengeId:e.challenge.challengeId,otpCode:t}})}catch(t){throw this.isCurrentRun(e.runEpoch)&&(this.emailOtpTargetActivationState={kind:`awaiting_code`,context:e},Date.now()>=e.challenge.expiresAtMs?this.notifyEmailOtpActivationV1({kind:`expired`,maskedEmailHint:e.challenge.maskedEmailHint,message:L(t)}):this.notifyEmailOtpActivationV1({kind:`incorrect`,maskedEmailHint:e.challenge.maskedEmailHint,expiresAtMs:e.challenge.expiresAtMs,resendAvailableAtMs:e.challenge.resendAvailableAtMs,message:L(t)})),t}this.assertCurrentRun(e.runEpoch);let r=lH(e.preparation),i=e.exportRoot.kind===`required`?e.exportRoot.recipient:null,a=null,o=null,s=null,c=null,l=null,u=null,d=r.enrollment.kind===`existing_enrollment`;try{let t=await rr(r);if(n.verificationGrant.targetEmail!==r.targetEmail)throw Error(`linked-device Email OTP verification target email changed`);if(d){let i=n.verificationGrant;if(i.enrollment.kind!==`existing_enrollment`)throw Error(`linked-device Email OTP verification enrollment changed`);let o=i.baseWalletAuthMethodId;if(!o)throw Error(`linked-device Email OTP base auth method is unavailable`);let u=n.factorRelease;if(!u)throw Error(`linked-device Email OTP factor release is unavailable`);let d=await this.ports.keyMaterial.openEmailOtpFactorReleaseV1({keyMaterial:this.requireKeyMaterialHandleV1(),walletId:r.walletId,linkSessionId:r.linkSessionId,enrollmentId:r.enrollmentId,deviceId:r.deviceId,walletAuthMethodId:r.walletAuthMethodId,baseWalletAuthMethodId:o,targetPreparationDigestB64u:t,expectedChallengeId:e.challenge.challengeId,verificationGrant:i,factorRelease:u});a=d.factorSecret,s=d.verificationGrant,c=u.enrollmentId,l=u.enrollmentSealKeyVersion}else{let e=n.verificationGrant;if(e.enrollment.kind!==`new_enrollment`)throw Error(`linked-device Email OTP verification enrollment changed`);if(n.factorRelease!==null)throw Error(`new linked-device Email OTP enrollment returned a factor release`);let t=this.getAuthenticationContext?.();if(!t)throw Error(`linked-device authentication context is unavailable`);let i=dH();a=i.buffer;let o=await fH({context:t,walletId:r.walletId,targetEmail:r.targetEmail,factorSecret:i});c=o.enrollmentId,l=o.enrollment.enrollmentSealKeyVersion,u=o.enrollment,s=e}if(!a||!s||!c||!l)throw Error(`linked-device Email OTP factor material is unavailable`);if(this.assertCurrentRun(e.runEpoch),e.exportRoot.kind===`required`){if(!i)throw Error(`linked-device Ed25519 export-root recipient is unavailable`);let t=r.ed25519ExportRoot;if(!t)throw Error(`linked-device Ed25519 export-root preparation is unavailable`);let n=uH(),o=mn({enrollmentId:c,enrollmentSealKeyVersion:l});this.resealedExportRoot=await this.acceptTargetExportRootV1({preparation:r,exportRoot:t,recipient:i,envelopeId:n,factor:o,replacementFactorSecret:new Uint8Array(a),runEpoch:e.runEpoch}),i=null}let f=Mn(d?{linkSessionId:r.linkSessionId,walletId:r.walletId,enrollmentId:r.enrollmentId,deviceId:r.deviceId,walletAuthMethodId:r.walletAuthMethodId,targetFactor:{kind:`email_otp`},targetEmail:r.targetEmail,emailOtpVerificationGrant:s,targetPreparationDigestB64u:t,ordinarySignerMaterialRecipientRequests:e.ordinarySignerMaterialRecipientRequests,registeredAtMs:Date.now()}:{linkSessionId:r.linkSessionId,walletId:r.walletId,enrollmentId:r.enrollmentId,deviceId:r.deviceId,walletAuthMethodId:r.walletAuthMethodId,targetFactor:{kind:`email_otp`},targetEmail:r.targetEmail,emailOtpVerificationGrant:s,emailOtpEnrollment:pH(u),targetPreparationDigestB64u:t,ordinarySignerMaterialRecipientRequests:e.ordinarySignerMaterialRecipientRequests,registeredAtMs:Date.now()}),p=await this.requireAuthenticatedTransport().registerTargetCredentialV1({registration:f});if(this.assertCurrentRun(e.runEpoch),this.targetCredentialRegistrationResult=p,o=new Uint8Array(a).slice(),await this.ports.keyMaterial.prepareOrdinarySignerMaterialV1({keyMaterial:this.requireKeyMaterialHandleV1(),targetFactor:p.targetFactor,preparations:p.ordinarySignerMaterialPreparations,recipientRequests:p.ordinarySignerMaterialRecipientRequests,recipientInputs:this.requireOrdinarySignerMaterialRecipientPreparationV1().recipientInputs,factorSecret:a}),a=null,this.assertCurrentRun(e.runEpoch),VV({flowId:this.flowId,linkSessionId:e.preparation.linkSessionId,stage:`ordinary_signer_material_prepared`}),!o)throw Error(`linked-device Email OTP factor runtime is unavailable`);this.emailOtpTargetActivationState={kind:`completed`,runEpoch:e.runEpoch,enrollment:d?{kind:`existing_enrollment`}:{kind:`new_enrollment`},factorSecret:o,providerUserId:s.providerUserId},o=null,this.notifyEmailOtpActivationV1({kind:`completed`,maskedEmailHint:e.challenge.maskedEmailHint})}catch(t){if(a&&a.byteLength>0&&new Uint8Array(a).fill(0),o?.fill(0),i&&await JB(this.ports.ed25519ExportRoot,i),this.isCurrentRun(e.runEpoch)){let n=L(t)||`Email OTP activation is unavailable`;this.emailOtpTargetActivationState={kind:`failed`,runEpoch:e.runEpoch,message:n},this.notifyEmailOtpActivationV1({kind:`unavailable`,message:n}),await this.cancelFailedPrecommitSession(e.event).catch(()=>void 0)}throw t}}activateTargetCredential(e){if(!this.isCurrentRun(e.runEpoch))return Promise.reject(new YV);switch(this.targetCredentialActivationState.kind){case`idle`:break;case`in_progress`:return this.targetCredentialActivationState.runEpoch===e.runEpoch?this.targetCredentialActivationState.promise:Promise.reject(new YV);case`factor_ready`:return this.targetCredentialActivationState.runEpoch===e.runEpoch?Promise.reject(Error(`Device-link target passkey activation has already completed`)):Promise.reject(new YV);default:return rH(this.targetCredentialActivationState)}let t=this.runTargetCredentialActivation(e);return this.targetCredentialActivationState={kind:`in_progress`,runEpoch:e.runEpoch,promise:t},t}async runTargetCredentialActivation(e){try{let t=await this.createTargetCredential(e),n=this.targetCredentialActivationState;if(!this.isCurrentRun(e.runEpoch)||n.kind!==`in_progress`||n.runEpoch!==e.runEpoch)throw oH(t),new YV;this.targetCredentialActivationState={kind:`factor_ready`,runEpoch:e.runEpoch,factorSecret:t}}catch(t){throw this.isCurrentRun(e.runEpoch)&&await this.handleSessionTransportFailure(e.event,t),t}finally{let t=this.targetCredentialActivationState;t.kind===`in_progress`&&t.runEpoch===e.runEpoch&&(this.targetCredentialActivationState={kind:`idle`})}}async waitForTargetCredentialActivation(){switch(this.requireSessionTargetFactorV1().kind){case`passkey_prf`:{let e=this.targetCredentialActivationState;if(e.kind===`in_progress`&&await e.promise,this.targetCredentialActivationState.kind!==`factor_ready`)throw Error(`linked-device target Passkey activation is incomplete`);return}case`email_otp`:{let e=this.emailOtpTargetActivationState;if(e.kind===`submitting`&&await e.promise,this.emailOtpTargetActivationState.kind!==`completed`)throw Error(`linked-device target Email OTP activation is incomplete`);return}default:throw Error(`linked-device target factor is unsupported`)}}clearTargetCredentialActivationState(){let e=this.targetCredentialActivationState;e.kind===`factor_ready`&&oH(e.factorSecret),this.targetCredentialActivationState={kind:`idle`}}async createTargetCredential(e){let{runEpoch:t,deviceId:n,preparation:r}=e;if(!this.keyMaterialHandle||!this.session)throw Error(`device-link key material is unavailable`);let i=this.requireAuthenticatedTransport();VV({flowId:this.flowId,linkSessionId:r.linkSessionId,stage:`target_passkey_prompt_started`});let a=r.ed25519ExportRoot,o=a===null?Promise.resolve(null):KB({ed25519ExportRoot:this.ports.ed25519ExportRoot,transport:i,identity:{linkSessionId:r.linkSessionId,walletId:r.walletId,walletKeyId:a.walletKeyId,enrollmentId:r.enrollmentId,deviceId:n,applicationBindingDigestB64u:a.applicationBindingDigestB64u,registeredPublicKeyB64u:a.registeredPublicKeyB64u,targetFactor:r.targetFactor,revocationEpoch:a.revocationEpoch},registeredAtMs:Date.now()});o.catch(()=>void 0);let s=null,c=null;try{if(s=await this.ports.targetCredential.createTargetCredentialV1({preparation:r,keyMaterial:this.keyMaterialHandle}),s.walletAuthMethodId!==r.walletAuthMethodId)throw Error(`linked-device target credential returned a different auth method`);if(VV({flowId:this.flowId,linkSessionId:r.linkSessionId,stage:`target_passkey_created`}),this.emit({phase:Zi.STEP_02_QR_SCAN_STARTED,status:`running`,message:`Finishing linked-device setup`,data:{role:`display`},interaction:{kind:`qr_display`,overlay:`show`}}),c=await o,c&&VV({flowId:this.flowId,linkSessionId:r.linkSessionId,stage:`export_root_recipient_published`}),this.assertCurrentRun(t),a!==null){if(!c)throw Error(`linked-device Ed25519 export-root recipient is unavailable`);let e=uH(),n=dn({rpId:cH(r),credentialIdB64u:s.webauthnRegistration.credentialIdB64u}),i=await this.acceptTargetExportRootV1({preparation:r,exportRoot:a,recipient:c,envelopeId:e,factor:n,replacementFactorSecret:s.factorSecret,runEpoch:t});VV({flowId:this.flowId,linkSessionId:r.linkSessionId,stage:`export_root_accepted`}),this.resealedExportRoot=i,c=null}this.assertCurrentRun(t);let e=await rr(r),n=Mn({linkSessionId:r.linkSessionId,walletId:r.walletId,enrollmentId:r.enrollmentId,deviceId:r.deviceId,walletAuthMethodId:s.walletAuthMethodId,targetFactor:{kind:`passkey_prf`},targetPreparationDigestB64u:e,webauthnRegistration:s.webauthnRegistration,ordinarySignerMaterialRecipientRequests:this.requireOrdinarySignerMaterialRecipientPreparationV1().recipientRequests,registeredAtMs:Date.now()}),l=await i.registerTargetCredentialV1({registration:n});return this.assertCurrentRun(t),this.targetCredentialRegistrationResult=l,await this.ports.keyMaterial.prepareOrdinarySignerMaterialV1({keyMaterial:this.requireKeyMaterialHandleV1(),targetFactor:l.targetFactor,preparations:l.ordinarySignerMaterialPreparations,recipientRequests:l.ordinarySignerMaterialRecipientRequests,recipientInputs:this.requireOrdinarySignerMaterialRecipientPreparationV1().recipientInputs,factorSecret:s.factorSecret.slice().buffer}),this.assertCurrentRun(t),VV({flowId:this.flowId,linkSessionId:r.linkSessionId,stage:`ordinary_signer_material_prepared`}),s.factorSecret}catch(e){if(s&&oH(s.factorSecret),!c)try{c=await o}catch{}throw c&&await JB(this.ports.ed25519ExportRoot,c),e}}async acceptTargetExportRootV1(e){let{preparation:t,exportRoot:n}=e,r=_n({linkSessionId:t.linkSessionId,walletKeyId:n.walletKeyId,targetFactor:t.targetFactor,applicationBindingDigestB64u:n.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,enrollmentId:t.enrollmentId,deviceId:t.deviceId,revocationEpoch:n.revocationEpoch});return await qB({ed25519ExportRoot:this.ports.ed25519ExportRoot,transport:this.requireAuthenticatedTransport(),recipient:e.recipient,replacementEnvelope:ZB({walletId:t.walletId,ownership:pn(t.walletAuthMethodId),envelopeId:e.envelopeId,factor:e.factor,binding:r,createdAtMs:Date.now()}),replacementFactorSecret:e.replacementFactorSecret,expiresAtMs:Math.min(t.expiresAtMs,this.requireSessionV1().qrData.expiresAtMs),assertCurrentRun:()=>this.assertCurrentRun(e.runEpoch),waitForPollV1:WV})}assertTargetPreparationMatchesSession(e){let t=this.requireSessionTargetFactorV1(),n=this.requireSessionV1().qrData;if(e.preparation.linkSessionId!==e.linkSessionId||String(e.preparation.deviceId)!==String(e.state.deviceId)||e.preparation.targetFactor.kind!==t.kind||e.preparation.deliveryRecipientPublicKey65B64u!==this.requireDeliveryRecipientPublicKey65B64u()||e.preparation.expiresAtMs<=Date.now())throw Error(`linked-device target preparation does not match the claimed session`);if(t.kind===`email_otp`&&n.targetFactor.kind===`email_otp`&&e.preparation.targetFactor.kind===`email_otp`&&e.preparation.targetEmail!==n.targetEmail)throw Error(`linked-device target preparation email does not match the QR session`)}async activateAuthorityForStateV1(e,t){this.assertCurrentRun(t),await this.waitForTargetCredentialActivation(),this.assertCurrentRun(t);let n=this.targetCredentialRegistrationResult;if(!n)throw Error(`linked-device target credential registration is unavailable`);let r=this.requireKeyMaterialHandleV1(),i=this.requireAuthenticatedTransport(),a=await this.ports.readExpectedLockGenerationV1(n.walletId);this.assertCurrentRun(t);let o=this.committedAuthorityPackages||await i.receiveCommittedAuthorityPackagesV1({linkSessionId:this.requireSessionV1().linkSessionId});this.committedAuthorityPackages=o,await this.ports.authorityInstallation.persistCommittedDeliveryResumeV1({linkSessionId:this.requireSessionV1().linkSessionId,committed:o,targetFactor:n.targetFactor,committedAtMs:Date.now()}),this.assertCurrentRun(t);let s=this.requireSessionV1().qrData.expiresAtMs,c=0;for(;Date.now()<s;){let s=await DV({transport:i,committed:o,installation:this.ports.authorityInstallation,sessionState:e,linkSessionId:this.requireSessionV1().linkSessionId,targetFactor:n.targetFactor,keyMaterialPort:this.ports.keyMaterial,keyMaterial:r,deliveryRecipientPublicKey65B64u:this.requireDeliveryRecipientPublicKey65B64u(),resealedExportRoot:this.resealedExportRoot,expectedLockGeneration:a,nowMs:()=>Date.now()});if(s.kind!==`pending_local_install`)return s;await WV(c),this.assertCurrentRun(t),c+=1}throw new X(`Linked-device authority activation did not complete before the link session expired`,Z.REGISTRATION_FAILED,`registration`)}async finishActiveAuthorityV1(e,t,n,r){this.assertCurrentRun(r);let i=this.requireSessionV1(),a=this.targetCredentialRegistrationResult;if(!a||a.walletId!==t.walletId)throw Error(`linked-device activation identity is unavailable`);this.handledStates.add(`provisioning`),this.handledStates.add(`authority_pending_local_install`),this.handledStates.add(`active`);let o=this.getAuthenticationContext?.();if(!o)throw Error(`linked-device authentication context is unavailable`);let s=iH({targetFactor:a.targetFactor,walletAuthMethodId:a.walletAuthMethodId,targetCredentialActivationState:this.targetCredentialActivationState,emailOtpTargetActivationState:this.emailOtpTargetActivationState,walletId:t.walletId,runEpoch:r});await Wx({context:o,factor:s.factor,walletSession:t,operationCredential:n,factorSecret32:s.factorSecret32});let c=this.committedAuthorityPackages;if(!c)throw Error(`linked-device committed authority packages are unavailable for acknowledgement`);let l=await this.ports.authorityInstallation.readLocalAuthorityInstallationReceiptV1({authorityId:t.authorityId});if(!l)throw Error(`linked-device installation receipt is unavailable for acknowledgement`);let u={kind:`local_authority_activation_final_ack_v1`,linkSessionId:i.qrData.linkSessionId,authorityId:t.authorityId,packageSetDigestB64u:c.packageSetDigestB64u,authorizationId:t.authorizationId,walletSessionId:n.walletSessionId,credentialDigestB64u:await br(n),installationReceiptDigestB64u:await _r(l),acknowledgedAtMs:Date.now()};await this.ports.authorityInstallation.persistPendingActivationAcknowledgementV1({acknowledgement:u});let d={walletSession:t,deviceId:e.deviceId,runEpoch:r};this.pendingActivationCompletion=d,await this.sendActivationAcknowledgementV1(u),await this.completeAcknowledgedActivationV1(d)}async completeAcknowledgedActivationV1(e){this.assertCurrentRun(e.runEpoch);let{walletSession:t}=e,n=this.requireSessionV1(),r=this.targetCredentialRegistrationResult,i=this.getAuthenticationContext?.();if(!r||!i)throw Error(`linked-device activation completion is unavailable`);this.session={linkSessionId:n.linkSessionId,qrData:n.qrData,state:{state:`active`,deviceId:e.deviceId,authorityId:t.authorityId,activatedAtMs:t.issuedAtMs}},i.signingEngine.setWalletAuthenticated(LV(t,r)),await this.cleanupCompletedLocalResources(),VV({flowId:this.flowId,linkSessionId:n.qrData.linkSessionId,stage:`post_link_runtime_ready`}),this.emit({phase:Zi.STEP_02_QR_SCAN_STARTED,status:`succeeded`,message:`Device link active`,walletId:String(t.walletId),data:{role:`display`,enrollmentId:String(r.enrollmentId)},interaction:{kind:`qr_display`,overlay:`hide`}})}requireAuthenticatedTransport(){if(!this.authenticatedTransport)throw new X(`Authenticated link-session transport is unavailable`,Z.UNSUPPORTED,`registration`);return this.authenticatedTransport}requireSessionTargetFactorV1(){if(!this.session)throw Error(`device-link session is unavailable`);return this.session.qrData.targetFactor}requireSessionV1(){if(!this.session)throw Error(`device-link session is unavailable`);return this.session}requireKeyMaterialHandleV1(){if(!this.keyMaterialHandle)throw Error(`device-link key material is unavailable`);return this.keyMaterialHandle}requireDeliveryRecipientPublicKey65B64u(){if(!this.deliveryRecipientPublicKey65B64u)throw Error(`device-link delivery recipient is unavailable`);return this.deliveryRecipientPublicKey65B64u}requireOrdinarySignerMaterialRecipientPreparationV1(){let e=this.ordinarySignerMaterialRecipientPreparation;if(!e)throw Error(`ordinary signer material recipient preparation is unavailable`);return e}startRun(){return this.clearRunActivationStateV1(),this.committedAuthorityPackages=null,this.deliveryRecoveryReason=null,this.runEpoch+=1,this.generationInProgress=!0,this.cancelled=!1,this.error=void 0,this.handledStates.clear(),this.runEpoch}isCurrentRun(e){return!this.cancelled&&this.runEpoch===e}assertCurrentRun(e){if(!this.isCurrentRun(e))throw new YV}handleSessionTransportEvent(e){this.sessionEventQueue=this.sessionEventQueue.then(this.handleSessionEvent.bind(this,e)).catch(this.handleSessionTransportFailure.bind(this,e))}async handleSessionTransportFailure(e,t){if(t instanceof YV)return;if(this.hasCommittedDeliveryState()){await this.handleCommittedDeliveryFailureV1(e,t);return}HV({flowId:this.flowId,linkSessionId:e.linkSessionId,state:e.state.state,error:t}),this.handledStates.delete(e.state.state);let n=KV(t,`registration`);this.error=n,this.emitFailure(n,`registration`),BV(this.options.options?.onError,n),await this.cancelFailedPrecommitSession(e).catch(()=>void 0),this.runEpoch+=1;try{await this.cleanupLocalResources()}catch{}}async handleCommittedDeliveryFailureV1(e,t){let n=qV(t);if(n){await this.requireExactMethodUnlockForCommittedDeliveryV1(e,n);return}VV({flowId:this.flowId,linkSessionId:e.linkSessionId,stage:`committed_delivery_retry_started`,details:{state:e.state.state,error:L(t)}}),this.handledStates.delete(e.state.state);try{await this.retryCommittedDeliveryV1(e)}catch(t){let n=qV(t);if(n){await this.requireExactMethodUnlockForCommittedDeliveryV1(e,n);return}HV({flowId:this.flowId,linkSessionId:e.linkSessionId,state:e.state.state,error:t})}}async requireExactMethodUnlockForCommittedDeliveryV1(e,t){this.deliveryRecoveryReason=t,this.handledStates.clear(),this.runEpoch+=1;let n=new X(JV(t),Z.DELIVERY_RECOVERY_REQUIRED,`registration`);this.error=n;try{await this.cleanupCompletedLocalResources()}catch(t){HV({flowId:this.flowId,linkSessionId:e.linkSessionId,state:e.state.state,error:t})}this.clearRunActivationStateV1(),this.committedAuthorityPackages=null,this.keyMaterialHandle=null,this.deliveryRecipientPublicKey65B64u=null,this.authenticatedTransport=null,this.subscription=null,this.emitFailure(n,`registration`),BV(this.options.options?.onError,n)}async retryCommittedDeliveryV1(e){if(!await this.replayPendingActivationAcknowledgementV1())switch(e.state.state){case`provisioning`:case`authority_pending_local_install`:case`active`:await this.replayCommittedAuthorityV1(e.state,this.runEpoch);return;default:throw Error(`committed link delivery cannot resume from ${e.state.state}`)}}async replayCommittedAuthorityV1(e,t){let n=await this.activateAuthorityForStateV1(e,t);if(n.kind!==`pending_local_install`){if(n.kind===`integrity_error`)throw new X(`Linked-device authority replay failed: ${n.reason}`,Z.REGISTRATION_FAILED,`registration`);if(n.kind===`failed_before_commit`)throw new X(`Linked-device authority replay cannot continue`,Z.REGISTRATION_FAILED,`registration`);await this.finishActiveAuthorityV1(e,n.session,n.operationCredential,t)}}async replayPendingActivationAcknowledgementV1(){let e=this.committedAuthorityPackages;if(!e)return!1;let t=await this.ports.authorityInstallation.readPendingActivationAcknowledgementV1({authorityId:e.authority.authorityId});if(!t)return!1;let n=this.requireSessionV1();if(t.linkSessionId!==n.qrData.linkSessionId||t.authorityId!==e.authority.authorityId||t.packageSetDigestB64u!==e.packageSetDigestB64u)throw Error(`pending linked-device acknowledgement identity is inconsistent`);let r=this.pendingActivationCompletion;if(!r||r.walletSession.authorizationId!==t.authorizationId)throw Error(`pending linked-device activation completion is unavailable`);return await this.sendActivationAcknowledgementV1(t),await this.completeAcknowledgedActivationV1(r),!0}async sendActivationAcknowledgementV1(e){await this.closeSessionSubscriptionV1();let t=this.requireAuthenticatedTransport();for(let n=1;n<=3;n+=1)try{await t.acknowledgeLocalAuthorityActivationV1({acknowledgement:e});break}catch(e){if(qV(e)||n===3)throw e}await this.ports.authorityInstallation.clearPendingActivationAcknowledgementV1({authorityId:e.authorityId}),await this.ports.authorityInstallation.clearCommittedDeliveryResumeV1({authorityId:e.authorityId})}async cancelFailedPrecommitSession(e){let t=this.authenticatedTransport;if(t)switch(e.state.state){case`claimed`:case`awaiting_target_factor`:case`awaiting_source_contribution`:case`provisioning`:{let n=Date.now();await this.cancelClaimedSessionV1(t,e.linkSessionId,n),this.session?.linkSessionId===e.linkSessionId&&(this.session={...this.session,state:{state:`cancelled`,cancelledAtMs:n}});return}case`displaying_qr`:case`authority_pending_local_install`:case`active`:case`expired`:case`cancelled`:case`failed_before_commit`:return;default:sr(e.state)}}async cleanupLocalResources(e=!1){if(!e&&this.hasCommittedDeliveryState())return;let t=e&&this.hasCommittedDeliveryState();t||this.clearRunActivationStateV1();let n,r=this.subscription;if(r)try{await r.close(),this.subscription===r&&(this.subscription=null)}catch(e){n=e}if(!n)try{await this.discardKeyMaterial()}catch(e){n=e}if(n)throw n;t&&(this.clearRunActivationStateV1(),this.committedAuthorityPackages=null)}clearRunActivationStateV1(){this.pendingActivationCompletion=null,this.clearTargetCredentialActivationState(),this.clearEmailOtpTargetActivationState(),this.resealedExportRoot=null,this.targetCredentialRegistrationResult=null,this.ordinarySignerMaterialRecipientPreparation=null}async closeSessionSubscriptionV1(){let e=this.subscription;e&&(await e.close(),this.subscription===e&&(this.subscription=null))}async cleanupCompletedLocalResources(){await this.cleanupLocalResources(!0)}clearEmailOtpTargetActivationState(){let e=this.emailOtpTargetActivationState;e.kind===`completed`&&tH(e).factorSecret.fill(0),this.emailOtpTargetActivationState={kind:`idle`}}hasCommittedDeliveryState(){return this.committedAuthorityPackages!==null||this.keyMaterialHandle!==null&&(this.session?.state.state===`authority_pending_local_install`||this.session?.state.state===`active`)}async discardKeyMaterial(){let e=this.keyMaterialHandle;if(!e)return;if(this.discardInProgress)return await this.discardInProgress;let t=this.ports.keyMaterial.discardKeyMaterialV1({handle:e});this.discardInProgress=t;try{await t,this.keyMaterialHandle===e&&(this.keyMaterialHandle=null,this.deliveryRecipientPublicKey65B64u=null,this.authenticatedTransport=null)}finally{this.discardInProgress===t&&(this.discardInProgress=null)}}emitFailure(e,t){this.emit({phase:t===`generation`?Zi.STEP_01_QR_PREPARE_STARTED:Zi.FAILED,status:`failed`,message:e.message,data:{role:`display`},interaction:{kind:`qr_display`,overlay:`hide`},error:{code:e.code,message:e.message,retryable:e.code!==Z.UNSUPPORTED&&e.code!==Z.DELIVERY_RECOVERY_REQUIRED}})}emit(e){this.options.options?.onEvent?.(Gi({flowId:this.flowId,...e}))}};function hH(e){let t=e.getState();if(t.cancelled||t.error||!t.session)return!0;switch(t.session.state.state){case`active`:case`expired`:case`cancelled`:case`failed_before_commit`:return!0;case`displaying_qr`:case`claimed`:case`awaiting_target_factor`:case`awaiting_source_contribution`:case`provisioning`:case`authority_pending_local_install`:return!1;default:return sr(t.session.state)}}var gH=class{deps;activeDeviceLinkFlow=null;activeOwnerLinkCancellation=null;constructor(e){this.deps=e}async startDevice2LinkingFlow(e){if(this.activeDeviceLinkFlow&&hH(this.activeDeviceLinkFlow)&&(this.activeDeviceLinkFlow=null),this.activeDeviceLinkFlow)throw Error(`Device-link QR flow is already running`);let t=new mH(e,this.deps.ports,this.deps.getContext);this.activeDeviceLinkFlow=t;try{return await t.generateQR()}catch(e){throw this.activeDeviceLinkFlow===t&&(this.activeDeviceLinkFlow=null),e}}async cancelDeviceLinking(){if(this.activeDeviceLinkFlow&&hH(this.activeDeviceLinkFlow)&&(this.activeDeviceLinkFlow=null),this.activeDeviceLinkFlow){await this.activeDeviceLinkFlow.cancel(),this.activeDeviceLinkFlow=null;return}let e=this.activeOwnerLinkCancellation;e&&(await this.deps.ports.transport.cancelClaimedSessionV1(e),this.activeOwnerLinkCancellation===e&&(this.activeOwnerLinkCancellation=null))}async scanAndLinkDevice(e,t){return await kB(this.deps.getContext(),e,t,this.deps.ports,this.registerOwnerLinkCancellationV1.bind(this))}registerOwnerLinkCancellationV1(e){this.activeOwnerLinkCancellation=e}};function _H(e){let t=r(e.authMethod.walletAuthMethodId);if(!t.ok)throw Error(t.error.message);let n=Pt(e.verificationDigestB64u);return e.kind===`verified_passkey_target_v1`?{kind:`passkey`,walletAuthMethodId:t.value,verificationDigestB64u:n,rpId:e.authMethod.rpId,credentialIdB64u:e.authMethod.credentialIdB64u}:{kind:`email_otp`,walletAuthMethodId:t.value,verificationDigestB64u:n,emailHashHex:e.authMethod.emailHashHex,registrationAuthorityId:e.authMethod.registrationAuthorityId}}function vH(e){return{async prepareOrdinarySignerMaterialV1(t){if(!(t.factorSecret instanceof ArrayBuffer)||t.factorSecret.byteLength!==32)throw Error(`ordinary signer material factorSecret must be 32 bytes`);let n=xH(t.preparations),r=CH(t.recipientRequests),i=TH(t.recipientInputs);OH(i,r);let a=[t.factorSecret,...DH(i)];return bH(await e({kind:`device_linking_ordinary_signer_material_prepare_private_v1`,handleId:D(t.keyMaterial.handleId,`keyMaterial.handleId`,`is required`),targetFactor:_H(t.targetFactor),preparations:n,recipientRequests:r,recipientInputs:i,factorSecret:t.factorSecret},a))},async createOrdinarySignerMaterialRecipientRequestsV1(t){return wH(await e({kind:`device_linking_ordinary_signer_material_recipient_prepare_v1`,handleId:D(t.keyMaterial.handleId,`keyMaterial.handleId`,`is required`),requirements:SH(t.requirements)}))},async sealCommittedAuthorityPackagesV1(t){let n=Bn(t.committed);return PH(await e({kind:`device_linking_ordinary_signer_material_seal_v1`,handleId:D(t.keyMaterial.handleId,`keyMaterial.handleId`,`is required`),committed:n,targetFactor:_H(t.targetFactor),resealedExportRoot:yH(t.resealedExportRoot)}))}}}function yH(e){if(e===null)return null;if(!vo(e,[`envelope`]))throw Error(`ordinary material resealed export root has unsupported fields`);return{envelope:vn(e.envelope)}}function bH(e){if(!vo(e,[`kind`,`targetFactor`,`preparations`]))throw Error(`ordinary material preparation result has invalid fields`);if(e.kind!==`device_linking_ordinary_signer_material_preparation_v1`)throw Error(`ordinary material preparation result kind is invalid`);return{kind:`device_linking_ordinary_signer_material_preparation_v1`,targetFactor:MH(e.targetFactor),preparations:xH(e.preparations)}}function xH(e){if(!Array.isArray(e)||e.length===0||e.length>2)throw Error(`ordinary signer material preparations must contain one or two entries`);let t=e.map(jH),n=t.map(e=>`kind`in e?`ed25519`:`ecdsa_secp256k1`);if(new Set(n).size!==t.length)throw Error(`ordinary signer material preparations repeat a key family`);let r=t.map(e=>`kind`in e?e.targetMaterialActivation:e.target.activation);if(r.length===2&&r[0].activationId===r[1].activationId)throw Error(`ordinary signer material preparations repeat an activation reference`);let i=t[0];if(!i)throw Error(`ordinary signer material preparations are empty`);return[i,...t.slice(1)]}function SH(e){if(!Array.isArray(e)||e.length===0||e.length>2)throw Error(`ordinary signer material recipient requirements must contain one or two entries`);let t=e.map((e,t)=>{if(!vo(e,[`kind`,`keyFamily`,`walletKeyId`]))throw Error(`ordinary recipient requirement ${t} has invalid fields`);if(e.kind!==`ordinary_signer_material_recipient_requirement_v1`)throw Error(`ordinary recipient requirement kind is invalid`);if(e.keyFamily!==`ed25519`&&e.keyFamily!==`ecdsa_secp256k1`)throw Error(`ordinary recipient requirement key family is invalid`);let n=AH(e.walletKeyId);return{kind:e.kind,keyFamily:e.keyFamily,walletKeyId:n}});kH(t);let n=t[0];if(!n)throw Error(`ordinary recipient requirements are empty`);return[n,...t.slice(1)]}function CH(e){if(!Array.isArray(e)||e.length===0||e.length>2)throw Error(`ordinary signer material recipient requests must contain one or two entries`);let t=e.map(e=>{if(vo(e,[`kind`,`keyFamily`,`walletKeyId`,`recipientPublicKeyB64u`])){if(e.kind!==`ordinary_ed25519_signer_material_recipient_request_v1`||e.keyFamily!==`ed25519`)throw Error(`ordinary Ed25519 recipient request kind is invalid`);return{kind:`ordinary_ed25519_signer_material_recipient_request_v1`,keyFamily:`ed25519`,walletKeyId:AH(e.walletKeyId),recipientPublicKeyB64u:FH(e.recipientPublicKeyB64u,`Ed25519 recipient public key`)}}if(vo(e,[`kind`,`keyFamily`,`walletKeyId`,`clientEphemeralPublicKey`])){if(e.kind!==`ordinary_ecdsa_signer_material_recipient_request_v1`||e.keyFamily!==`ecdsa_secp256k1`)throw Error(`ordinary ECDSA recipient request kind is invalid`);return{kind:`ordinary_ecdsa_signer_material_recipient_request_v1`,keyFamily:`ecdsa_secp256k1`,walletKeyId:AH(e.walletKeyId),clientEphemeralPublicKey:D(e.clientEphemeralPublicKey,`ECDSA client ephemeral public key`,`is required`)}}throw Error(`ordinary recipient request key family is invalid`)});kH(t);let n=t[0];if(!n)throw Error(`ordinary recipient requests are empty`);return[n,...t.slice(1)]}function wH(e){if(!vo(e,[`kind`,`recipientRequests`,`recipientInputs`]))throw Error(`ordinary recipient preparation result has invalid fields`);if(e.kind!==`device_linking_ordinary_signer_material_recipient_preparation_v1`)throw Error(`ordinary recipient preparation result kind is invalid`);let t=CH(e.recipientRequests),n=TH(e.recipientInputs);return OH(n,t),{recipientRequests:t,recipientInputs:n}}function TH(e){if(!Array.isArray(e)||e.length===0||e.length>2)throw Error(`ordinary signer material recipient inputs must contain one or two entries`);let t=e.map(e=>{if(vo(e,[`kind`,`keyFamily`,`walletKeyId`,`recipientPrivateKey`])){if(e.kind!==`ordinary_ed25519_signer_material_recipient_input_v1`||e.keyFamily!==`ed25519`)throw Error(`ordinary Ed25519 recipient input kind is invalid`);return{kind:`ordinary_ed25519_signer_material_recipient_input_v1`,keyFamily:`ed25519`,walletKeyId:AH(e.walletKeyId),recipientPrivateKey:EH(e.recipientPrivateKey,`Ed25519 recipient private key`)}}if(vo(e,[`kind`,`keyFamily`,`walletKeyId`,`clientEphemeralPrivateKey`])){if(e.kind!==`ordinary_ecdsa_signer_material_recipient_input_v1`||e.keyFamily!==`ecdsa_secp256k1`)throw Error(`ordinary ECDSA recipient input kind is invalid`);return{kind:`ordinary_ecdsa_signer_material_recipient_input_v1`,keyFamily:`ecdsa_secp256k1`,walletKeyId:AH(e.walletKeyId),clientEphemeralPrivateKey:EH(e.clientEphemeralPrivateKey,`ECDSA client ephemeral private key`)}}throw Error(`ordinary recipient input key family is invalid`)});kH(t);let n=t[0];if(!n)throw Error(`ordinary recipient inputs are empty`);return[n,...t.slice(1)]}function EH(e,t){if(!(e instanceof ArrayBuffer)||e.byteLength!==32)throw Error(`${t} must be a 32-byte ArrayBuffer`);return e}function DH(e){return e.map(e=>e.kind===`ordinary_ed25519_signer_material_recipient_input_v1`?e.recipientPrivateKey:e.clientEphemeralPrivateKey)}function OH(e,t){if(e.length!==t.length)throw Error(`ordinary recipient inputs and requests have different lengths`);for(let n of t)if(e.filter(e=>e.walletKeyId===n.walletKeyId&&e.keyFamily===n.keyFamily).length!==1)throw Error(`ordinary recipient input for ${String(n.walletKeyId)} is missing or duplicated`)}function kH(e){let t=new Set,n=new Set;for(let r of e){if(t.has(r.keyFamily))throw Error(`ordinary recipient family repeats`);if(n.has(String(r.walletKeyId)))throw Error(`ordinary recipient wallet key repeats`);t.add(r.keyFamily),n.add(String(r.walletKeyId))}let r=e[0];if(e.length===2&&r?.keyFamily!==`ed25519`)throw Error(`ordinary recipient requests must be ordered Ed25519 then ECDSA`)}function AH(e){let n=t(e);if(!n.ok)throw Error(n.error.message);return n.value}function jH(e){return Rr(e)}function MH(e){if(vo(e,[`kind`,`walletAuthMethodId`,`verificationDigestB64u`,`rpId`,`credentialIdB64u`])){if(e.kind!==`passkey`)throw Error(`ordinary material target factor kind is unsupported`);let t=r(e.walletAuthMethodId);if(!t.ok)throw Error(t.error.message);let n=Pt(e.verificationDigestB64u);return{kind:`passkey`,walletAuthMethodId:t.value,verificationDigestB64u:n,rpId:D(e.rpId,`ordinary target factor rpId`,`is required`),credentialIdB64u:FH(e.credentialIdB64u,`ordinary target factor credentialIdB64u`)}}if(vo(e,[`kind`,`walletAuthMethodId`,`verificationDigestB64u`,`emailHashHex`,`registrationAuthorityId`])){if(e.kind!==`email_otp`)throw Error(`ordinary material target factor kind is unsupported`);let t=r(e.walletAuthMethodId);if(!t.ok)throw Error(t.error.message);let n=Pt(e.verificationDigestB64u),i=D(e.emailHashHex,`ordinary target factor emailHashHex`,`is required`);if(!/^[0-9a-f]{64}$/.test(i))throw Error(`ordinary target factor emailHashHex is invalid`);return{kind:`email_otp`,walletAuthMethodId:t.value,verificationDigestB64u:n,emailHashHex:i,registrationAuthorityId:D(e.registrationAuthorityId,`ordinary target factor registrationAuthorityId`,`is required`)}}throw Error(`ordinary material target factor kind is unsupported`)}function NH(e){if(!vo(e,[`kind`,`authorityId`,`walletAuthMethodId`,`walletKeyId`,`envelope`]))throw Error(`ordinary material export-root record has invalid fields`);if(e.kind!==`wallet_authority_export_root_v1`)throw Error(`ordinary material export-root record kind is invalid`);let n=s(e.authorityId);if(!n.ok)throw Error(n.error.message);let i=r(e.walletAuthMethodId);if(!i.ok)throw Error(i.error.message);let a=t(e.walletKeyId);if(!a.ok)throw Error(a.error.message);return{kind:`wallet_authority_export_root_v1`,authorityId:n.value,walletAuthMethodId:i.value,walletKeyId:a.value,envelope:vn(e.envelope)}}function PH(e){if(!vo(e,[`signerMaterials`,`exportRoot`,`installedRecordSetDigestB64u`])||!Array.isArray(e.signerMaterials)||e.signerMaterials.length===0)throw Error(`ordinary material worker returned an invalid sealed record set`);let t=e.signerMaterials.map(e=>ta(e)),n=t[0];if(!n)throw Error(`ordinary material worker returned an invalid sealed record set`);return{signerMaterials:[n,...t.slice(1)],exportRoot:e.exportRoot===null?null:NH(e.exportRoot),installedRecordSetDigestB64u:Pt(e.installedRecordSetDigestB64u)}}function FH(e,t){let n=D(e,t,`is required`),r;try{r=F(n)}catch{throw Error(`${t} is invalid base64url`)}if(r.length===0||P(r)!==n)throw r.fill(0),Error(`${t} must be canonical non-empty base64url`);return r.fill(0),n}function IH(e,t){if(typeof e!=`string`||e.trim()!==e||e.length===0)throw Error(`${t} is required`);return e}function LH(e,t){try{return Pt(e)}catch(e){throw Error(`${t} ${e instanceof Error?e.message:`is invalid`}`)}}function RH(e,t,n){let r=IH(e,n);if(!/^[A-Za-z0-9_-]+$/.test(r))throw Error(`${n} is invalid`);let i;try{i=F(r)}catch{throw Error(`${n} is invalid`)}if(i.length!==t||P(i)!==r)throw Error(`${n} must be canonical base64url`);return i.fill(0),r}function zH(e){if(!vo(e,[`kind`,`handleId`]))throw Error(`device-linking key handle has invalid fields`);let t=e;if(t.kind!==`device_linking_key_material_handle_v1`)throw Error(`device-linking key handle kind is invalid`);return{kind:`device_linking_key_material_handle_v1`,handleId:IH(t.handleId,`device-linking key handle.handleId`)}}function BH(e){if(!vo(e,[`handleId`,`linkPublicKeyB64u`,`devicePublicKeyB64u`,`deliveryRecipientPublicKey65B64u`]))throw Error(`device-linking key create response has invalid fields`);let t=e;return{handle:{kind:`device_linking_key_material_handle_v1`,handleId:IH(t.handleId,`device-linking key create handleId`)},linkPublicKeyB64u:Yn(t.linkPublicKeyB64u),devicePublicKeyB64u:Yn(t.devicePublicKeyB64u),deliveryRecipientPublicKey65B64u:RH(t.deliveryRecipientPublicKey65B64u,65,`deliveryRecipientPublicKey65B64u`)}}function VH(e){if(!vo(e,[`kind`,`verificationGrant`,`factorSecret`]))throw Error(`device-linking Email OTP factor release response has invalid fields`);let t=e;if(t.kind!==`device_linking_email_otp_factor_release_result_v1`)throw Error(`device-linking Email OTP factor release response kind is invalid`);if(!(t.factorSecret instanceof ArrayBuffer)||t.factorSecret.byteLength!==32)throw Error(`device-linking Email OTP factor release secret is invalid`);return{kind:`device_linking_email_otp_factor_release_result_v1`,verificationGrant:Rn(t.verificationGrant),factorSecret:t.factorSecret}}function HH(e){return ze(e)}function UH(e){if(!vo(e,[`signatureB64u`]))throw Error(`device-linking request signature response has invalid fields`);return{signatureB64u:RH(e.signatureB64u,64,`signatureB64u`)}}function WH(e){if(vo(e,[`id`,`ok`,`result`])&&e.ok===!0){let t=e.id;return typeof t!=`string`||t.trim()!==t||t.length===0?null:{id:t,ok:!0,result:e.result}}if(vo(e,[`id`,`ok`,`error`])&&e.ok===!1){let t=e.id;return typeof t!=`string`||t.trim()!==t||t.length===0||typeof e.error!=`string`||!e.error.trim()?null:{id:t,ok:!1,error:e.error}}return null}function GH(){if(!globalThis.crypto||typeof globalThis.crypto.getRandomValues!=`function`)throw Error(`secure randomness is unavailable for device-linking worker`);let e=globalThis.crypto.getRandomValues(new Uint8Array(16)),t=`device-linking-${P(e)}`;return e.fill(0),t}function KH(e){return e!==void 0&&Number.isSafeInteger(e)&&e>0?e:6e4}function qH(e){return e instanceof Error?e:typeof e==`string`&&e.trim()?Error(e):Error(`device-linking worker failed`)}function JH(){if(typeof Worker>`u`)throw Error(`device-linking worker is unavailable; provide an authenticated worker endpoint`);let e=rp(void 0,{worker:`deviceLinking`});return new Worker(e,{type:`module`})}function YH(e){if(!e.startsWith(`/`)||e.includes(`?`)||e.includes(`#`)||e.trim()!==e)throw Error(`canonicalPath is invalid`);return e}function XH(e,t){if(!Number.isSafeInteger(e)||e<=0)throw Error(`${t} is invalid`);return e}function ZH(e){let t=S(e.linkSessionId);if(!t.ok)throw Error(t.error.message);if(e.method!==`GET`&&e.method!==`POST`)throw Error(`method is invalid`);let n=XH(e.expiresAtMs,`expiresAtMs`),r=XH(e.issuedAtMs,`issuedAtMs`);if(n<=r)throw Error(`expiresAtMs must be after issuedAtMs`);return{kind:`device_linking_request_sign_v1`,handleId:IH(e.handle.handleId,`handle.handleId`),linkSessionId:t.value,method:e.method,canonicalPath:YH(e.canonicalPath),bodyDigestB64u:LH(e.bodyDigestB64u,`bodyDigestB64u`),devicePublicKeyDigestB64u:LH(e.devicePublicKeyDigestB64u,`devicePublicKeyDigestB64u`),challengeB64u:RH(e.challengeB64u,32,`challengeB64u`),issuedAtMs:r,expiresAtMs:n}}function QH(e={}){let t=KH(e.timeoutMs),n=new Map,i=e.endpoint??null,a=!1,o=e=>{let t=WH(e.data);if(!t)return;let r=n.get(t.id);r&&(clearTimeout(r.timeoutId),n.delete(t.id),t.ok?r.resolve(t.result):r.reject(Error(t.error)))},c=e=>{let t=qH(e.message);for(let[e,r]of n)clearTimeout(r.timeoutId),n.delete(e),r.reject(t)},l=e=>{e.addEventListener(`message`,o),e.addEventListener(`error`,c)};e.endpoint&&(l(e.endpoint),i=e.endpoint);let u=()=>{if(i)return i;let e=JH();try{return l(e),i=e,e}catch(t){throw e.terminate(),t}},d=()=>{if(a)return;a=!0;let e=i;e?.removeEventListener(`message`,o),e?.removeEventListener(`error`,c);let t=Error(`device-linking worker transport is closed`);for(let[e,r]of n)clearTimeout(r.timeoutId),n.delete(e),r.reject(t);e?.terminate(),i=null},m=(e,r)=>{if(a)return Promise.reject(Error(`device-linking worker transport is closed`));let i;try{i=u()}catch(e){return Promise.reject(qH(e))}let o=GH();return new Promise((a,s)=>{let c=setTimeout(()=>{n.delete(o),s(Error(`device-linking worker request timed out after ${t}ms`))},t);n.set(o,{resolve:a,reject:s,timeoutId:c});try{i.postMessage({id:o,request:e},r)}catch(e){clearTimeout(c),n.delete(o),s(qH(e))}})};return{...vH(m),close:d,async createBootstrapKeyMaterialV1(){return BH(await m({kind:`device_linking_key_material_create_v1`}))},async discardKeyMaterialV1(e){await m({kind:`device_linking_key_material_discard_v1`,handleId:zH(e.handle).handleId})},async openEmailOtpFactorReleaseV1(e){let t=zH(e.keyMaterial),n=_(e.walletId);if(!n.ok)throw Error(n.error.message);let i=S(e.linkSessionId);if(!i.ok)throw Error(i.error.message);let a=f(e.enrollmentId);if(!a.ok)throw Error(a.error.message);let o=p(e.deviceId);if(!o.ok)throw Error(o.error.message);let s=r(e.walletAuthMethodId);if(!s.ok)throw Error(s.error.message);let c=r(e.baseWalletAuthMethodId);if(!c.ok)throw Error(c.error.message);let l=LH(e.targetPreparationDigestB64u,`targetPreparationDigestB64u`),u=IH(e.expectedChallengeId,`expectedChallengeId`),d=Rn(e.verificationGrant),h=Fn(e.factorRelease);return VH(await m({kind:`device_linking_email_otp_factor_release_open_v1`,handleId:t.handleId,walletId:n.value,linkSessionId:i.value,enrollmentId:a.value,deviceId:o.value,walletAuthMethodId:s.value,baseWalletAuthMethodId:c.value,targetPreparationDigestB64u:l,expectedChallengeId:u,verificationGrant:d,factorRelease:h}))},async openWalletSessionCredentialDeliveryV1(e){let t=zH(e.keyMaterial),n=vr(e.delivery),i=e.expected,a=_(i.walletId);if(!a.ok)throw Error(a.error.message);let o=s(i.authorityId);if(!o.ok)throw Error(o.error.message);let c=S(i.linkSessionId);if(!c.ok)throw Error(c.error.message);let l=r(i.walletAuthMethodId);if(!l.ok)throw Error(l.error.message);return HH(await m({kind:`device_linking_wallet_session_credential_delivery_open_v1`,handleId:t.handleId,delivery:n,expected:{...i,linkSessionId:c.value,walletId:a.value,authorityId:o.value,walletAuthMethodId:l.value,deliveryBinding:cr(i.deliveryBinding)}}))},async signDeviceSessionRequestV1(e){return UH(await m(ZH(e)))}}}function $H(e){return{claimSessionV1:async t=>eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(t.request.payload.linkSessionId)}/claim`,body:t.request,authentication:t.authentication}),jn),resolveEmailOtpBaseFactorV1:async t=>eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(t.linkSessionId)}/email-otp-base-factor`,body:t.request,authentication:t.authentication}),An),cancelClaimedSessionV1:async t=>eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(t.linkSessionId)}/owner-cancel`,body:{expectedRevision:t.expectedRevision},authentication:t.authentication}),rU),recordOwnerApprovalV1:async t=>eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(t.approval.linkSessionId)}/approval`,body:t.approval,authentication:t.authentication}),pr),getSourceContributionPreparationV1:async t=>{let n=await e.request.requestOwnerV1({method:`GET`,canonicalPath:`${oU(t.linkSessionId)}/source-contribution-preparation`,authentication:t.authentication});return n.status===204?null:eU(n,Xr)},recordSourceContributionV1:async t=>eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(t.approval.linkSessionId)}/source-contribution`,body:t.approval,authentication:t.authentication}),nU),getApprovalV1:e.approvalUpdates.getApprovalV1,getEd25519ExportRootRecipientV1:async t=>{let n=await e.request.requestOwnerV1({method:`GET`,canonicalPath:`${oU(t.linkSessionId)}/ed25519-export-root-recipient`,authentication:t.authentication});return n.status===204?null:eU(n,Kn)},submitEd25519ExportRootPackageV1:async t=>{eU(await e.request.requestOwnerV1({method:`POST`,canonicalPath:`${oU(sU(t.submission.linkSessionId))}/ed25519-export-root`,body:t.submission,authentication:t.authentication}),e=>e)},subscribeApprovalV1:e.approvalUpdates.subscribeApprovalV1}}function eU(e,t){if(e.status<200||e.status>=300)throw Object.assign(Error(tU(e)),{status:e.status});return t(e.body)}function tU(e){let t=aU(e.body);return t?`linked-device owner request failed: ${t.message}`:`linked-device owner request failed with HTTP ${e.status}`}function nU(e){let t=iU(e);if(!t)throw Error(`linked-device source contribution response is invalid`);return Pn(t.session)}function rU(e){let t=iU(e);if(!t)throw Error(`linked-device session response is invalid`);return Pn(t.session)}function iU(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return null;let t=new Map(Object.entries(e)),n=[...t.keys()],r=new Set([`ok`,`outcome`,`session`]);return n.length!==r.size||!n.every(e=>r.has(e))||t.get(`ok`)!==!0||t.get(`outcome`)!==`applied`&&t.get(`outcome`)!==`replayed`?null:{session:t.get(`session`)}}function aU(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return null;let t=new Map(Object.entries(e)),n=[...t.keys()];if(n.length===0||n.length>2||!n.every(e=>e===`code`||e===`message`))return null;let r=t.get(`message`);return typeof r==`string`?{message:r}:null}function oU(e){return`${Uz}/${String(e)}`}function sU(e){let t=S(e);if(!t.ok)throw Error(t.error.message);return t.value}function cU(e){let t=a(e);if(t.ok)return t.value;throw Error(t.error.message)}function lU(e){switch(e){case`ble`:case`cable`:case`hybrid`:case`internal`:case`nfc`:case`smart-card`:case`usb`:return e;default:throw Error(`linked-device WebAuthn transport ${e} is unsupported`)}}function uU(e){e.byteLength>0&&e.fill(0)}function dU(e){let t=e.credential.authenticatorAttachment;if(t!==void 0&&t!==`platform`&&t!==`cross-platform`)throw Error(`linked-device WebAuthn authenticator attachment is invalid`);return{kind:`linked_device_webauthn_registration_v1`,credentialIdB64u:cU(e.credentialIdB64u),authenticatorAttachment:t??null,clientDataJsonB64u:e.credential.response.clientDataJSON,attestationObjectB64u:e.credential.response.attestationObject,transports:e.credential.response.transports.map(lU)}}function fU(e){return{async createTargetCredentialV1(t){let n=t.preparation.passkeyCreationOptions;if(n.walletAuthMethodId!==t.preparation.walletAuthMethodId)throw Error(`linked-device passkey options are bound to a different auth method`);let r=await e.authenticator.run({kind:`create_passkey`,registrationOptions:n,requirePrfFirst:!0});if(!r.ok)throw Error(`linked-device passkey creation failed: ${r.message}`);if(r.operation!==`create_passkey`||!r.requirePrfFirst)throw Error(`linked-device passkey creation returned the wrong operation result`);let i=dU(r),a=F(r.prf.prfFirstB64u);if(a.byteLength!==32)throw uU(a),Error(`linked-device passkey PRF output must be 32 bytes`);return{walletAuthMethodId:n.walletAuthMethodId,webauthnRegistration:i,factorSecret:a}}}}function pU(e,t){return t.authorityId===e.authorityId&&t.linkSessionId===e.linkSessionId&&t.packageSetDigestB64u===e.packageSetDigestB64u}async function mU(e){let[t,n]=await Promise.all([e.installation.listCommittedDeliveryResumesV1(),e.installation.listPendingActivationAcknowledgementsV1()]);for(let r of n){let n=t.find(pU.bind(null,r));if(!n)throw Error(`durable linked-device acknowledgement has no matching resume`);let i=await e.readExactSession({walletId:n.walletId,authorityId:n.authorityId,authMethodId:n.authMethodId});i.kind!==`missing`&&await _V({installation:e.installation,transport:e.transport,walletId:n.walletId,authorityId:n.authorityId,authMethodId:n.authMethodId,operationCredential:i.operationCredential})}}async function hU(e){let t=await q.readExactWithOperationCredential(e);switch(t.kind){case`found`:return{kind:`found`,operationCredential:t.operationCredential};case`missing`:return{kind:`missing`};case`upgrade_required`:throw Error(`Linked-device acknowledgement requires a newer client`)}}function gU(e){let t=QH({...e.workerEndpoint?{endpoint:e.workerEndpoint}:{},...e.workerTimeoutMs===void 0?{}:{timeoutMs:e.workerTimeoutMs}}),n=iB({owner:$H({request:e.ownerRequest,approvalUpdates:e.ownerApprovalUpdates}),http:e.http,relayerUrl:e.relayerUrl,publishableKey:e.publishableKey,projectEnvironmentId:e.projectEnvironmentId,keyMaterial:t,nowMs:e.nowMs,pollIntervalMs:e.pollIntervalMs}),r=nB({http:e.http,relayerUrl:e.relayerUrl,projectEnvironmentId:e.projectEnvironmentId}),i=fU({authenticator:e.authenticator}),a=SV({indexedDB:K,sealing:t,nowMs:e.nowMs}),o=QB(e.custodyCeremonyTransport);return{transport:n,ownerAuthorization:e.ownerAuthorization,sourceContribution:e.sourceContribution,keyMaterial:t,targetCredential:i,authorityInstallation:a,readExpectedLockGenerationV1:async e=>{let t=await K.resolveSelectedWalletAuthority(String(e));if(t.kind===`missing_selection`)return 0;if(t.kind!==`resolved`)throw Error(`selected wallet authority is unavailable: ${t.kind}`);return t.selection.lockGeneration},ed25519ExportRoot:o,resumePendingAcknowledgementsV1:mU.bind(null,{installation:a,transport:r,readExactSession:hU}),dispose:t.close}}const _U=`/wallet/device-linking/v1/devices`;var vU=class extends Error{code=`owner_wallet_session_reauth_required`;constructor(){super(`The owner Wallet Session must be renewed`),this.name=`OwnerWalletSessionReauthRequiredError`}};function yU(e){let t=gU(e);return{linkedDeviceManagement:bU({request:e.managementRequest,authorizeRemoval:e.authorizeRemoval}),deviceLinkingPorts:t,dispose:t.dispose}}function bU(e){return{listLinkedDevices:async({walletId:t,limit:n,cursor:r})=>{let i=hr({kind:`linked_device_list_request_v1`,walletId:t,limit:n,cursor:r}),a=`${_U}?walletId=${encodeURIComponent(String(i.walletId))}&limit=${encodeURIComponent(String(i.limit))}&cursor=${encodeURIComponent(i.cursor??``)}`,o=await e.request.request({method:`GET`,canonicalPath:a,walletId:i.walletId});return SU(o,`list linked devices`),wU(o.body)},revokeLinkedDevice:async({walletId:t,walletAuthMethodId:n})=>{let{requestedAtMs:r,sourceProof:i}=await e.authorizeRemoval({walletId:t,walletAuthMethodId:n}),a=lr({kind:`linked_device_revoke_request_v1`,walletId:t,walletAuthMethodId:n,requestedAtMs:r}),o=async()=>await e.request.request({method:`POST`,canonicalPath:`${_U}/${encodeURIComponent(String(n))}/revoke`,body:{...a,sourceProof:i},walletId:t}),s;try{s=await o()}catch(e){if(!(e instanceof Yw)||e.code!==`network_error`)throw e;s=await o()}return xU(s)}}}function xU(e){return e.status===404?nr({kind:`not_found`}):e.status===409?nr({kind:`conflict`}):e.status===401||e.status===403?nr({kind:`unauthorized`}):(SU(e,`revoke linked device`),EU(e.body))}function SU(e,t){if(e.status<200||e.status>=300){if(e.status===401&&kU(e.body))throw new vU;let n=CU(e.body);throw Error(n?`linked-device ${t} failed with HTTP ${e.status}: ${n}`:`linked-device ${t} failed with HTTP ${e.status}`)}}function CU(e){return typeof e!=`object`||!e||Array.isArray(e)?null:OU(e)||kU(e)?e.message:null}function wU(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`linked-device list response must be an object`);if(!TU(e))throw Error(`linked-device list response has unexpected fields`);if(e.ok!==!0)throw Error(`linked-device list response is not successful`);return ur({devices:e.devices,ownerDevices:e.ownerDevices,nextCursor:e.nextCursor})}function TU(e){return Object.keys(e).sort().join(`|`)===`devices|nextCursor|ok|ownerDevices`}function EU(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`linked-device revoke response must be an object`);if(!DU(e))throw Error(`linked-device revoke response has unexpected fields`);if(e.ok!==!0)throw Error(`linked-device revoke response is not successful`);return nr({kind:e.kind,walletAuthMethodId:e.walletAuthMethodId,authorityId:e.authorityId,revocationEpoch:e.revocationEpoch})}function DU(e){return Object.keys(e).sort().join(`|`)===`authorityId|kind|ok|revocationEpoch|walletAuthMethodId`}function OU(e){return Object.keys(e).sort().join(`|`)!==`kind|message|ok`||!(`ok`in e)||!(`kind`in e)||!(`message`in e)?!1:e.ok===!1&&(e.kind===`invalid_input`||e.kind===`internal`)&&typeof e.message==`string`&&e.message.trim().length>0}function kU(e){return typeof e!=`object`||!e||Array.isArray(e)||Object.keys(e).sort().join(`|`)!==`code|kind|message|ok`||!(`ok`in e)||!(`kind`in e)||!(`code`in e)||!(`message`in e)?!1:e.ok===!1&&e.kind===`unauthorized`&&typeof e.code==`string`&&typeof e.message==`string`&&e.message.trim().length>0}function AU(e){if(typeof e!=`string`||!e.trim())throw Error(`Yao lane request JSON is required`);return e}async function jU(e){let t=await Ya({ctx:e.workerCtx,kind:`walletCustodyCeremony`,request:{type:`openEd25519YaoLaneSource`,payload:{kind:`unlocked_ed25519_export_root_capability`,capability:e.capability,applicationBindingDigestB64u:e.applicationBindingDigestB64u,walletKeyId:e.walletKeyId,enrollmentId:e.enrollmentId,revocationEpoch:e.revocationEpoch,registeredPublicKeyB64u:e.registeredPublicKeyB64u}}});return new MU(e.workerCtx,t.sourceHandle)}var MU=class{#e=!1;constructor(e,t){this.workerCtx=e,this.sourceHandle=t}async discard(){this.#e||(this.#e=!0,await Ya({ctx:this.workerCtx,kind:`walletCustodyCeremony`,request:{type:`discardEd25519YaoLaneSource`,payload:{sourceHandle:this.sourceHandle}}}))}async prepareSourcePreservingRegistration(e){if(this.#e)throw Error(`Ed25519 Yao lane source is already consumed`);return this.#e=!0,{requestJson:AU((await Ya({ctx:this.workerCtx,kind:`walletCustodyCeremony`,request:{type:`prepareEd25519YaoSourcePreservingRegistration`,payload:{sourceHandle:this.sourceHandle,targetAdmission:e.targetAdmission,applicationBinding:e.applicationBinding,participantIds:e.participantIds,expectedRegisteredPublicKeyB64u:e.expectedRegisteredPublicKeyB64u,targetClientRecipientPublicKeyB64u:e.targetClientRecipientPublicKeyB64u}}})).requestJson)}}};function NU(e){return async({preparation:t})=>{let n=t.source.activation,r=e.readLinkedEcdsaHolderV1({materialActivation:n});if(r)return PU(r,n);let i=await e.readActiveEcdsaCapabilityManifestV1({materialActivation:n});return FU({sourceActivation:n,manifest:i}),{walletKeyId:IU(i),sourceDerivation:{applicationBindingDigestB64u:Pt(i.durableMaterial.routerAbEcdsaDerivationNormalSigning.scope.context.application_binding_digest_b64u),clientShareRetryCounter:i.durableMaterial.routerAbEcdsaDerivationNormalSigning.scope.public_identity.client_share_retry_counter,ecdsaThresholdKeyId:Pi(i.durableMaterial.roleLocalBinding.ecdsaThresholdKeyId),sourceNormalSigning:i.durableMaterial.routerAbEcdsaDerivationNormalSigning}}}}function PU(e,n){if(!g(e.materialActivation,n))throw Error(`linked ECDSA holder activation does not match preparation`);let r=e.activationReceipt.normalSigning,i=r.scope,a=ai({walletId:e.walletId,signingRootId:i.signing_root_id,signingRootVersion:i.signing_root_version}),o=t(`wallet-key:ecdsa:${e.walletId}:${a}`);if(!o.ok)throw Error(`linked ECDSA source wallet key identity: ${o.error.message}`);return{walletKeyId:o.value,sourceDerivation:{applicationBindingDigestB64u:Pt(i.context.application_binding_digest_b64u),clientShareRetryCounter:i.public_identity.client_share_retry_counter,ecdsaThresholdKeyId:Pi(e.ecdsaThresholdKeyId),sourceNormalSigning:r},linkedHolderHandleId:e.holderHandleId}}function FU(e){if(!g(e.manifest.activation.materialActivation,e.sourceActivation))throw Error(`ECDSA capability manifest activation does not match preparation`)}function IU(e){let n=ai({walletId:e.signer.walletId,signingRootId:e.signer.signingRootId,signingRootVersion:e.signer.signingRootVersion}),r=t(`wallet-key:ecdsa:${e.signer.walletId}:${n}`);if(!r.ok)throw Error(`ECDSA source wallet key identity: ${r.error.message}`);return r.value}function LU(e){return{produceSourceContributionV1:async({preparation:t,capability:n,authentication:r})=>{let i=await jU({workerCtx:e.workerContext,capability:n,applicationBindingDigestB64u:await BU(t.applicationBinding),walletKeyId:String(t.walletKeyId),enrollmentId:String(t.enrollmentId),revocationEpoch:t.sourceRevocationEpoch,registeredPublicKeyB64u:t.sourceRegisteredPublicKeyB64u});try{let n=await i.prepareSourcePreservingRegistration({targetAdmission:t.targetAdmission,applicationBinding:t.applicationBinding,participantIds:t.participantIds,expectedRegisteredPublicKeyB64u:t.sourceRegisteredPublicKeyB64u,targetClientRecipientPublicKeyB64u:t.targetClientRecipientPublicKeyB64u}),a=Jr(await e.executeSourcePreservingV1({linkSessionId:t.linkSessionId,sourceBinding:t.sourceBinding,targetRequestJson:n.requestJson,participantIds:t.participantIds,authentication:r}));return{kind:`linked_device_ed25519_source_contribution_v1`,keyFamily:`ed25519`,linkSessionId:t.linkSessionId,enrollmentId:t.enrollmentId,sourceAuthorityId:t.sourceAuthorityId,walletKeyId:t.walletKeyId,targetDeviceId:t.targetDeviceId,targetFactorVerificationDigestB64u:t.targetFactorVerificationDigestB64u,targetMaterialActivation:t.targetMaterialActivation,targetClientRecipientPublicKeyB64u:t.targetClientRecipientPublicKeyB64u,targetSigningWorkerRecipientPublicKeyB64u:t.targetSigningWorkerRecipientPublicKeyB64u,sourceRegisteredPublicKeyB64u:t.sourceRegisteredPublicKeyB64u,sourceBinding:t.sourceBinding,reservationId:a.reservationId,targetBinding:t.targetAdmission.binding,activationReceipt:a.activationReceipt,participantIds:a.participantIds,deriver_a_client_package:a.deriver_a_client_package,deriver_b_client_package:a.deriver_b_client_package}}finally{await i.discard()}}}}function RU(e){return{ed25519:e.ed25519,ecdsa:{produceSourceContributionV1:async({preparation:t})=>await zU({workerContext:e.workerContext,readMetadataV1:e.readEcdsaMetadataV1,preparation:t})}}}async function zU(e){let t=await e.readMetadataV1({preparation:e.preparation}),n=await qu({preparation:e.preparation,workerCtx:e.workerContext,...t.linkedHolderHandleId===void 0?{}:{linkedHolderHandleId:t.linkedHolderHandleId}});return{kind:`linked_device_ecdsa_source_contribution_v1`,keyFamily:`ecdsa_secp256k1`,linkSessionId:e.preparation.linkSessionId,enrollmentId:e.preparation.enrollmentId,sourceAuthorityId:e.preparation.sourceAuthorityId,walletKeyId:t.walletKeyId,targetDeviceId:e.preparation.target.targetDeviceId,targetFactorVerificationDigestB64u:e.preparation.target.targetFactorVerificationDigestB64u,sourceSigner:e.preparation.source,sourceDerivation:t.sourceDerivation,target:e.preparation.target,package:n.package}}async function BU(e){return P(Uint8Array.from(await qr(e)))}const VU=new ra;async function HU(e,t){let n=await K.resolveSelectedWalletAuthority(String(t.walletId));if(n.kind!==`resolved`)throw Error(`Unlock the wallet before removing a device`);return await Bz(e,{kind:`selected_method`,walletAuthMethodId:n.authMethod.walletAuthMethodId},t)}function UU(e){let{platform:t,ownerAuthorities:n}=e,r=KU({signingEngine:e.signingEngine,ownerRequest:n.ownerRequest,readEcdsaMetadataV1:GU({signingEngine:e.signingEngine})}),i=yU({authenticator:t.authenticator,http:t.http,relayerUrl:String(e.configs.network.relayer?.url||``).trim(),publishableKey:e.configs.registration.publishableKey,projectEnvironmentId:e.configs.registration.projectEnvironmentId,ownerRequest:n.ownerRequest,ownerApprovalUpdates:WU({request:n.ownerRequest,pollIntervalMs:1e3}),ownerAuthorization:n.ownerAuthorization,sourceContribution:r,custodyCeremonyTransport:ro(e.signingEngine.getSignerWorkerContext()),managementRequest:n.managementRequest,authorizeRemoval:HU.bind(void 0,{configs:e.configs,signingEngine:e.signingEngine}),nowMs:Date.now,pollIntervalMs:1e3}),a=new gH({getContext:e.getContext,ports:i.deviceLinkingPorts});return{domain:{linkedDeviceManagement:i.linkedDeviceManagement,startLinking:a.startDevice2LinkingFlow.bind(a),cancelLinking:YU.bind(null,a),approveLinking:Eu.bind(null,{execute:a.scanAndLinkDevice.bind(a),readAppearance:e.readAppearance,readMeasurementBinding:e.signingEngine.getWalletIframeSurfaceMeasurementBinding.bind(e.signingEngine)})},resumePendingAcknowledgementsV1:i.deviceLinkingPorts.resumePendingAcknowledgementsV1,dispose:XU.bind(null,i.dispose)}}function WU(e){return{getApprovalV1:async t=>await qU(e.request,t),subscribeApprovalV1:async t=>JU({...e,input:t})}}function GU(e){return NU({readActiveEcdsaCapabilityManifestV1:async({materialActivation:t})=>{let n=e.signingEngine.readWalletAuthenticationState();if(n.kind!==`authenticated`)throw Error(`ECDSA source metadata requires an authenticated wallet`);let r=await VU.lookupByMaterialActivation({walletId:n.walletId,materialActivation:t});if(r.kind===`ambiguous_authority`&&(r=await Qv({walletId:n.walletId,materialActivation:t,authorities:r.authorities})),r.kind!==`active`)throw Error(`ECDSA source metadata manifest is ${r.kind}`);return r.manifest},readLinkedEcdsaHolderV1:({materialActivation:t})=>{let n=e.signingEngine.readWalletAuthenticationState();return n.kind===`authenticated`?Ld({walletId:n.walletId,materialActivation:t}):null}})}function KU(e){let t=e.signingEngine.getSignerWorkerContext();return RU({workerContext:t,ed25519:LU({workerContext:t,executeSourcePreservingV1:async({linkSessionId:t,targetRequestJson:n,authentication:r})=>{let i=await e.ownerRequest.requestOwnerV1({method:`POST`,canonicalPath:`${Uz}/${String(t)}/source-contribution/execute`,body:JSON.parse(n),authentication:r});if(i.status<200||i.status>=300)throw Error(`Wallet-host Ed25519 source-preserving request failed with HTTP ${i.status}`);return i.body}}),readEcdsaMetadataV1:e.readEcdsaMetadataV1})}async function qU(e,t){let n=await e.requestOwnerV1({method:`GET`,canonicalPath:`${Uz}/${String(t.linkSessionId)}/approval`,authentication:t.authentication});if(n.status<200||n.status>=300)throw Error(`Wallet-host approval request failed with HTTP ${n.status}`);return pr(n.body)}function JU(e){let t=!1,n=null,r=async()=>{if(!t){try{let n=await qU(e.request,e.input);t||e.input.onResult(n)}catch{}t||(n=setTimeout(()=>void r(),e.pollIntervalMs))}};return r(),{close:()=>{t=!0,n&&clearTimeout(n),n=null}}}async function YU(e){wu({kind:`all`}),await e.cancelDeviceLinking()}function XU(e){wu({kind:`all`}),e()}const ZU=[`delivery`,`challengeId`,`otpCode`,`resend`,`webauthn`,`webauthnRegistration`,`webauthn_registration`,`authenticatorOptions`,`publicKey`,`passkey`,`passkeyPrfFirstB64u`],QU=[`recoveryKeys`,`recoveryCodes`,`bootstrap`,`bootstrapMaterial`,`clientSecret32`];function $U(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer timestamp`);return e}function eW(e,t,n){let r=t.find(t=>Object.prototype.hasOwnProperty.call(e,t));if(r)throw Error(`${n} must not include ${r}`)}function tW(e){return N(e,`offerId`)}function nW(e,t=`candidateId`){return N(e,t)}function rW(e){let t=E(e,`registration candidate`);return eW(t,ZU,`registration candidate`),eW(t,QU,`registration candidate`),{candidateId:nW(t.candidateId),walletId:ki(N(t.walletId,`candidate.walletId`))}}function iW(e){let t=E(e,`Google Email OTP registration offer`);if(eW(t,ZU,`Google Email OTP registration offer`),eW(t,QU,`Google Email OTP registration offer`),t.kind!==`google_email_otp_registration_offer_v1`)throw Error(`registration offer kind must be google_email_otp_registration_offer_v1`);if(!Array.isArray(t.candidates)||t.candidates.length<1)throw Error(`registration offer must include at least one candidate`);let n=t.candidates.map(rW),r=nW(t.selectedCandidateId,`selectedCandidateId`);if(!n.some(e=>e.candidateId===r))throw Error(`selectedCandidateId must refer to an offered candidate`);let[i,...a]=n;return{kind:`google_email_otp_registration_offer_v1`,offerId:tW(t.offerId),expiresAtMs:$U(t.expiresAtMs,`expiresAtMs`),emailHint:N(t.emailHint,`emailHint`),candidates:[i,...a],selectedCandidateId:r}}const aW=600*1e3;function oW(e){return{ok:!0,value:e}}function sW(e,t){let n=t instanceof Error&&t.message?t.message:String(t||e),r=t&&typeof t==`object`&&`retryAfterMs`in t?Number(t.retryAfterMs):NaN;return{ok:!1,error:{code:e,message:n,...Number.isFinite(r)&&r>=0?{retryAfterMs:Math.floor(r)}:{}}}}function cW(e,t,n){let r=sW(e,n);return r.ok?r:{ok:!1,error:{...r.error,message:t}}}function lW(e){let t=e&&typeof e==`object`&&`code`in e?String(e.code||``):``;if(t.includes(`rate`))return`email_otp_rate_limited`;if(t.includes(`expired`))return`email_otp_expired`;if(t.includes(`invalid`)||t.includes(`otp`))return`email_otp_invalid_code`;let n=e instanceof Error?e.message.toLowerCase():``;return n.includes(`backup`)?`recovery_code_backup_incomplete`:n.includes(`expired`)?`email_otp_expired`:n.includes(`invalid`)||n.includes(`code`)?`email_otp_invalid_code`:`unlock_failed`}function uW(e){if((e&&typeof e==`object`&&`code`in e?String(e.code||``):``)===`already_finalized_restore_required`)return`registration_restore_required`;let t=e instanceof Error?e.message.toLowerCase():``;return t.includes(`already finalized`)||t.includes(`restore or unlock`)?`registration_restore_required`:t.includes(`backup`)?`recovery_code_backup_incomplete`:t.includes(`expired`)?`flow_expired`:`registration_failed`}function dW(e){let t=String(e.walletId||``).trim();if(!t)throw Error(`Google verification did not return a wallet id`);return ki(t)}function fW(e){let t=String(e.providerSubject||``).trim();if(!t)throw Error(`Google verification did not return a provider subject`);return t}function pW(e){let t=String(e.email||``).trim();if(!t)throw Error(`Google verification did not return an email address`);return t}function mW(e){let t=typeof e==`number`?e:typeof e==`string`?Date.parse(e):NaN;return Number.isFinite(t)&&t>Date.now()?t:Date.now()+aW}function hW(e){let t=typeof e==`number`?e:typeof e==`string`?Date.parse(e):NaN;if(!Number.isFinite(t)||t<=Date.now())throw Error(`Google Email OTP registration offer is expired or missing expiry`);return Math.floor(t)}function gW(e){return e.mode===`register`?{title:`Create your Email OTP wallet`,description:`Google verified ${e.emailHint}.`,submitLabel:`Create wallet`,helperText:``}:{title:`Check your email to unlock your wallet`,description:`Enter the 6-digit code we sent to ${e.emailHint}.`,submitLabel:`Unlock wallet`,helperText:``}}function _W(e){return e===`register_started`?`register`:`login`}function vW(e){if(!e||typeof e!=`object`||!(`code`in e))return!1;let t=String(e.code||``).trim(),n=e instanceof Error?e.message:String(e.message||``).trim();return t===`not_found`&&/Email OTP enrollment not found/i.test(n)}function yW(){return`Account doesn't exist. Create your account to continue.`}function bW(e){return!e||typeof e!=`object`||!(`code`in e)?`google_verification_failed`:Reflect.get(e,`code`)===`stale_identity_mapping`?`google_account_registration_required`:`google_verification_failed`}function xW(e,t){if(e.replaceExistingWallet===!0&&t!==`register`)throw Error(`replaceExistingWallet is only valid with register mode`);return{idToken:e.idToken,accountMode:t,relayUrl:e.relayUrl,restartRegistrationOffer:t===`register`&&e.replaceExistingWallet===!0,...e.mode===`login`&&e.loginTarget.kind===`wallet`?{loginWalletId:String(e.loginTarget.walletId)}:{}}}function SW(e){return e.providerSubject.toLowerCase()===e.verifiedEmail.toLowerCase()?`email`:`google`}async function CW(e){return await e.deps.resolveGoogleEmailOtpProvider(xW(e.input,e.input.mode))}function wW(e){let t=e.authInput.mode===`login`&&e.authInput.loginTarget.kind===`wallet`?ki(String(e.authInput.loginTarget.walletId)):dW(e.resolution),n=pW(e.resolution),r=e.resolution,i=_W(r.mode),a=r.mode===`register_started`?iW({kind:`google_email_otp_registration_offer_v1`,offerId:r?.offer?.offerId,expiresAtMs:hW(r.expiresAtMs),emailHint:n,candidates:r?.offer?.candidates,selectedCandidateId:r?.offer?.selectedCandidateId}):void 0;return{walletId:a?DW(a).walletId:t,...a?{offer:a}:{},providerSubject:fW(e.resolution),emailHint:n,requestedMode:e.authInput.mode,mode:i,expiresAtMs:r.mode===`register_started`?hW(r.expiresAtMs):mW(void 0),...r.mode===`register_started`?{registrationAttemptId:r.registrationAttemptId}:{}}}async function TW(e){if(e.state.mode!==`login`||!e.deps.resolveLinkedEmailOtpWalletAuth)return e.state;let t=await e.deps.resolveLinkedEmailOtpWalletAuth({walletId:String(e.state.walletId),email:e.state.emailHint,provider:SW({providerSubject:e.state.providerSubject,verifiedEmail:e.state.emailHint}),providerSubjectId:e.state.providerSubject});switch(t.kind){case`none`:return e.state;case`selected`:return{...e.state,linkedEmailOtpSelection:t};case`rejected`:throw Error(t.message);default:throw Error(`Google Email OTP linked auth selection is invalid`)}}function EW(e){let t=e.offer.candidates.findIndex(t=>t.walletId===e.currentWalletId);return t<0||e.offer.candidates.length<2?null:e.offer.candidates[(t+1)%e.offer.candidates.length]||null}function DW(e){let t=e.candidates.find(t=>t.candidateId===e.selectedCandidateId);if(!t)throw Error(`Google Email OTP registration offer selected candidate is missing`);return t}async function OW(e){let t=await e.deps.requestEmailOtpChallenge({walletId:e.state.walletId,...e.state.linkedEmailOtpSelection?{walletAuthMethodId:e.state.linkedEmailOtpSelection.walletAuthMethodId}:{},...e.relayUrl?{relayUrl:e.relayUrl}:{},...e.onEvent?{onEvent:e.onEvent}:{}});return{challengeId:t.challengeId,expiresAtMs:kW(t.expiresAtMs),emailHint:t.delivery.emailHint,delivery:t.delivery,walletAuthMethodId:t.walletAuthMethodId,signerSelection:t.signerSelection}}function kW(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=Date.now())throw Error(`Email code challenge is expired or missing expiry`);return e}function AW(e){let t=e.policy||{kind:`configured`};return t.kind===`none`?[]:t.kind===`explicit`?t.targets:Ks({signerOptions:e.configs.signing.thresholdEcdsa.provisioningDefaults,chains:e.configs.network.chains}).map(e=>e.chainTarget)}function jW(e){let t=e.policy||{kind:`configured`};return t.kind===`none`?[]:t.kind===`explicit`?t.targets:jo(e.configs.network.chains).map(e=>e.chainTarget)}function MW(e){return{...e.onEvent?{onEvent:e.onEvent}:{},...e.recoveryCodeBackup?{recoveryCodeBackup:e.recoveryCodeBackup}:{}}}function NW(e){let t=Math.floor(Number(e.signing.sessionDefaults?.remainingUses)||0);return t<=0?xe:Math.min(t,xe)}async function PW(e){let t=En({walletId:e.state.walletId}),n={kind:`wallet_auth_method`,walletAuthMethodId:e.challenge.walletAuthMethodId},[r]=e.targets;if(!r){if(e.challenge.signerSelection.kind!==`ed25519_only`)throw Error(`Selected Email OTP authority requires an ECDSA chain target`);await e.deps.loginWithEmailOtpEd25519YaoCapability({walletSession:t,authoritySelector:n,providerSubjectId:e.state.providerSubject,emailOtpAuthorityEmail:e.state.emailHint,challengeId:e.challenge.challengeId,otpCode:e.otpCode,remainingUses:NW(e.deps.configs),ed25519Selection:e.challenge.signerSelection});return}let i={walletSession:t,walletAuthMethodId:n.walletAuthMethodId,providerIdentity:{provider:SW({providerSubject:e.state.providerSubject,verifiedEmail:e.state.emailHint}),providerSubjectId:e.state.providerSubject},challengeId:e.challenge.challengeId,emailOtpAuthorityEmail:e.state.emailHint,otpCode:e.otpCode,...e.input.relayUrl?{relayUrl:e.input.relayUrl}:{},...e.input.emailOtpAuthPolicy?{emailOtpAuthPolicy:e.input.emailOtpAuthPolicy}:{},...e.input.onEvent?{onEvent:e.input.onEvent}:{}};if(e.challenge.signerSelection.kind!==`ecdsa`)throw Error(`Selected Email OTP authority has no ECDSA signer`);await e.deps.loginWithEmailOtpEcdsaCapability({...i,chainTarget:r,publicationChainTargets:e.targets,keyHandle:e.challenge.signerSelection.keyHandle,ed25519Selection:e.challenge.signerSelection.ed25519})}function FW(e){return{...e.options,signerOptions:{tempo:{enabled:!1,signingSession:{kind:`jwt`,ttlMs:0,remainingUses:0}},evm:{enabled:!1,signingSession:{kind:`jwt`,ttlMs:0,remainingUses:0}}}}}async function IW(e,t){let n=await e.getWalletSession(t);if(n.appIdentity.kind!==`resolved`||String(n.appIdentity.walletId)!==String(t)||n.authentication.kind!==`authenticated`||String(n.authentication.walletId)!==String(t))throw Error(`Wallet auth completed, but the local signing session is not ready yet.`);return n}async function LW(e,t){let n=await e.getWalletSession(t);if(n.appIdentity.kind!==`resolved`||String(n.appIdentity.walletId)!==String(t))throw Error(`Wallet registration completed, but the local wallet identity is not ready.`);return n}function RW(e,t){return as(t)?{kind:`started`,completion:e.prewarmEmailOtpYao().catch(()=>void 0)}:{kind:`not_started`}}async function zW(e,t){let n;try{n=wW({authInput:t,resolution:await CW({deps:e,input:t})}),n=await TW({deps:e,state:n})}catch(e){return sW(bW(e),e)}if(n.mode===`register`)return oW(UW(e,{state:n,input:t,prewarm:{kind:`not_started`}}));try{let r=await OW({deps:e,state:n,...t.relayUrl?{relayUrl:t.relayUrl}:{},...t.onEvent?{onEvent:t.onEvent}:{}});return oW(GW(e,{state:n,challenge:r,input:t}))}catch(e){return vW(e)?cW(`google_account_registration_required`,yW(),e):sW(`email_otp_challenge_failed`,e)}}async function BW(e,t){if(t.method===`google`){let n=await zW(e,{mode:`login`,idToken:t.idToken,loginTarget:t.target,onEvent:t.onEvent});return n.ok?n.value.mode===`login`?oW(n.value):sW(`unlock_failed`,Error(`Email unlock requires an existing wallet`)):n}try{let n=t.email.trim().toLowerCase();if(!n)throw Error(`Email address is required`);let r=await TW({deps:e,state:{walletId:ki(t.walletId),providerSubject:n,emailHint:n,requestedMode:`login`,mode:`login`,expiresAtMs:Date.now()+aW}});return r.linkedEmailOtpSelection?oW(GW(e,{state:r,challenge:await OW({deps:e,state:r,onEvent:t.onEvent}),input:{onEvent:t.onEvent}})):sW(`unlock_failed`,Error(`No active email method matches this wallet`))}catch(e){return sW(`email_otp_challenge_failed`,e)}}function VW(e){let t=!0;return{ensureActive(){if(!t)throw Error(`Google Email OTP wallet auth flow is no longer active`);if(Date.now()>e.state.expiresAtMs)throw t=!1,Error(`Google Email OTP wallet auth flow expired`)},burn(){t=!1}}}function HW(e){return String(e.input.relayUrl||e.deps.configs.network.relayer?.url||``).trim()}function UW(e,t){let n=String(t.state.registrationAttemptId||``).trim();if(!n)throw Error(`Google Email OTP registration requires a registration attempt id`);if(!t.state.offer)throw Error(`Google Email OTP registration requires an offer`);let r=t.state.offer,i=AW({configs:e.configs,policy:t.input.ecdsaTargets}),a=MW({onEvent:t.input.onEvent,recoveryCodeBackup:t.input.recoveryCodeBackup}),o=i.length?a:FW({options:a}),s=DW(r).walletId,c={kind:`email_otp`,proofKind:`google_sso_registration`,email:t.state.emailHint,providerSubject:t.state.providerSubject,googleEmailOtpRegistrationAttemptId:n,googleEmailOtpRegistrationOfferId:r.offerId,googleEmailOtpRegistrationCandidateId:r.selectedCandidateId},l={completion:`wallet_session`,wallet:{kind:`provided`,walletId:s},authMethod:c,signerSelection:t.input.signerSelection??Lo({configs:e.configs,options:o,ecdsaChainTargets:i}),options:o},u=t.prewarm.kind===`not_started`?RW(e,l.signerSelection):t.prewarm,d=VW({state:t.state});return{kind:`google_email_otp_wallet_auth_flow_v1`,state:`registration_ready`,flowId:`google-email-otp-registration:${s}:${n}`,requestedMode:t.state.requestedMode,mode:`register`,walletId:s,emailHint:t.state.emailHint,prompt:gW({mode:`register`,emailHint:t.state.emailHint}),expiresAtMs:t.state.expiresAtMs,completeRegistration:async()=>{try{d.ensureActive();let t=await e.registerWallet(l);if(!t.success){let e=Object.assign(Error(t.error||`Wallet registration failed`),{code:t.errorCode});return sW(uW(e),e)}return d.burn(),oW({walletId:s,mode:`register`,session:await LW(e,s),registration:t})}catch(e){return sW(uW(e),e)}},rerollWalletId:async()=>{try{if(d.ensureActive(),!t.state.offer)return sW(`google_verification_failed`,Error(`Google Email OTP registration offer is missing wallet candidates`));let n=EW({offer:t.state.offer,currentWalletId:s});return n?(d.burn(),oW(UW(e,{state:{...t.state,walletId:n.walletId,offer:{...t.state.offer,selectedCandidateId:n.candidateId}},input:t.input,prewarm:u}))):sW(`google_verification_failed`,Error(`Google Email OTP registration offer has no alternate wallet candidate`))}catch(e){return sW(`google_verification_failed`,e)}},cancel:async()=>{d.burn()}}}var WW=class{state=`ready`;constructor(e){this.expiresAtMs=e}begin(){if(this.state!==`ready`)throw Error(`Email unlock flow is no longer available`);if(Date.now()>=this.expiresAtMs)throw this.state=`finished`,Error(`Email unlock flow expired`);this.state=`running`}release(){this.state===`running`&&(this.state=`ready`)}burn(){this.state=`finished`}cancel(){if(this.state===`running`)throw Error(`Email unlock operation is already in progress`);this.burn()}};function GW(e,t){let n=new WW(t.state.expiresAtMs);return{kind:`google_email_otp_wallet_auth_flow_v1`,state:`challenge_sent`,flowId:`google-email-otp-login:${t.state.walletId}:${t.challenge.challengeId}`,requestedMode:t.state.requestedMode,mode:`login`,walletId:t.state.walletId,emailHint:t.challenge.emailHint,prompt:gW({mode:`login`,emailHint:t.challenge.emailHint}),delivery:t.challenge.delivery,expiresAtMs:t.state.expiresAtMs,resend:async()=>{let r=!1;try{n.begin(),r=!0;let i=await OW({deps:e,state:t.state,...t.input.relayUrl?{relayUrl:t.input.relayUrl}:{},...t.input.onEvent?{onEvent:t.input.onEvent}:{}});return n.burn(),oW(GW(e,{state:t.state,challenge:i,input:t.input}))}catch(e){return sW(`email_otp_challenge_failed`,e)}finally{r&&n.release()}},submit:async r=>{let i=!1;try{if(n.begin(),i=!0,Date.now()>=t.challenge.expiresAtMs)return sW(`email_otp_expired`,Error(`Email code expired. Request a new code.`));let a=String(r.otpCode||``).trim();if(!/^\d{6}$/.test(a))return sW(`email_otp_invalid_code`,Error(`Enter the 6-digit code from your email.`));let o=jW({configs:e.configs,policy:t.input.ecdsaTargets}),s=t.challenge.signerSelection.kind===`ed25519_only`?[]:o;if(t.state.linkedEmailOtpSelection?.execution===`authority`){if(!e.loginWithLinkedEmailOtpWallet)throw Error(`Exact linked Email OTP wallet unlock is unavailable`);await e.loginWithLinkedEmailOtpWallet({walletId:String(t.state.walletId),walletAuthMethodId:t.state.linkedEmailOtpSelection.walletAuthMethodId,email:t.state.emailHint,providerSubjectId:t.state.providerSubject,challengeId:t.challenge.challengeId,otpCode:a,relayUrl:HW({deps:e,input:t.input})})}else await PW({deps:e,state:t.state,input:t.input,challenge:t.challenge,otpCode:a,targets:s});n.burn();let c=await IW(e,t.state.walletId);return oW({walletId:t.state.walletId,mode:`login`,session:c})}catch(e){return sW(lW(e),e)}finally{i&&n.release()}},cancel:async()=>{n.cancel()}}}async function KW(e){return await e.challenge.submit({otpCode:e.code})}function qW(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}function JW(){return{emailOtpProofVerificationMs:0,walletUnlockExchangeMs:0,ecdsaMaterialRestoreMs:0,signingSessionSealApplyMs:0,warmCapabilityPersistenceMs:0,activeRuntimeConstructionMs:0,emailHashLookupMs:0,workerUnlockAndSessionBootstrapMs:0,walletStateActivationMs:0,runtimePostconditionMs:0,walletIframeRoundTripMs:0}}function YW(e,t,n){XW(e,t,n)}function XW(e,t,n){let r=Math.max(0,Math.round(n));e[t]+=r,ZW()&&console.info(`[EmailOtpUnlock] timing`,{bucket:t,deltaMs:r,accumulatedMs:e[t]})}function ZW(){return Reflect.get(globalThis,`__SEAMS_EMAIL_OTP_UNLOCK_DIAGNOSTICS`)===!0}function QW(e){if(!ZW())return;let t=Object.entries(e.timings),n=[];for(let[e,r]of t)r>0&&n.push({bucket:e,durationMs:r});n.sort(rG);let r=n.slice(0,5),i=e.error instanceof Error?e.error.message:e.error?String(e.error):``,a={kind:`email_otp_unlock_timing_summary_v1`,status:e.status,mode:e.mode,walletId:e.walletId,...e.chainTarget?{chainTarget:e.chainTarget}:{},totalElapsedMs:Math.max(0,Math.round(qW()-e.startedAtMs)),timings:e.timings,topBuckets:r,...i?{errorMessage:i}:{}};console.info(`[EmailOtpUnlock] timing summary`,a)}function $W(e,t){if(!A(e))throw Error(`[SeamsWeb] ${t} requires a concrete ECDSA chainTarget`);return xn(e)}function eG(e,t){return`email-otp-unlock:${String(e||`unknown-wallet`).trim()||`unknown-wallet`}:${String(t||`active`).trim()||`active`}`}function tG(e,t){try{e?.(qi(t))}catch{}}function nG(e,t){let n=Ft(t.error);tG(e,{...t,phase:n?G.CANCELLED:G.FAILED,status:n?`cancelled`:`failed`,interaction:t.interaction??{kind:n?`otp_input`:`none`,overlay:`hide`},error:{message:t.error.message}})}function rG(e,t){return t.durationMs-e.durationMs}async function iG(e,t){if(e.kind===`device_link`)return`authority`;let n=await K.listPendingWalletRegistrationCommits();for(let e of n)if(e.operation===`near_provisioning`&&e.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&e.walletAuthMethodId===t)return`authority`;return`ordinary`}function aG(e){let t=r(e);if(!t.ok)throw Error(`Email OTP unlock returned an invalid wallet auth method id`);return t.value}function oG(e){let t=e.recovery.verifiedAuthorityProjection.authority,n=gi({kind:`wallet_auth_authority_ref`,walletId:t.walletId,walletAuthMethodId:e.authorization.record.authMethodId,authorityDigest:t.authorityDigestB64u});if(!n)throw Error(`Email OTP unlock returned an invalid authority reference`);return n}function sG(e,t,n){XW(e,t,qW()-n)}function cG(e){return{kind:`email_otp_unlock_active_runtime_state_v1`,inventory:e}}function lG(e){if(e.result.authorization.record.walletId!==e.walletSession.walletId)throw Error(`Email OTP unlock authorization does not match the wallet session`);return{kind:`email_otp_unlock_activation_plan_v1`,mode:`evm_family_ecdsa`,activeAuthorization:e.result.authorization,authorizations:e.result.authorizations,runtimeState:cG(e.runtimeInventory)}}function uG(e){ZW()&&console.info(`[EmailOtpUnlock] activation plan constructed`,{kind:e.kind,mode:e.mode,walletId:e.activeAuthorization.record.walletId,authorityDigest:e.activeAuthorization.record.authorityDigestB64u,walletSessionIds:e.authorizations.map(hG),runtimeTargetCount:e.runtimeState.inventory.ecdsaByTarget.size})}function dG(e,t){let n=t.chainTarget.kind===`tempo`?`Tempo`:`EVM`,r={flowId:t.flowId,walletId:t.walletId,authMethod:`email_otp`,...t.challengeId?{requestId:t.challengeId}:{}};switch(t.progress.code){case`otp.verify.succeeded`:return tG(e,{...r,phase:G.STEP_03_EMAIL_OTP_VERIFY_SUCCEEDED,status:`succeeded`,interaction:{kind:`otp_input`,overlay:`hide`}}),G.STEP_03_EMAIL_OTP_VERIFY_SUCCEEDED;case`signer.ecdsa.bootstrap.started`:return tG(e,{...r,phase:G.STEP_05_SIGNING_SESSION_WARMUP_STARTED,status:`running`,message:`Preparing ${n} signing session`,data:{chainTarget:t.chainTarget}}),G.STEP_05_SIGNING_SESSION_WARMUP_STARTED;case`signer.ecdsa.bootstrap.prepared`:return tG(e,{...r,phase:G.STEP_05_SIGNING_SESSION_WARMUP_STARTED,status:`running`,message:`Coordinating ${n} signing session`,data:{chainTarget:t.chainTarget}}),G.STEP_05_SIGNING_SESSION_WARMUP_STARTED;case`signer.ecdsa.bootstrap.responded`:return tG(e,{...r,phase:G.STEP_05_SIGNING_SESSION_WARMUP_STARTED,status:`running`,message:`Finalizing ${n} signing session`,data:{chainTarget:t.chainTarget}}),G.STEP_05_SIGNING_SESSION_WARMUP_STARTED;case`signer.ecdsa.bootstrap.succeeded`:return tG(e,{...r,phase:G.STEP_05_SIGNING_SESSION_WARMUP_STARTED,status:`running`,message:`Saving ${n} signing session`,data:{chainTarget:t.chainTarget}}),G.STEP_05_SIGNING_SESSION_WARMUP_STARTED;default:return null}}function fG(e){let t=new mG(e);return{requestEmailCode:t.requestEmailCode.bind(t),unlockWithEmailCode:KW,startGoogleSignIn:t.startGoogleSignInDomain.bind(t)}}function pG(e){return{curve:`ecdsa`,chainTarget:e}}var mG=class{constructor(e){this.deps=e}async readOwnerScopedSigningLanes(e){return await this.deps.getContext().signingEngine.readOwnerScopedSigningLanes(e,new Ja)}async requestUnlockChallenge(e){let t=eG(e.walletId);tG(e.onEvent,{flowId:t,walletId:e.walletId,authMethod:`email_otp`,phase:G.STEP_03_EMAIL_OTP_CHALLENGE_STARTED,status:`running`});try{let t=e.walletAuthMethodId;if(!t){let n=await K.resolveSelectedWalletAuthority(String(e.walletId||``).trim());n.kind===`resolved`&&n.authMethod.kind===`email_otp`&&n.authMethod.status===`active`&&String(n.authMethod.walletId)===String(e.walletId||``).trim()&&(t=String(n.authMethod.walletAuthMethodId))}if(!t)throw Error(`Email OTP challenge requires an exact walletAuthMethodId`);let n=await Ys({relayUrl:String(e.relayUrl||this.deps.getContext().configs.network.relayer.url||``).trim(),walletId:String(e.walletId||``).trim(),walletAuthMethodId:t});return tG(e.onEvent,{flowId:eG(e.walletId,n.challengeId),walletId:e.walletId,authMethod:`email_otp`,phase:G.STEP_03_EMAIL_OTP_CHALLENGE_SENT,status:`succeeded`,data:{challengeId:n.challengeId,otpChannel:n.otpChannel}}),n}catch(n){let r=I(n);throw nG(e.onEvent,{flowId:t,walletId:e.walletId,authMethod:`email_otp`,error:r}),r}}async loginWithEmailOtpEcdsaCapabilityDomain(e){let t=e.walletSession.walletId,n=eG(t,e.challengeId),r=$W(e.chainTarget,`Email OTP ECDSA unlock`),i={startedAtMs:qW(),timings:JW()};tG(e.onEvent,{flowId:n,walletId:t,authMethod:`email_otp`,phase:G.STEP_03_EMAIL_OTP_VERIFY_STARTED,status:`running`,interaction:{kind:`otp_input`,overlay:`none`},...e.challengeId?{requestId:e.challengeId}:{}});try{let a=new Set,o=gG.bind(null,a,e.onEvent,{flowId:n,walletId:t,challengeId:e.challengeId,chainTarget:r}),s=_G.bind(null,a,e.onEvent),c=qW(),l=await this.emailOtpEmailHashHex(e.emailOtpAuthorityEmail||``);sG(i.timings,`emailHashLookupMs`,c),c=qW();let u=e.ed25519Selection.kind===`present`?e.ed25519Selection:null,d=await this.deps.getContext().signingEngine.loginWithEmailOtpEcdsaCapabilityInternal({...e,authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:e.walletAuthMethodId},chainTarget:r,emailHashHex:l,...u?{ed25519YaoRecovery:{kind:`requested`,providerSubject:e.providerIdentity.providerSubjectId,signerSlot:u.signerSlot,nearAccountId:u.nearAccountId,expectedOperationalPublicKey:u.operationalPublicKey,expectedThresholdSessionId:u.thresholdSessionId}}:{ed25519YaoRecovery:{kind:`not_requested`}},ecdsaBootstrapAuthorization:{kind:`route_plan_auth`},providerIdentity:{kind:`explicit_provider_user`,provider:e.providerIdentity.provider,providerUserId:e.providerIdentity.providerSubjectId},onProgress:o});await _I({walletId:String(t),walletAuthMethodId:String(e.walletAuthMethodId),projection:d.recovery.verifiedAuthorityProjection});let f;if(u){let t;switch(d.ed25519YaoRecovery.kind){case`capability`:t=await this.deps.getContext().signingEngine.activateEmailOtpEd25519CustodyCapabilityInternal({walletSession:e.walletSession,providerSubject:e.providerIdentity.providerSubjectId,emailHashHex:l,signerSlot:u.signerSlot,expectedOperationalPublicKey:u.operationalPublicKey,expectedThresholdSessionId:u.thresholdSessionId,bootstrap:d.ed25519YaoRecovery.bootstrap,activeClientHandle:d.ed25519YaoRecovery.activeClientHandle,metadata:d.ed25519YaoRecovery.metadata,authority:oG(d)});break;case`cache_absent`:throw Error(`Email OTP wallet custody material is unavailable; recover with a recovery code`);case`not_requested`:throw Error(`Email OTP capability unlock omitted Ed25519 Yao session material`);default:throw Error(`Email OTP capability unlock returned an invalid Ed25519 Yao state`)}f={kind:`near_ed25519_wallet`,signer:t,walletAuthMethodId:aG(e.walletAuthMethodId)}}else{if(d.ed25519YaoRecovery.kind!==`not_requested`)throw Error(`EVM-family ECDSA Email OTP unlock returned unexpected Ed25519 Yao material`);f={kind:`evm_family_ecdsa_wallet`,walletId:t,walletAuthMethodId:aG(e.walletAuthMethodId)}}let p=qW()-c;YW(i.timings,`workerUnlockAndSessionBootstrapMs`,p),YW(i.timings,`emailOtpProofVerificationMs`,d.timings.emailOtpProofVerificationMs),YW(i.timings,`ecdsaMaterialRestoreMs`,d.timings.ecdsaMaterialRestoreMs),YW(i.timings,`signingSessionSealApplyMs`,d.timings.signingSessionSealApplyMs),YW(i.timings,`warmCapabilityPersistenceMs`,d.timings.warmCapabilityPersistenceMs),c=qW(),await bI({signingEngine:this.deps.getContext().signingEngine,nearClient:this.deps.getContext().nearClient},f),sG(i.timings,`walletStateActivationMs`,c),c=qW();let m=await vI({walletId:String(t),walletAuthMethodId:String(e.walletAuthMethodId),providerSubject:e.providerIdentity.providerSubjectId,emailHashHex:l,projection:d.recovery.verifiedAuthorityProjection}),h=await Dy({source:`wallet_unlock`,walletId:t,ownerScope:{auth:{kind:`email_otp`,providerSubjectId:e.providerIdentity.providerSubjectId},ownerAuthority:{walletAuthMethodId:m.walletAuthMethodId,authorityDigest:m.authorityDigest}},requiredTargets:[...u?[{curve:`ed25519`}]:[],...(e.publicationChainTargets??[r]).map(pG)],readOwnerScopedSigningLanes:this.readOwnerScopedSigningLanes.bind(this)});uG(lG({walletSession:e.walletSession,result:d,runtimeInventory:h}));let g=qW()-c;return YW(i.timings,`runtimePostconditionMs`,g),YW(i.timings,`activeRuntimeConstructionMs`,g),QW({status:`succeeded`,mode:`evm_family_ecdsa`,walletId:t,chainTarget:r,startedAtMs:i.startedAtMs,timings:i.timings}),s({flowId:n,walletId:t,authMethod:`email_otp`,phase:G.STEP_03_EMAIL_OTP_VERIFY_SUCCEEDED,status:`succeeded`,interaction:{kind:`otp_input`,overlay:`hide`},...e.challengeId?{requestId:e.challengeId}:{}}),s({flowId:n,walletId:t,authMethod:`email_otp`,phase:G.STEP_05_ECDSA_SIGNING_SESSION_READY,status:`succeeded`,...e.challengeId?{requestId:e.challengeId}:{},data:{chainTarget:r}}),s({flowId:n,walletId:t,authMethod:`email_otp`,phase:G.STEP_07_COMPLETED,status:`succeeded`,...e.challengeId?{requestId:e.challengeId}:{}}),d}catch(a){let o=I(a);throw QW({status:`failed`,mode:`evm_family_ecdsa`,walletId:t,chainTarget:r,startedAtMs:i.startedAtMs,timings:i.timings,error:o}),nG(e.onEvent,{flowId:n,walletId:t,authMethod:`email_otp`,...e.challengeId?{requestId:e.challengeId}:{},error:o}),o}}async loginWithLinkedEmailOtpWalletDomain(e){let t=await ts(ki(e.walletId));if(t){if(t.auth.kind!==`email_otp`||t.walletAuthMethodId!==e.walletAuthMethodId||t.auth.email!==e.email.trim().toLowerCase()||t.auth.providerSubject!==e.providerSubjectId)throw Error(`Pending registration requires its exact email authentication method`);let n=this.deps.getContext(),r=Bp({defaults:n.configs.signing.sessionDefaults,override:void 0});if(r.kind===`disabled`)throw Error(`Pending registration recovery requires an enabled signing session policy`);await rs({relayerUrl:e.relayUrl,sessionPolicy:r,pending:t,exactMethod:{kind:`email_otp`,challengeId:e.challengeId,otpCode:e.otpCode},signingSurface:n.signingEngine,nearContext:n,nearCompletion:`await`,onEvent:void 0}),n.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.walletId,authMethod:`email_otp`}),this.deps.resumePendingAcknowledgements();return}let n=await this.emailOtpEmailHashHex(e.email);await rS({context:this.deps.getContext(),walletIdInput:e.walletId,emailHashHex:n,walletAuthMethodId:e.walletAuthMethodId,providerSubjectId:e.providerSubjectId,challengeId:e.challengeId,otpCode:e.otpCode,relayUrl:e.relayUrl}),this.deps.resumePendingAcknowledgements()}async requestEmailCode(e){return await BW(this.flowDependencies(),e)}async startGoogleSignInDomain(e){return await zW(this.flowDependencies(),e)}flowDependencies(){return{configs:this.deps.getContext().configs,resolveGoogleEmailOtpProvider:this.resolveGoogleEmailOtpProviderDomain.bind(this),requestEmailOtpChallenge:this.requestUnlockChallenge.bind(this),prewarmEmailOtpYao:this.prewarmEmailOtpYaoDomain.bind(this),registerWallet:this.deps.registerWallet,loginWithEmailOtpEcdsaCapability:this.loginWithEmailOtpEcdsaCapabilityDomain.bind(this),loginWithEmailOtpEd25519YaoCapability:this.loginWithEmailOtpEd25519YaoCapabilityDomain.bind(this),resolveLinkedEmailOtpWalletAuth:this.resolveLinkedEmailOtpWalletAuthDomain.bind(this),loginWithLinkedEmailOtpWallet:this.loginWithLinkedEmailOtpWalletDomain.bind(this),getWalletSession:this.getGoogleEmailOtpWalletSessionDomain.bind(this)}}async resolveGoogleEmailOtpProviderDomain(e){return await lc({relayUrl:String(e.relayUrl||this.deps.getContext().configs.network.relayer.url||``).trim(),idToken:e.idToken,accountMode:e.accountMode,...e.loginWalletId?{loginWalletId:e.loginWalletId}:{},projectEnvironmentId:this.deps.getContext().configs.registration.projectEnvironmentId,publishableKey:this.deps.getContext().configs.registration.publishableKey,...e.restartRegistrationOffer===!0?{restartRegistrationOffer:!0}:{}})}async resolveLinkedEmailOtpWalletAuthDomain(e){let t=await ts(ki(e.walletId));if(t)return t.auth.kind!==`email_otp`||t.auth.email!==e.email.trim().toLowerCase()||t.auth.providerSubject!==e.providerSubjectId?{kind:`rejected`,message:`Pending registration requires its exact email authentication method`}:{kind:`selected`,walletAuthMethodId:t.walletAuthMethodId,execution:`authority`};let n=await this.emailOtpEmailHashHex(e.email),r=await Bb({walletIdInput:e.walletId,emailHashHex:n,provider:e.provider,providerSubjectId:e.providerSubjectId});switch(r.kind){case`none`:{let t=await K.listWalletAuthMethodsV2ForWallet(e.walletId),r=[];for(let e of t)e.kind===`email_otp`&&e.status===`active`&&e.emailHashHex.toLowerCase()===n&&r.push(e);let i=r[0];if(r.length===0||!i){let t=await K.listWalletAuthMethodsForWallet(e.walletId),r=[];for(let i of t)i.kind===`email_otp`&&i.status===`active`&&i.emailHashHex.toLowerCase()===n&&bi(i.authority)&&i.authority.factor.provider===e.provider&&i.authority.factor.providerUserId===e.providerSubjectId&&r.push(i);let i=r[0];if(r.length===0||!i)return{kind:`none`};if(r.length!==1)return{kind:`rejected`,message:`Multiple active local Email OTP factors match the verified email`};let a=i.authority;return!a||!bi(a)?{kind:`none`}:{kind:`selected`,walletAuthMethodId:String(a.bindingId),execution:`ordinary`}}if(r.length!==1)return{kind:`rejected`,message:`Multiple active local Email OTP authorities match the verified email`};let a=await K.getWalletAuthority(String(i.walletAuthorityId));return!a||a.state!==`active`||a.walletId!==i.walletId||a.authorityId!==i.walletAuthorityId||a.provenance.kind!==`wallet_registration`&&a.provenance.kind!==`wallet_recovery`?{kind:`none`}:(await Pb({authMethod:i,provider:e.provider,providerSubjectId:e.providerSubjectId}),{kind:`selected`,walletAuthMethodId:String(i.walletAuthMethodId),execution:await iG(a.provenance,i.walletAuthMethodId),keyFamilies:a.signerActivations.keyFamilies})}case`selected`:return{kind:`selected`,walletAuthMethodId:String(r.selection.authMethod.walletAuthMethodId),execution:await iG(r.selection.authority.provenance,r.selection.authMethod.walletAuthMethodId),keyFamilies:r.selection.authority.signerActivations.keyFamilies};case`rejected`:return{kind:`rejected`,message:r.message};default:throw Error(`Linked Email OTP authority resolution is invalid`)}}async prewarmEmailOtpYaoDomain(){await this.deps.getContext().signingEngine.prewarmEmailOtpYao()}async getGoogleEmailOtpWalletSessionDomain(e){return await this.deps.getWalletSession(e)}async loginWithEmailOtpEd25519YaoCapabilityDomain(e){if(e.authoritySelector.kind!==`wallet_auth_method`)throw Error(`Email OTP Ed25519 unlock requires an exact wallet auth method`);let t=await this.emailOtpEmailHashHex(e.emailOtpAuthorityEmail),n=await this.deps.getContext().signingEngine.loginWithEmailOtpWalletCustodyEd25519Internal({...e,emailHashHex:t});await bI({signingEngine:this.deps.getContext().signingEngine,nearClient:this.deps.getContext().nearClient},{kind:`near_ed25519_wallet`,signer:n,walletAuthMethodId:aG(e.authoritySelector.walletAuthMethodId)})}async emailOtpEmailHashHex(e){let t=String(e||``).trim().toLowerCase();if(!t)throw Error(`[SeamsWeb][email-otp] verified email is required for auth-method hash`);return j(t)}};function hG(e){return e.operationCredential.walletSessionId}function gG(e,t,n,r){let i=dG(t,{flowId:n.flowId,walletId:n.walletId,challengeId:n.challengeId,chainTarget:n.chainTarget,progress:r});i&&e.add(i)}function _G(e,t,n){e.has(n.phase)||tG(t,n)}function vG(e){let t=o(e.rpId);if(!t.ok)throw Error(t.error.message);let n=a(e.credentialIdB64u);if(!n.ok)throw Error(n.error.message);let r=String(e.credentialPublicKeyB64u||``).trim();if(!r)throw Error(`Wallet add-passkey finalize omitted credential public key`);if(F(r).byteLength===0)throw Error(`Wallet add-passkey finalize returned an empty credential public key`);if(!Number.isSafeInteger(e.counter)||e.counter<0)throw Error(`Wallet add-passkey finalize returned an invalid credential counter`);let i=Date.now();return{version:`wallet_auth_method_v1`,kind:`passkey`,status:`active`,localStatus:`synced`,walletId:e.walletId,rpId:t.value,credentialIdB64u:n.value,credentialPublicKeyB64u:r,counter:e.counter,createdAtMs:i,updatedAtMs:i}}async function yG(e){await K.upsertWalletAuthMethod(vG(e))}async function bG(e){await yG(e);let t=r(e.walletAuthMethodId),n=s(e.walletAuthorityId);if(!t.ok||!n.ok)throw Error(`added passkey identity is invalid`);await SG({walletId:e.walletId,walletAuthMethodId:t.value,walletAuthorityId:n.value,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,credentialPublicKeyB64u:e.credentialPublicKeyB64u,counter:e.counter});let i=new Date().toISOString();await K.upsertProfileAuthenticator({profileId:String(e.walletId),signerSlot:e.signerSlot,credentialId:e.credentialIdB64u,credentialPublicKey:F(e.credentialPublicKeyB64u),registered:i,syncedAt:i})}function xG(e){let t=o(e.rpId),n=a(e.credentialIdB64u),i=r(e.walletAuthMethodId),c=s(e.walletAuthorityId),l=String(e.credentialPublicKeyB64u||``).trim();if(!t.ok||!n.ok||!i.ok||!c.ok)throw Error(`Synced passkey auth-method identity is invalid`);if(!l||F(l).byteLength===0)throw Error(`Synced passkey auth method omitted credential public key`);if(!Number.isSafeInteger(e.counter)||e.counter<0)throw Error(`Synced passkey auth method returned an invalid credential counter`);let u=Date.now(),d=Ei({version:`wallet_auth_method_v2`,walletAuthMethodId:i.value,walletId:e.walletId,walletAuthorityId:c.value,kind:`passkey`,status:`active`,rpId:t.value,credentialIdB64u:n.value,credentialPublicKeyB64u:l,counter:e.counter,createdAtMs:u,updatedAtMs:u,activatedAtMs:u});if(d.kind!==`passkey`||d.status!==`active`)throw Error(`Synced passkey auth method branch is invalid`);return d}async function SG(e){await K.upsertWalletAuthMethodV2(xG(e))}function CG(e){if(!e||!(e instanceof PublicKeyCredential))throw Error(`Passkey registration did not return a public-key credential`);return e}function wG(e){return{challenge:F(e.challengeB64u),rp:{id:e.rpId,name:e.rpId},user:{id:F(e.user.idB64u),name:e.user.name,displayName:e.user.displayName},pubKeyCredParams:e.pubKeyCredParams.map(e=>({type:e.type,alg:e.alg})),authenticatorSelection:e.authenticatorSelection,timeout:e.timeoutMs,attestation:e.attestation,excludeCredentials:e.excludeCredentials.map(e=>({type:e.type,id:F(e.id)})),extensions:{prf:{eval:{first:F(e.extensions.prf.eval.firstB64u),second:F(e.extensions.prf.eval.secondB64u)}}}}}function TG(e){if(e.kind!==`unlocked_capability`)throw Error(`wallet custody reseal source is not an unlocked capability`);return e.capability}function EG(e){let t=a(e);if(!t.ok)throw Error(`Passkey registration credential id is invalid: ${t.error.message}`);return t.value}async function DG(e){let t=e.registrationCredential?e.registrationCredential:xc({credential:CG(await navigator.credentials.create({publicKey:wG(e.registration)})),firstPrfOutput:!0,secondPrfOutput:!1}),n=Sc(t);if(!n)throw Error(`New passkey did not return PRF.first`);let r=EG(t.rawId||t.id),i=T(ve(`wallet-custody-envelope`,24,`wallet custody envelope ids`));if(!i.ok)throw Error(i.error.message);let a=dn({rpId:e.registration.rpId,credentialIdB64u:r}),o=pn(e.walletAuthMethodId),s=gn({walletId:e.existingEnvelope.walletId,envelopeId:i.value,factor:a,envelopeRevision:Te(1),binding:e.existingEnvelope.binding,ownership:o}),c=F(n),l=e.sealSource.kind===`factor_secret`?e.sealSource.existingFactorSecret.slice():null,u;try{u=Ga(l===null?await e.worker.requestOperation({kind:`walletCustodyCeremony`,request:{type:`resealWalletCustodyFromUnlockedCapability`,payload:{capability:TG(e.sealSource),replacementEnvelopeBindingJson:s,replacementFactorSecret:c.buffer},transfer:[c.buffer]}}):await e.worker.requestOperation({kind:`walletCustodyCeremony`,request:{type:`linkWalletCustodyPasskey`,payload:{existingEnvelope:e.existingEnvelope,existingFactorSecret:l.buffer,replacementEnvelopeBindingJson:s,replacementFactorSecret:c.buffer},transfer:[l.buffer,c.buffer]}}))}finally{l&&l.byteLength>0&&l.fill(0),c.byteLength>0&&c.fill(0)}let d=(e.nowMs??Date.now)();return{registration:t,custodyEnvelope:vn(fn({envelopeId:i.value,walletId:e.existingEnvelope.walletId,ownership:o,binding:e.existingEnvelope.binding,factor:a,envelopeRevision:Te(1),nonceB64u:u.nonceB64u,sealedCustodySecretB64u:u.sealedCustodySecretB64u,ciphertextDigestB64u:u.ciphertextDigestB64u,aadHashB64u:u.aadHashB64u,lifecycle:{state:`active`,activatedAtMs:d},createdAtMs:d,updatedAtMs:d}))}}async function OG(e){let t=await uo({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodIntentGrant:e.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.addAuthMethodIntentDigestB64u,intent:e.intent,auth:e.auth,authority:{kind:`passkey`}});if(!t.custodyEnvelope||!t.registration)throw Error(`Passkey add-auth-method start omitted custody envelope or registration options`);let n=await DG({registration:t.registration,walletAuthMethodId:e.walletAuthMethodId,existingEnvelope:t.custodyEnvelope,sealSource:e.sealSource,worker:e.worker,...e.createRegistrationCredential?{registrationCredential:await e.createRegistrationCredential(t.registration)}:{},nowMs:e.nowMs});return{finalized:await ho({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodCeremonyId:t.addAuthMethodCeremonyId,webauthnRegistration:n.registration,custodyEnvelope:n.custodyEnvelope})}}async function kG(e){let t=await K.resolveSelectedWalletAuthority(String(e));if(t.kind!==`resolved`)return{kind:`unavailable`,reason:`selected wallet authority is ${t.kind}`};if(t.authMethod.status!==`active`)return{kind:`unavailable`,reason:`selected auth method is not active`};if(t.authority.state!==`active`)return{kind:`unavailable`,reason:`selected wallet authority is not active`};if(t.selection.lockState!==`unlocked`||t.selection.walletId!==e||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.walletId!==e||t.authMethod.walletAuthorityId!==t.authority.authorityId||t.authority.walletId!==e)return{kind:`unavailable`,reason:`selected wallet authority identity is invalid`};let n;if(t.authMethod.kind===`voiceid`){let r=await K.listWalletAuthMethodsV2ForWallet(e),i=AG(e,t.authority.authorityId,r);if(!i)return{kind:`unavailable`,reason:`this authority needs an active passkey or Email OTP method to confirm the addition`};n=i}else n=t.authMethod;return{kind:`resolved`,sourceAuthMethod:n,source:{walletAuthorityId:n.walletAuthorityId,walletAuthMethodId:n.walletAuthMethodId,authorityDigestB64u:String(t.authority.authorityDigestB64u),revocationEpoch:t.authority.revocationEpoch}}}function AG(e,t,n){let r=null;for(let i of n)if(!(i.status!==`active`||i.walletId!==e||i.walletAuthorityId!==t))switch(i.kind){case`passkey`:return i;case`email_otp`:r=i;break;case`voiceid`:break;default:return jG(i)}return r}function jG(e){throw Error(`Unsupported confirmation method: ${String(e)}`)}function MG(e){return[{id:e.credentialIdB64u,type:`public-key`,transports:[]}]}async function NG(e){if(e.finalized.walletId!==e.walletId||e.finalized.rpId!==e.rpId||e.finalized.authMethod.kind!==`passkey`||e.finalized.authMethod.status!==`active`)throw Error(`Wallet add-passkey finalize returned a mismatched auth method`);return await yG({walletId:e.finalized.walletId,rpId:e.finalized.rpId,credentialIdB64u:e.finalized.authMethod.credentialIdB64u,credentialPublicKeyB64u:e.finalized.authMethod.credentialPublicKeyB64u,counter:e.finalized.authMethod.counter}),{ok:!0,walletId:e.finalized.walletId,rpId:e.finalized.rpId,walletAuthMethodId:e.walletAuthMethodId,authMethod:{kind:`passkey`,status:`active`}}}function PG(e){let t=e.signingEngine.getSignerWorkerContext();return{requestOperation:Za.bind(void 0,t)}}async function FG(e){let t=String(e.context.configs.network.relayer.url||``).trim();if(!t)throw Error(`registration.addPasskey requires relayer.url`);let n=hc(e.context.configs);if(!n)throw Error(`registration.addPasskey requires registration.publishableKey and registration.projectEnvironmentId`);let r=await kG(e.walletId);if(r.kind!==`resolved`)throw Error(`Wallet add-passkey requires a selected active source: ${r.reason}`);let i=await yo({relayerUrl:t,walletId:e.walletId,request:{walletId:e.walletId,rpId:e.rpId,authMethod:{kind:`passkey`,rpId:e.rpId},caller:{caller:`same_device_addition`,source:r.source}},auth:{publishableKey:n.publishableKey,environmentId:n.projectEnvironmentId}});if(await hn(i.intent)!==i.addAuthMethodIntentDigestB64u)throw Error(`Add-auth-method intent digest mismatch`);if(i.intent.walletId!==e.walletId||i.intent.authMethod.kind!==`passkey`||i.intent.authMethod.rpId!==e.rpId)throw Error(`Add-auth-method intent identity changed`);let a=await K.getProfile(String(e.walletId));if(!a||!Number.isSafeInteger(a.defaultSignerSlot)||a.defaultSignerSlot<1)throw Error(`Wallet add-passkey requires an initialized wallet profile`);if(r.sourceAuthMethod.kind===`email_otp`)return await IG({context:e.context,walletId:e.walletId,rpId:e.rpId,relayerUrl:t,profile:a,sourceWalletAuthorityId:r.source.walletAuthorityId,sourceWalletAuthMethodId:r.source.walletAuthMethodId,intentResponse:i,...e.options?{options:e.options}:{}});let o=MG(r.sourceAuthMethod),s=await e.context.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(e.walletId),challengeB64u:i.addAuthMethodIntentDigestB64u,allowCredentials:o,includeSecondPrfOutput:!1}),c=Tl(s);if(!c||!o.some(e=>e.id===c))throw Error(`Wallet add-passkey selected a credential outside the authorized wallet`);let l=F(El(s,`Wallet add-passkey custody linking`));try{let n=await OG({relayerUrl:t,walletId:e.walletId,addAuthMethodIntentGrant:i.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:i.addAuthMethodIntentDigestB64u,intent:i.intent,auth:{kind:`webauthn_assertion`,rpId:e.rpId,credential:Tc(s),expectedChallengeDigestB64u:i.addAuthMethodIntentDigestB64u},sealSource:{kind:`factor_secret`,existingFactorSecret:l},walletAuthMethodId:i.intent.targetWalletAuthMethodId,worker:PG(e.context),createRegistrationCredential:async t=>{let n=await e.context.signingEngine.requestRegistrationCredentialConfirmation({walletId:String(e.walletId),signerSlot:a.defaultSignerSlot,confirmerText:e.options?.confirmerText,confirmationConfigOverride:e.options?.confirmationConfig,registrationOptions:t});if(!n.confirmed)throw Error(`Wallet add-passkey registration was cancelled`);return n.credential}});return await NG({walletId:e.walletId,rpId:e.rpId,walletAuthMethodId:i.intent.targetWalletAuthMethodId,finalized:n.finalized})}finally{l.fill(0)}}async function IG(e){let t=Xa(String(e.walletId));if(!t)throw Error(`Wallet add-passkey from an Email OTP source requires an unlocked wallet`);let n=async()=>await po({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodIntentGrant:e.intentResponse.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.intentResponse.addAuthMethodIntentDigestB64u}),r=await n(),i=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:`add_passkey`,walletId:String(e.walletId),emailAddress:r.emailHint||`your email`,challengeId:r.challengeId,...r.emailHint?{emailHint:r.emailHint}:{},confirmerText:{title:`Enter email code to add a passkey`,body:`This one-time code confirms you can add a new passkey to this wallet.`},...e.options?.confirmationConfig?{confirmationConfigOverride:e.options.confirmationConfig}:{},onResend:n}),a=(await OG({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodIntentGrant:e.intentResponse.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.intentResponse.addAuthMethodIntentDigestB64u,intent:e.intentResponse.intent,auth:{kind:`email_otp`,challengeId:i.challengeId,otpCode:i.otpCode,expectedChallengeDigestB64u:e.intentResponse.addAuthMethodIntentDigestB64u},sealSource:{kind:`unlocked_capability`,capability:t},walletAuthMethodId:e.intentResponse.intent.targetWalletAuthMethodId,worker:PG(e.context),createRegistrationCredential:async t=>{let n=await e.context.signingEngine.requestRegistrationCredentialConfirmation({walletId:String(e.walletId),signerSlot:e.profile.defaultSignerSlot,confirmerText:e.options?.confirmerText,confirmationConfigOverride:e.options?.confirmationConfig,registrationOptions:t});if(!n.confirmed)throw Error(`Wallet add-passkey registration was cancelled`);return n.credential}})).finalized;if(a.walletId!==e.walletId||a.authMethod.kind!==`passkey`||a.authMethod.status!==`active`)throw Error(`Wallet add-passkey finalize returned a mismatched auth method`);return await bG({walletId:e.walletId,walletAuthMethodId:e.intentResponse.intent.targetWalletAuthMethodId,walletAuthorityId:e.sourceWalletAuthorityId,rpId:String(e.rpId),credentialIdB64u:a.authMethod.credentialIdB64u,credentialPublicKeyB64u:a.authMethod.credentialPublicKeyB64u,counter:a.authMethod.counter,signerSlot:e.profile.defaultSignerSlot,credential:{id:a.authMethod.credentialIdB64u,rawId:a.authMethod.credentialIdB64u}}),await ko({walletId:e.walletId,walletAuthorityId:e.sourceWalletAuthorityId,sourceWalletAuthMethodId:e.sourceWalletAuthMethodId,targetAuthority:await U({authority:a.authority})}),{ok:!0,walletId:e.walletId,rpId:String(e.rpId),walletAuthMethodId:e.intentResponse.intent.targetWalletAuthMethodId,authMethod:{kind:`passkey`,status:`active`}}}async function LG(e){let t=ki(String(e.walletId||``).trim()),n=o(String(e.rpId||``).trim());if(!n.ok)throw Error(n.error.message);try{let r=await FG({context:e.context,walletId:t,rpId:n.value,options:e.options});return await e.options?.afterCall?.(!0,r),r}catch(t){let n=I(t);try{e.options?.onError?.(n)}finally{await e.options?.afterCall?.(!1)}throw n}}async function RG(e){let t=await uo({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodIntentGrant:e.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:e.addAuthMethodIntentDigestB64u,intent:e.intent,auth:e.auth,authority:e.authority});if(!t.custodyEnvelope)throw Error(`Email OTP add-auth-method start omitted the source custody envelope`);let n=t.custodyEnvelope,r=crypto.getRandomValues(new Uint8Array(32)),i=r.slice(),a;try{a=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:e.relayerUrl,walletId:V(String(e.walletId)),userId:e.providerSubject,clientSecret32:r})}catch(e){throw i.fill(0),e}finally{r.fill(0)}let o=T(ve(`wallet-custody-envelope`,24,`wallet custody envelope ids`));if(!o.ok)throw Error(o.error.message);let s=mn({enrollmentId:a.enrollmentId,enrollmentSealKeyVersion:a.enrollmentSealKeyVersion}),c=pn(e.walletAuthMethodId),l=Te(1),u=gn({walletId:n.walletId,envelopeId:o.value,factor:s,envelopeRevision:l,binding:n.binding,ownership:c}),d=e.existingFactorSecret.slice(),f;try{f=Ga(await e.worker.requestOperation({kind:`walletCustodyCeremony`,request:{type:`linkWalletCustodyPasskey`,payload:{existingEnvelope:n,existingFactorSecret:d.buffer,replacementEnvelopeBindingJson:u,replacementFactorSecret:i.buffer},transfer:[d.buffer,i.buffer]}}))}finally{d.byteLength>0&&d.fill(0),i.byteLength>0&&i.fill(0)}let p=(e.nowMs??Date.now)(),m=vn(fn({envelopeId:o.value,walletId:n.walletId,ownership:c,binding:n.binding,factor:s,envelopeRevision:l,nonceB64u:f.nonceB64u,sealedCustodySecretB64u:f.sealedCustodySecretB64u,ciphertextDigestB64u:f.ciphertextDigestB64u,aadHashB64u:f.aadHashB64u,lifecycle:{state:`active`,activatedAtMs:p},createdAtMs:p,updatedAtMs:p}));return{finalized:await ho({relayerUrl:e.relayerUrl,walletId:e.walletId,addAuthMethodCeremonyId:t.addAuthMethodCeremonyId,custodyEnvelope:m,emailOtpTarget:{kind:`new_enrollment`,enrollment:a.emailOtpEnrollment}})}}async function zG(e){if(!bi(e.authority))throw Error(`Wallet add-email-code finalize returned a non-Email authority`);let t=r(e.walletAuthMethodId);if(!t.ok)throw Error(t.error.message);let n=s(e.walletAuthorityId);if(!n.ok)throw Error(n.error.message);let i=String(e.authority.verifier.emailHashHex||``).trim();if(!i)throw Error(`Wallet add-email-code finalize returned no verified email digest`);let a=String(e.authority.factor.providerUserId||``).trim();if(!a)throw Error(`Wallet add-email-code finalize returned no provider identity`);let o=u(e.emailAddress);if(!o.ok)throw Error(o.error.message);let c=Date.now();await K.upsertWalletAuthMethod({version:`wallet_auth_method_v1`,kind:`email_otp`,status:`active`,localStatus:`synced`,walletId:e.walletId,emailHashHex:i,registrationAuthorityId:a,authority:e.authority,createdAtMs:c,updatedAtMs:c}),await K.upsertWalletAuthMethodV2(Ei({version:`wallet_auth_method_v2`,walletAuthMethodId:t.value,walletId:e.walletId,walletAuthorityId:n.value,kind:`email_otp`,status:`active`,emailHashHex:i,registrationAuthorityId:a,createdAtMs:c,updatedAtMs:c,activatedAtMs:c}));let l=await K.retainVerifiedEmailOtpLocalPresentation({walletId:e.walletId,walletAuthMethodId:t.value,emailAddress:o.value});if(l.kind!==`retained`)throw Error(`Verified Email OTP presentation was not retained: ${l.reason}`)}function BG(e){let t=e.signingEngine.getSignerWorkerContext();return{requestOperation:Za.bind(void 0,t)}}function VG(e){return e}function HG(e){let t=String(e||``).trim().toLowerCase();if(!t||!t.includes(`@`))throw Error(`registration.addEmail requires an email address`);return t}async function UG(e){let t=String(e.context.configs.network.relayer.url||``).trim();if(!t)throw Error(`registration.addEmail requires relayer.url`);let n=hc(e.context.configs);if(!n)throw Error(`registration.addEmail requires registration.publishableKey and registration.projectEnvironmentId`);let r=HG(e.emailAddress),i=VG(r),a=o(String(e.context.signingEngine.getRpId()||``).trim());if(!a.ok)throw Error(`registration.addEmail ${a.error.message}`);let s=a.value,c=await kG(e.walletId);if(c.kind!==`resolved`)throw Error(`Wallet add-email-code requires a selected active source: ${c.reason}`);if(c.sourceAuthMethod.kind!==`passkey`)throw Error(`Wallet add-email-code requires a selected active passkey source`);let l=await yo({relayerUrl:t,walletId:e.walletId,request:{walletId:e.walletId,rpId:String(s),authMethod:{kind:`email_otp`,email:r},caller:{caller:`same_device_addition`,source:c.source}},auth:{publishableKey:n.publishableKey,environmentId:n.projectEnvironmentId}});if(await hn(l.intent)!==l.addAuthMethodIntentDigestB64u)throw Error(`Add-auth-method intent digest mismatch`);if(l.intent.walletId!==e.walletId||l.intent.authMethod.kind!==`email_otp`||l.intent.authMethod.email!==r)throw Error(`Add-auth-method intent identity changed`);let u=await K.getProfile(String(e.walletId));if(!u||!Number.isSafeInteger(u.defaultSignerSlot)||u.defaultSignerSlot<1)throw Error(`Wallet add-email-code requires an initialized wallet profile`);let d=MG(c.sourceAuthMethod),f=await e.context.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(e.walletId),challengeB64u:l.addAuthMethodIntentDigestB64u,allowCredentials:d,includeSecondPrfOutput:!1}),p=Tl(f);if(!p||!d.some(e=>e.id===p))throw Error(`Wallet add-email-code selected a credential outside the authorized wallet`);let m=El(f,`Wallet add-email-code custody linking`),h=async()=>await po({relayerUrl:t,walletId:e.walletId,addAuthMethodIntentGrant:l.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:l.addAuthMethodIntentDigestB64u}),g=await h(),_=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:`add_email_code`,walletId:String(e.walletId),emailAddress:r,challengeId:g.challengeId,...g.emailHint?{emailHint:g.emailHint}:{},...e.options?.confirmerText?{confirmerText:e.options.confirmerText}:{},...e.options?.confirmationConfig?{confirmationConfigOverride:e.options.confirmationConfig}:{},onResend:h}),v=await Ps({authMethod:{kind:`email_otp`,proofKind:`otp_challenge`,email:r,providerSubject:i,otpCode:_.otpCode,challengeId:_.challengeId},relayUrl:t,walletId:String(e.walletId),registrationIntentDigestB64u:l.addAuthMethodIntentDigestB64u}),y=F(m);try{let n=await RG({context:e.context,relayerUrl:t,walletId:e.walletId,addAuthMethodIntentGrant:l.addAuthMethodIntentGrant,addAuthMethodIntentDigestB64u:l.addAuthMethodIntentDigestB64u,intent:l.intent,auth:{kind:`webauthn_assertion`,rpId:s,credential:Tc(f),expectedChallengeDigestB64u:l.addAuthMethodIntentDigestB64u},authority:{kind:`email_otp`,emailOtpRegistrationProof:v.proof},existingFactorSecret:y,walletAuthMethodId:l.intent.targetWalletAuthMethodId,providerSubject:i,worker:BG(e.context)});if(n.finalized.walletId!==e.walletId||n.finalized.authMethod.kind!==`email_otp`||n.finalized.authMethod.status!==`active`)throw Error(`Wallet add-email-code finalize returned a mismatched auth method`);return await zG({walletId:e.walletId,walletAuthMethodId:l.intent.targetWalletAuthMethodId,walletAuthorityId:c.source.walletAuthorityId,emailAddress:r,authority:n.finalized.authority}),await ko({walletId:e.walletId,walletAuthorityId:c.source.walletAuthorityId,sourceWalletAuthMethodId:c.source.walletAuthMethodId,targetAuthority:await U({authority:n.finalized.authority})}),{ok:!0,walletId:e.walletId,emailAddress:r,walletAuthMethodId:l.intent.targetWalletAuthMethodId,authMethod:{kind:`email_otp`,status:`active`}}}finally{y.fill(0)}}async function WG(e){let t=ki(String(e.walletId||``).trim());try{let n=await UG({context:e.context,walletId:t,emailAddress:e.emailAddress,options:e.options});return await e.options?.afterCall?.(!0,n),n}catch(t){let n=I(t);try{e.options?.onError?.(n)}finally{await e.options?.afterCall?.(!1)}throw n}}function GG(e,t){return{registerWallet:KG.bind(null,e),getNearAccountState:qG.bind(null,e),addSigner:JG.bind(null,e),addPasskey:YG.bind(null,e),activateAuthMethod:XG.bind(null,e),getAuthMethodAvailability:$G.bind(null,e),setAuthMethodEnabled:eK.bind(null,e,t),removeAuthMethod:ZG.bind(null,e),addEmail:QG.bind(null,e)}}async function KG(e,t){let n=e();return await As({context:n,completion:t.completion,authMethod:t.authMethod,wallet:t.wallet,signerSelection:t.signerSelection,options:t.options||{},authenticatorOptions:va(n.configs.webauthn.authenticatorOptions)})}async function qG(e,t){let n=V(t.walletId);return Fo(n)||await e().signingEngine.getWalletNearProvisioningState(n)}async function JG(e,t){return await sc({context:e(),walletId:t.walletId,rpId:t.rpId,signerSelection:t.signerSelection,options:t.options||{}})}async function YG(e,t){return await LG({context:e(),walletId:t.walletId,rpId:t.rpId,options:t.options})}async function XG(e,t){let n=e();return await(await cp(n.configs.authMethods,t.method)).activate({context:n,walletId:V(t.walletId)})}async function ZG(e,t){let n=await Hz({context:e(),walletId:t.walletId,walletAuthMethodId:t.walletAuthMethodId});return n.authMethod.kind===`voiceid`&&await Wa(n.walletId,n.walletAuthMethodId),n}async function QG(e,t){return await WG({context:e(),walletId:t.walletId,emailAddress:t.emailAddress,options:t.options})}async function $G(e,t){if(!pe(e().configs.authMethods,t.method))throw Error(`Enable the authentication plugin in the SDK first.`);return Ha(V(t.walletId))}async function eK(e,t,n){if(typeof n.enabled!=`boolean`)throw Error(`Authentication method availability must be a boolean.`);let r=V(n.walletId),i=await $G(e,n);if(i.kind===`not_enrolled`)throw Error(`Enroll VoiceID before enabling it.`);let a=await t.getSession(r);if(a.authentication.kind!==`authenticated`||a.authentication.walletId!==r)throw Error(`Unlock this wallet before managing VoiceID.`);if(n.enabled&&a.authentication.authMethod===`voiceid`)throw Error(`Unlock with a passkey or Email OTP before enabling VoiceID.`);if(!n.enabled&&!await Ua(r,i.walletAuthMethodId))throw Error(`Add another authentication method before turning off VoiceID.`);return await Ba(r,i.walletAuthMethodId,n.enabled),!n.enabled&&a.authentication.authMethod===`voiceid`&&await t.lock(),n.enabled?{kind:`enabled`,walletAuthMethodId:i.walletAuthMethodId}:{kind:`disabled`,walletAuthMethodId:i.walletAuthMethodId}}async function tK(e){let{context:t,pending:n,options:r}=e,i=String(n.walletId);js(r?.onEvent,i,{phase:G.STEP_01_STARTED,status:`started`,authMethod:`passkey`});try{if(n.auth.kind!==`passkey`)throw Error(`Pending registration requires its founding email authentication method`);let e=r?.unlockSelection?.mode===`ed25519_only`||r?.unlockSelection?.mode===`ed25519_and_ecdsa`;if(e&&n.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`wallet unlock is missing the requested capability subject`);let a=Bp({defaults:t.configs.signing.sessionDefaults,override:r?.signingSession});if(a.kind===`disabled`)throw Error(`Pending registration recovery requires an enabled signing session policy`);let o=await rs({relayerUrl:t.configs.network.relayer.url,sessionPolicy:a,pending:n,exactMethod:{kind:`passkey`},signingSurface:t.signingEngine,nearContext:t,nearCompletion:e?`await`:`background`,onEvent:r?.onEvent}),s=await nK({context:t,walletId:n.walletId,requireNear:e,signingSession:o.signingSession});return js(r?.onEvent,i,{phase:G.STEP_06_SESSION_READY,status:`succeeded`,authMethod:`passkey`}),await oc({context:t,authMethod:`passkey`,unlockSubjectId:i,loginResult:s,onEvent:r?.onEvent,afterCall:r?.afterCall})}catch(e){let t=I(e);return await ec({unlockSubjectId:i,message:t.message,error:t,cancelled:Ft(t),onEvent:r?.onEvent,onError:r?.onError,afterCall:r?.afterCall})}}async function nK(e){if(!e.requireNear)return{success:!0,kind:`ecdsa_wallet_unlocked`,walletId:e.walletId,signingSession:e.signingSession};let t=Fo(e.walletId);if(t?.status!==`near_ready`)throw Error(t?.status===`near_failed_retryable`?t.error:`Pending NEAR registration did not establish the requested account`);let n=await qS(e.context,e.walletId,new Ja);if(n.appIdentity.kind!==`resolved`||!n.appIdentity.nearAccountId||n.appIdentity.nearAccountId!==t.nearAccountId)throw Error(`Pending NEAR registration did not establish the requested account`);return{success:!0,kind:`near_wallet_unlocked`,walletId:e.walletId,nearAccountId:n.appIdentity.nearAccountId,loggedInNearAccountId:n.appIdentity.nearAccountId,operationalPublicKey:n.appIdentity.nearOperationalPublicKey,signingSession:e.signingSession}}var rK=class extends Error{constructor(e){super(e===`expired`?`Owner approval expired`:`Owner approval was cancelled`),this.code=e,this.name=`ExternalOwnerApprovalError`}},iK=class{state=`reviewing`;surface=null;controller=new AbortController;cancelBound=this.cancel.bind(this);expireBound=this.expire.bind(this);constructor(e,t,n,r){this.input=e,this.appearance=t,this.measurement=n,this.rpId=r}assertCurrent(){if(this.input.assertCurrent(),this.input.challenge.expiresAtMs<=Date.now()&&this.expire(),this.state===`expired`)throw new rK(`expired`);if(this.input.signal.aborted||this.controller.signal.aborted||this.state===`cancelled`)throw this.cancel(),new rK(`cancelled`)}cancel(){this.state===`cancelled`||this.state===`expired`||this.state===`approved`||(this.state=`cancelled`,this.controller.abort(),this.surface?.close(!1))}expire(){this.state===`cancelled`||this.state===`expired`||this.state===`approved`||(this.state=`expired`,this.controller.abort(),this.surface?.close(!1))}async approve(){this.assertCurrent();let e=this.input.challenge,t=setTimeout(this.expireBound,Math.max(0,e.expiresAtMs-Date.now()));this.input.signal.addEventListener(`abort`,this.cancelBound,{once:!0});let n;try{if(this.measurement.kind!==`wallet_iframe`)throw Error(`Owner approval requires the Wallet origin`);let{mountConfirmUI:t}=await import(`./confirm-ui-DWFcGTsT.js`).then(e=>e.n);this.assertCurrent(),this.surface=await t({ctx:{surfaceMeasurementBinding:this.measurement},summary:{title:e.kind===`associate`?`Connect this app to your wallet?`:`Remove this app connection?`,body:[`Application: ${e.identity.issuer}`,`Account: ${JSON.stringify(e.identity.subject)}`,`Wallet: ${e.walletId}`,``,e.kind===`associate`?`Allow this account to view wallet settings. Signing still requires your confirmation.`:`Remove settings access for this account.`].join(`
2
+ `)},securityContext:{rpId:this.rpId},appearance:this.appearance,uiMode:`modal`}),this.surface.element.dataset.seamsExternalOwnerApproval=e.kind,this.surface.update({confirmText:e.kind===`associate`?`Connect app`:`Remove connection`,cancelText:`Cancel`}),n=this.surface.onCancel?.(this.cancelBound),(await this.surface.takeDecision()).kind!==`confirmed`&&this.cancel(),this.assertCurrent(),this.state=`collecting_proof`,this.surface.update({preparing:!0});let r=await new Uf(this.rpId).getAuthenticationCredentialsSerializedForChallengeB64u({subjectId:e.walletId,challengeB64u:e.challengeB64u,includeSecondPrfOutput:!1,cancellation:{kind:`abort_signal`,signal:this.controller.signal}});this.assertCurrent();let i=Tl(r);if(!i)throw Error(`Owner approval did not receive a passkey credential`);return this.state=`approved`,{kind:`passkey`,walletId:e.walletId,rpId:this.rpId,credentialIdB64u:i,challenge_digest:e.challengeB64u,webauthn_authentication:Tc(r)}}catch(e){throw this.state===`expired`?new rK(`expired`):this.controller.signal.aborted||e instanceof DOMException&&e.name===`NotAllowedError`?new rK(`cancelled`):e}finally{clearTimeout(t),this.input.signal.removeEventListener(`abort`,this.cancelBound),n?.(),this.surface?.close(!1),this.surface=null,this.controller.abort()}}};async function aK(e,t){let n=e();return new iK(t,n.configs.ui.appearance,n.signingEngine.getWalletIframeSurfaceMeasurementBinding(),n.signingEngine.getRpId()).approve()}function oK(e){switch(e.kind){case`owner_operation`:return e.connection;case`prepared`:return{kind:`empty`};case`empty`:case`restoring`:case`authenticated`:return e;default:return sK(e)}}function sK(e){throw Error(`Unsupported external authentication state: ${String(e)}`)}var cK=class{state={kind:`empty`};generation=0;constructor(e,t,n,r){this.configs=e,this.lockOwner=t,this.approveOwner=n,this.parentOrigin=r,this.restore()}storageKey(){return`seams.external-auth:${this.parentOrigin}:${this.configs.network.relayer.url}:${this.configs.registration.projectEnvironmentId}`}restore(){try{let e=sessionStorage.getItem(this.storageKey());if(!e)return;let t=E(JSON.parse(e),`external session`),n=_(t.walletId);if(!n.ok)throw Error(`Invalid wallet`);this.state={kind:`restoring`,attempt:{walletId:n.value,attemptId:D(t.attemptId,`attemptId`),binding:D(t.binding,`binding`),sessionToken:D(t.sessionToken,`sessionToken`)}}}catch{sessionStorage.removeItem(this.storageKey())}}async request(e,t){return E(await(await fetch(`${this.configs.network.relayer.url.replace(/\/$/,``)}${pt}/${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.configs.registration.publishableKey}`,"x-seams-environment-id":this.configs.registration.projectEnvironmentId},body:JSON.stringify({...t,appOrigin:this.parentOrigin}),cache:`no-store`,credentials:`omit`})).json(),`external authentication response`)}async lock(){let e=this.state,t=oK(e);e.kind===`owner_operation`&&e.approval.kind===`pending`&&e.approval.controller.abort(),this.generation+=1,this.state={kind:`empty`},sessionStorage.removeItem(this.storageKey()),e.kind!==`empty`&&await this.request(`logout`,{walletId:e.attempt.walletId,sessionToken:e.attempt.sessionToken}),e.kind===`owner_operation`&&t.kind!==`empty`&&await this.request(`logout`,{walletId:t.attempt.walletId,sessionToken:t.attempt.sessionToken})}async releaseForOwner(){this.state.kind!==`empty`&&await this.lock()}async prepare(e){let t=_(e);if(!t.ok)return lt(`invalid_request`);let n=this.lock(),r=this.generation;if(await n,r!==this.generation||(await this.lockOwner(),r!==this.generation))return lt(`superseded`);let i=lK(),a=lK(),o=await this.request(`prepare`,{walletId:t.value,binding:i,sessionToken:a});if(r!==this.generation)return lt(`superseded`);if(o.ok!==!0)return vt(o);let s=E(o.value,`external authentication attempt`),c=D(s.attemptId,`attemptId`);if(typeof s.expiresAtMs!=`number`||s.walletId!==t.value||s.purpose!==`authenticate`)throw Error(`Invalid attempt`);return this.state={kind:`prepared`,attempt:{walletId:t.value,attemptId:c,binding:i,sessionToken:a}},{ok:!0,value:{purpose:`authenticate`,walletId:t.value,attemptId:c,expiresAtMs:s.expiresAtMs}}}async authenticate(e,t=uK){if(t(),e.method===`google`){let t=await this.prepare(e.walletId);if(!t.ok)return t}let n=this.state,r=this.generation;if(n.kind!==`prepared`||n.attempt.walletId!==e.walletId)return lt(`access_denied`);let i=n.attempt,a;if(e.method===`google`){let t=await this.request(`exchange`,{walletId:e.walletId,attemptId:i.attemptId,idToken:e.idToken});if(t.ok!==!0)return vt(t);a=D(E(t.value,`exchange`).code,`code`)}else{if(e.attemptId!==i.attemptId)return lt(`access_denied`);a=e.code}if(r!==this.generation)return lt(`superseded`);t();let o=await this.request(`redeem`,{walletId:i.walletId,attemptId:i.attemptId,binding:i.binding,sessionToken:i.sessionToken,code:a});if(o.ok!==!0)return vt(o);try{t()}catch{return await this.request(`logout`,{walletId:i.walletId,sessionToken:i.sessionToken}),lt(`superseded`)}let s=dK(o.value,i,this.configs.registration.projectEnvironmentId);return r===this.generation?(this.state={kind:`authenticated`,attempt:i,settings:s},sessionStorage.setItem(this.storageKey(),JSON.stringify(i)),{ok:!0,value:s.authentication}):(await this.request(`logout`,{walletId:i.walletId,sessionToken:i.sessionToken}),lt(`superseded`))}async prepareAssociation(e){let t=_(e);if(!t.ok)return lt(`invalid_request`);let n=this.state,r=oK(n),i=++this.generation;n.kind===`owner_operation`&&n.approval.kind===`pending`&&n.approval.controller.abort(),this.state=r,(n.kind===`prepared`||n.kind===`owner_operation`)&&await this.request(`logout`,{walletId:n.attempt.walletId,sessionToken:n.attempt.sessionToken});let a=lK(),o=lK(),s=await this.request(`prepare-association`,{walletId:t.value,binding:a,sessionToken:o});if(i!==this.generation)return lt(`superseded`);if(s.ok!==!0)return vt(s);let c=E(s.value,`external association attempt`),l=D(c.attemptId,`attemptId`);if(typeof c.expiresAtMs!=`number`||c.walletId!==t.value||c.purpose!==`associate`)throw Error(`Invalid external association attempt`);return this.state={kind:`owner_operation`,purpose:`associate`,approval:{kind:`ready`},attempt:{walletId:t.value,attemptId:l,binding:a,sessionToken:o},connection:r},{ok:!0,value:{purpose:`associate`,walletId:t.value,attemptId:l,expiresAtMs:c.expiresAtMs}}}async associate(e,t=uK){if(t(),e.method===`google`){let t=await this.prepareAssociation(e.walletId);if(!t.ok)return t}let n=this.state;if(n.kind!==`owner_operation`||n.purpose!==`associate`||n.attempt.walletId!==e.walletId)return lt(`access_denied`);let r=this.generation,i;if(e.method===`google`){let t=await this.request(`exchange`,{walletId:e.walletId,attemptId:n.attempt.attemptId,idToken:e.idToken});if(t.ok!==!0)return vt(t);i=D(E(t.value,`association exchange`).code,`code`)}else{if(e.attemptId!==n.attempt.attemptId)return lt(`access_denied`);i=e.code}return this.completeOwnerOperation(n.attempt,i,r,t)}assertOwnerOperation(e,t,n){if(n(),e!==this.generation||this.state.kind!==`owner_operation`||this.state.attempt.attemptId!==t)throw new rK(`cancelled`)}async completeOwnerOperation(e,t,n,r){let i=this.assertOwnerOperation.bind(this,n,e.attemptId,r);try{i();let n=await this.request(`owner-challenge`,{walletId:e.walletId,attemptId:e.attemptId,binding:e.binding,sessionToken:e.sessionToken,code:t});if(i(),n.ok!==!0)return vt(n);let r=ut(n.value);if(this.state.kind!==`owner_operation`||r.kind!==this.state.purpose||r.walletId!==e.walletId||r.attemptId!==e.attemptId)return lt(`access_denied`);let a=new AbortController;this.state={kind:`owner_operation`,purpose:this.state.purpose,attempt:e,connection:this.state.connection,approval:{kind:`pending`,controller:a}};let o=await this.approveOwner({challenge:r,signal:a.signal,assertCurrent:i});if(i(),r.expiresAtMs<=Date.now())return lt(`expired`);let s=await this.request(r.kind,{walletId:e.walletId,attemptId:e.attemptId,binding:e.binding,sessionToken:e.sessionToken,code:t,factorProof:o});return i(),s.ok===!0?{ok:!0,value:null}:vt(s)}catch(e){return n===this.generation?e instanceof rK?lt(e.code):lt(`unavailable`):lt(`superseded`)}finally{if(n===this.generation&&this.state.kind===`owner_operation`&&this.state.attempt.attemptId===e.attemptId){let t=this.state;t.approval.kind===`pending`&&t.approval.controller.abort(),this.state=t.connection;try{await this.request(`logout`,{walletId:e.walletId,sessionToken:e.sessionToken})}catch{}}}}async captureOwnerOperation(e){let t=await this.getSession(String(e.walletId));if(t?.authentication.kind!==`external_authenticated`||t.authentication.sessionId!==e.sessionId||t.authentication.associationId!==e.associationId)throw Error(`The external wallet connection changed.`);return this.assertOwnerOperationCurrent.bind(this,this.generation,e)}assertOwnerOperationCurrent(e,t){let n=oK(this.state);if(e!==this.generation||n.kind!==`authenticated`||n.settings.authentication.sessionId!==t.sessionId||n.settings.authentication.expiresAtMs<=Date.now())throw Error(`The external wallet connection changed or expired.`)}async getSession(e){let t=this.state,n=oK(t);if(n.kind===`empty`||e&&e!==n.attempt.walletId)return null;let r=this.generation,i=await this.request(`settings`,{walletId:n.attempt.walletId,sessionToken:n.attempt.sessionToken});if(r!==this.generation)return null;if(i.ok!==!0)return this.state.kind===`owner_operation`?(this.state={kind:`owner_operation`,purpose:this.state.purpose,attempt:this.state.attempt,approval:this.state.approval,connection:{kind:`empty`}},sessionStorage.removeItem(this.storageKey())):await this.lock(),null;let a=dK(i.value,n.attempt,this.configs.registration.projectEnvironmentId),o={kind:`authenticated`,attempt:n.attempt,settings:a};return this.state=this.state.kind===`owner_operation`?{kind:`owner_operation`,purpose:this.state.purpose,attempt:this.state.attempt,approval:this.state.approval,connection:o}:o,fK(a)}async remove(e,t=uK){t();let n=_(e.walletId);if(!n.ok)return lt(`invalid_request`);let r=this.state,i=oK(r),a=++this.generation;r.kind===`owner_operation`&&r.approval.kind===`pending`&&r.approval.controller.abort(),this.state=i;let o=lK(),s=lK(),c=await this.request(`prepare-unlink`,{walletId:n.value,associationId:e.associationId,binding:o,sessionToken:s});if(a!==this.generation)return lt(`superseded`);if(c.ok!==!0)return vt(c);let l=E(c.value,`association removal attempt`),u={walletId:n.value,attemptId:D(l.attemptId,`attemptId`),binding:o,sessionToken:s};return this.state={kind:`owner_operation`,purpose:`unlink`,attempt:u,connection:i,approval:{kind:`ready`}},this.completeOwnerOperation(u,D(l.code,`code`),a,t)}};function lK(){return P(crypto.getRandomValues(new Uint8Array(32)))}function uK(){}function dK(e,t,n){let r=mt(e),i=r.authentication;if(i.walletId!==t.walletId||i.sessionId!==t.attemptId||i.environmentId!==n)throw Error(`External settings do not match the requested session`);return r}function fK(e){let t=null,n=null,r=null,i=null;for(let a of e.accounts)a.family===`ed25519`?(t=a.address,n=a.publicKey):(r=a.address,i=a.publicKey);return{appIdentity:{kind:`resolved`,walletId:e.authentication.walletId,nearAccountId:t===null?null:B(t),nearOperationalPublicKey:n,userData:null,authMethods:[],thresholdEcdsaEthereumAddress:r,thresholdEcdsaPublicKeyB64u:i},authentication:e.authentication,externalSettings:e,capabilityProjection:{kind:`not_requested`},nonceDiagnostics:null}}function pK(e,t){let n=new cK(e().configs,qC.bind(null,e()),aK.bind(null,e),t);return{readExternalSession:wK.bind(null,e,n),captureExternalOwnerOperation:n.captureOwnerOperation.bind(n),authenticate:n.authenticate.bind(n),prepareExternalAuth:n.prepare.bind(n),prepareExternalAssociation:n.prepareAssociation.bind(n),associateExternalAuth:n.associate.bind(n),removeExternalAuth:n.remove.bind(n),unlock:xK.bind(null,e,n),unlockWithAuthMethod:hK.bind(null,e,n),lock:SK.bind(null,e,n),getSession:CK.bind(null,e,n),getRecentUnlocks:EK.bind(null,e),hasPasskey:TK}}function mK(e){return e.kind===z.passkey&&e.status===`active`}async function hK(e,t,n,i=_K,a){await t.lock();let o=e(),s=V(n.walletId),c=r(n.walletAuthMethodId);if(!c.ok)throw Error(`Wallet unlock method ID is invalid.`);let l=await cp(o.configs.authMethods,n.method);return i(),await l.unlock({walletId:s,walletAuthMethodId:c.value,relayerUrl:o.configs.network.relayer.url,assertActive:i,mountCapture:a,surfaceMeasurementBinding:o.signingEngine.getWalletIframeSurfaceMeasurementBinding(),prepareSession:gK.bind(null,o,s,i)})}async function gK(e,t,n,r){r.throwIfAborted(),n(),await qC(e),r.throwIfAborted(),n();let i=await e.signingEngine.advanceWalletLockGeneration(t);return r.throwIfAborted(),n(),e.signingEngine.installAuthMethodSession.bind(e.signingEngine,i)}function _K(){}function vK(e){switch(e?.mode){case`ed25519_only`:return{kind:`near_ed25519_only`};case`ecdsa_only`:return{kind:`evm_family_ecdsa_only`};case`ed25519_and_ecdsa`:case void 0:return{kind:`all_registered_mpc`}}throw Error(`wallet unlock selection is unsupported`)}async function yK(e){let t=await _b({walletId:e.walletId,requestedCapabilityFamilies:vK(e.selection)});switch(t.kind===`missing_requested_capability_subject`&&(await ss({relayerUrl:e.relayerUrl}),t=await _b({walletId:e.walletId,requestedCapabilityFamilies:vK(e.selection)})),t.kind){case`resolved`:return t.subjectSet;case`missing_requested_capability_subject`:throw Error(`wallet unlock is missing the requested capability subject`);case`capability_subject_resolution_failed`:throw Error(`wallet unlock subject resolution failed: ${t.reason}`)}throw Error(`wallet unlock subject resolution returned an unknown result`)}function bK(e){let t=null;for(let n of e.subjects)if(n.kind===`near_ed25519_wallet`){if(t)throw Error(`wallet unlock resolved multiple NEAR Ed25519 subjects`);t=n}return t}async function xK(e,t,n,r){await t.lock();let i=String(n||``).trim();if(!i)throw Error(`unlock requires walletId`);let a=e(),o=await ts(V(i));if(o)return await tK({context:a,pending:o,options:r});let s=await yK({relayerUrl:a.configs.network.relayer.url,walletId:i,selection:r?.unlockSelection}),c=await Mx(a,s,r);if(c?.success){let e=bK(s);e&&await a.signingEngine.activateAuthenticatedWalletState({walletId:e.walletId,nearAccountId:e.nearAccountId,signerSlot:e.signerSlot,nearClient:a.nearClient})}return await a.signingEngine.warmCriticalResources({kind:`none`}),c}async function SK(e,t){try{await t.lock()}finally{await qC(e())}}async function CK(e,t,n){return await wK(e,t,n)||await qS(e(),n,new Ja)}async function wK(e,t,n){return e().signingEngine.readWalletAuthenticationState().kind===`authenticated`?(await t.releaseForOwner(),null):t.getSession(n)}async function TK(e){let t=String(e||``).trim();if(!t)return!1;try{return(await K.listWalletAuthMethodsV2ForWallet(t)).some(mK)}catch{return!1}}async function EK(e){return await BC(e())}async function DK(e,t,n){let r=V(t.walletSession.walletId);return await e().signingEngine.scheduleRouterAbEcdsaDerivationLoginPresignaturePrefill({walletId:r,chainTarget:t.chainTarget},n)}async function OK(e){switch(e.state.kind){case`active_session`:break;case`wallet_unlocked_without_signing_session`:if(e.state.reason!==`exhausted`)return;break;case`external_read`:case`wallet_locked`:case`wallet_authenticated_identity_unresolvable`:case`expired_session`:return;default:e.state;return}let t=En({walletId:e.state.walletId}),n=new Ja,r=[];for(let i of e.chainTargets)r.push(e.prefill({walletSession:t,chainTarget:i},n));await Promise.all(r)}function kK(e){switch(e.kind){case`ecdsa`:return{kind:`ecdsa`,walletSession:En(e.walletSession),chainTarget:xn(e.chainTarget)};case`ed25519`:return{kind:`ed25519`,walletSession:En(e.walletSession),nearAccount:Cn(e.nearAccount.accountId)}}}function AK(e){switch(e.kind){case`ecdsa`:return{kind:`ecdsa`,laneIdentity:nl(e.laneIdentity)};case`ed25519`:{let t=m(e.materialActivation);if(!t.ok)throw Error(t.error.message);return{kind:`ed25519`,laneIdentity:il(e.laneIdentity),materialActivation:t.value}}}}function jK(e,t){let n={...e.options,theme:e.options.theme??t};switch(e.kind){case`ecdsa`:{let t=nl(e.laneIdentity);if(String(t.signer.walletId)!==String(e.walletSession.walletId))throw Error(`[SeamsWeb] key export lane wallet does not match wallet session`);if(!wn(t.signer.chainTarget,e.chainTarget))throw Error(`[SeamsWeb] key export lane chain target does not match request target`);return{kind:`ecdsa`,chainTarget:e.chainTarget,walletSession:e.walletSession,laneIdentity:t,options:n}}case`ed25519`:{let t=il(e.laneIdentity),r=m(e.materialActivation);if(!r.ok)throw Error(r.error.message);if(String(t.signer.account.wallet.walletId)!==String(e.walletSession.walletId))throw Error(`[SeamsWeb] Ed25519 export lane wallet does not match wallet session`);if(String(t.signer.account.nearAccountId)!==String(e.nearAccount.accountId))throw Error(`[SeamsWeb] Ed25519 export lane does not match the NEAR account`);return{kind:`ed25519`,nearAccount:Cn(e.nearAccount.accountId),walletSession:e.walletSession,laneIdentity:t,materialActivation:r.value,options:n}}}}function MK(e,t){let n=t;return{locale:me(n.locale??e.locale),theme:Ye({value:n.theme,fallback:e.theme,legacyTokens:n.tokens}),palette:Je({value:n.palette,fallback:e.palette})}}function NK(e,t){t.event===`registration.near_provisioning_changed`&&e(t)}function PK(e){switch(e.kind){case`completed`:return;case`pending`:console.warn(`[SeamsWeb] pending wallet recovery replay remains pending:`,e.recoveryOperationId,e.failure);return;case`discarded`:console.warn(`[SeamsWeb] pending wallet recovery was refused and discarded:`,e.recoveryOperationId);return;case`corrupt`:console.warn(`[SeamsWeb] pending wallet recovery replay record is corrupt:`,e.recoveryOperationId);return}}function FK(e){e().catch(IK)}function IK(e){console.warn(`[SeamsWeb] pending linked-device acknowledgement replay failed:`,e instanceof Error?e.message:String(e||`unknown error`))}var LK=class{signingEngine;nearClient;configs;readExternalSession;captureExternalOwnerOperation;appearance;theme;prefillRestoredSession;recovery;devices;keys;preferences;auth;placement;registration;registerWalletCommand;near;tempo;evm;deviceLinkingDispose;resumePendingAcknowledgementsV1;constructor(e,t,n){this.parentOrigin=t,this.configs=e,aa({mode:`wallet`}),this.nearClient=n||new af(Ke(this.configs.network.chains));let r=CD(K),i=new Pz(this.configs,this.nearClient,{managerStores:r.managerStores,signingEngineStores:r.signingEngineStores,sealedSigningSessionStore:r.sealedSigningSessionStore,ed25519YaoPublicCapabilityReferences:r.ed25519YaoPublicCapabilityReferences,createRuntime:zT,initializeRuntime:TD,shouldPrewarmUiConfirmUi:zK});this.signingEngine=i,this.appearance=this.configs.ui.appearance,this.theme=this.appearance.theme.mode;try{this.signingEngine.setAppearance(this.appearance)}catch{}let a=this.signingEngine.getUserPreferences(),o=RT(i.getSignerWorkerContext()),s=Xw({confirmDeviceLinking:Tu,http:o.http,relayerUrl:String(this.configs.network.relayer?.url||``).trim(),walletSessions:q,resolveSelectedWalletAuthority:K.resolveSelectedWalletAuthority.bind(K),readWalletAuthenticationState:i.readWalletAuthenticationState.bind(i),readUnlockedEd25519ExportRootCapabilityV1:Qa});this.placement=OT({lockWallet:this.lockAfterWalletMove.bind(this),signingEngine:i,managementRequest:s.managementRequest,readAuthentication:i.readWalletAuthenticationState.bind(i)});let c=UU({readAppearance:this.readAppearance.bind(this),platform:o,ownerAuthorities:s,configs:this.configs,signingEngine:i,getContext:this.getContext.bind(this)});this.deviceLinkingDispose=c.dispose,this.resumePendingAcknowledgementsV1=c.resumePendingAcknowledgementsV1;let l=pK(this.getContext.bind(this),t);this.readExternalSession=l.readExternalSession,this.captureExternalOwnerOperation=l.captureExternalOwnerOperation;let u=GG(this.getContext.bind(this),l);this.registerWalletCommand=u.registerWallet,this.prefillRestoredSession=DK.bind(null,this.getContext.bind(this));let d=fG({getContext:this.getContext.bind(this),registerWallet:u.registerWallet,getWalletSession:l.getSession,resumePendingAcknowledgements:this.resumePendingAcknowledgementsAfterExactUnlockV1.bind(this)}),f={flush:RK,setCurrentWallet:a.setCurrentWallet.bind(a),getCurrentWalletId:a.getCurrentWalletId.bind(a),onConfirmationConfigChange:a.onConfirmationConfigChange.bind(a),onCurrentWalletChange:a.onCurrentWalletChange.bind(a),setConfirmationBehavior:a.setConfirmationBehavior.bind(a),setConfirmationConfig:a.setConfirmationConfig.bind(a),getConfirmationConfig:a.getConfirmationConfig.bind(a)},p={resolveExactKeyExportLane:this.resolveExactKeyExportLaneDomain.bind(this),exportKeypairWithUI:this.exportKeypairWithUIDomain.bind(this)},m=hk({createNearCommands:nD.bind(null,this.getContext.bind(this),this.runOwnerNearOperation.bind(this)),createEvmFamilyCommands:oD.bind(null,this.getContext.bind(this)),nearClient:this.nearClient,configs:this.configs,preferences:f,auth:{...l,...d},registration:{...u,onNearAccountChange:this.onNearAccountChange.bind(this)},recovery:{syncAccount:this.syncAccountDomain.bind(this),getCodeStatus:this.getCodeStatusDomain.bind(this),confirmBackup:this.confirmBackupDomain.bind(this),requestWalletCustodyEmailOtpChallenge:this.requestWalletCustodyEmailOtpChallengeDomain.bind(this),rotateCodes:this.rotateCodesDomain.bind(this)},devices:{...c.domain},keys:p});this.preferences=f,this.auth=m.auth,this.registration=m.registration,this.recovery=m.recovery,this.devices=m.devices,this.keys=p,this.near=m.near,this.tempo=m.tempo,this.evm=m.evm,this.resumePendingRegistrationOnStartup(),FK(c.resumePendingAcknowledgementsV1)}async prefillRestoredWalletSession(e){await OK({state:e,chainTargets:this.configuredChainTargets(),prefill:this.prefillRestoredSession})}async lockAfterWalletMove(){Aw(),await this.auth.lock()}onSdkLifecycleEvent(e){return this.signingEngine.onSdkLifecycleEvent(e)}async runOwnerNearOperation(e,t,n,r){return await uw({getContext:this.getContext.bind(this),captureConnection:this.captureExternalOwnerOperation,parentOrigin:this.parentOrigin},e,t,n,r)}getContext(){return{signingEngine:this.signingEngine,nearClient:this.nearClient,configs:this.configs,theme:this.theme,resumePendingAcknowledgementsV1:this.resumePendingAcknowledgementsAfterExactUnlockV1.bind(this)}}resumePendingAcknowledgementsAfterExactUnlockV1(){FK(this.resumePendingAcknowledgementsV1)}async resumePendingRegistrationOnStartup(){if(K.isDisabled())return;let e=String(this.configs.network.relayer?.url||``).trim();if(e){try{let t=await ss({relayerUrl:e});for(let e of t)e.kind===`failed`&&console.warn(`[SeamsWeb] pending registration replay remains pending:`,e.registrationCeremonyId,e.error)}catch(e){console.warn(`[SeamsWeb] pending registration startup replay failed:`,e instanceof Error?e.message:String(e||`unknown error`))}try{let t=await Du({relayUrl:e});for(let e of t)PK(e)}catch(e){console.warn(`[SeamsWeb] pending wallet recovery startup replay failed:`,e instanceof Error?e.message:String(e||`unknown error`))}}}dispose(){this.deviceLinkingDispose(),this.signingEngine.dispose()}readAppearance(){return this.appearance}setTheme(e){e!==`light`&&e!==`dark`||this.setAppearance({theme:{...this.appearance.theme,mode:e}})}chainTarget(e){return XT(this.configs.network.chains,e)}configuredChainTargets(){return Tn(this.configs.network.chains)}setAppearance(e){let t=MK(this.appearance,e);this.appearance=t,this.theme=t.theme.mode;try{this.signingEngine.setAppearance(t)}catch{}try{document.documentElement.setAttribute(`data-seams-theme`,this.theme)}catch{}}setWalletIframeSurfaceMeasurementBinding(e){this.signingEngine.setWalletIframeSurfaceMeasurementBinding(e)}async syncAccountDomain(e){let t=e.walletId?ki(e.walletId):null;return await XE(this.getContext(),t?String(t):null,e.options)}onNearAccountChange(e){return this.onSdkLifecycleEvent(NK.bind(null,e))}async getCodeStatusDomain(e){let t=String(this.configs.network.relayer.url||``).trim(),n=e.authorization.kind===`passkey`?await If({relayUrl:t,walletId:e.walletId,rpId:this.configs.wallet.rpId}):await Rf({context:this.getContext(),relayUrl:t,walletId:e.walletId});return n.kind===`ready`?{...n,pendingLocalBackup:await Ol.has(e.walletId)}:n}async preloadedCodeStatusDomain(e){return e}async confirmBackupDomain(e){let t=String(this.configs.network.relayer.url||``).trim(),n=this.getCodeStatusDomain.bind(this,e);if(e.authorization.kind===`email_otp`){let e=await n();if(e.kind!==`ready`)throw Error(e.message);n=this.preloadedCodeStatusDomain.bind(this,e)}let r=await Dl({walletId:e.walletId,loadStatus:n,loadPendingBackup:this.loadPendingWalletRecoveryCodeBackupRequest.bind(this,e.walletId)},this.signingEngine.getWalletIframeSurfaceMeasurementBinding(),{appearance:this.appearance});if(r.kind!==`wallet_recovery_codes_backed_up_v1`)throw Error(`Pending wallet recovery-code backup was not completed`);let i=e.authorization.kind===`passkey`?await Bf({relayUrl:t,walletId:e.walletId,rpId:this.configs.wallet.rpId,expectedIssuedAtMs:r.issuedAtMs}):await Wf({context:this.getContext(),relayUrl:t,walletId:e.walletId,expectedIssuedAtMs:r.issuedAtMs});return i.kind===`acknowledged`&&await Ol.deleteIssuedAtMs(e.walletId,r.issuedAtMs),i}async loadPendingWalletRecoveryCodeBackupRequest(e){let t=await Ol.read(e);if(!t)return null;if(t.kind!==`ready`)throw Error(`Recovery codes are awaiting a verified server issuance. Retry registration.`);return{kind:`wallet_recovery_code_backup_request_v1`,walletId:t.walletId,recoveryCodes:t.recoveryCodes,continuation:`pending_backup_must_finish`,issuedAtMs:t.issuedAtMs}}async requestWalletCustodyEmailOtpChallengeDomain(e){return await zf({relayUrl:String(this.configs.network.relayer.url||``).trim(),...e})}async rotateCodesDomain(e){let t=String(this.configs.network.relayer.url||``).trim();return await ZD({context:this.getContext(),relayUrl:t,walletId:e.walletId,authorization:e.authorization})}async signTempoFeeTokenPreferenceInternal(e){let t=pD(e),n=await this.signingEngine.signEvmFamily({...e,request:t});if(n.chain!==`evm`||n.kind!==`eip1559`)throw Error(`[SeamsWeb][tempo] expected EVM FeeManager result, received ${n.chain}`);return n}async resolveExactKeyExportLaneDomain(e){let t=kK(e);if($T(this.configs,t),!String(t.walletSession.walletId||``).trim())throw Error(`[SeamsWeb] key export lane resolution requires wallet session context`);return AK(await this.signingEngine.resolveExactKeyExportLane(t))}async exportKeypairWithUIDomain(e){let t=jK(e,this.theme);if($T(this.configs,t),!String(t.walletSession.walletId||``).trim())throw Error(`[SeamsWeb] key export requires wallet session user context`);await this.signingEngine.exportKeypairWithUI(t)}};async function RK(){}function zK(e){return!(typeof window>`u`||window.Worker===void 0||e&&e!==window.location.origin)}const BK=`seams-theme-overrides`,VK=[`.seams-wallet-ui`,`.seams-auth-menu-surface`,`.seams-host-themed-dialog`],HK=VK.join(`,
3
+ `),UK=VK.map(e=>`${e}[theme="light"],\n:root[data-seams-theme="light"] ${e}:not([theme="dark"])`).join(`,
4
+ `);let WK=null;function GK(){return WK||=cn({doc:document,baseCss:``,dynamicStyleDataAttr:`data-seams-theme-overrides`,nonce:()=>sn()}),WK}function KK(e){let t=e.trim();return t&&/^[A-Za-z][A-Za-z0-9_-]*$/.test(t)?t:null}function qK(e){let t=e.trim();return!t||t.length>1024||/[{};\n\r]/.test(t)?null:t}function JK(e,t){let n=[];for(let[r,i]of Object.entries(e)){let e=KK(r);if(!e)continue;let a=qK(i);a&&n.push(` --seams-${t}-${e}: ${a} !important;`)}return n}function YK(e){let t=e.theme.mode,n=e.theme.colors,r=[...JK(n,`colors`),...JK(e.theme.shape??{},`shape`)],i=[];if(r.length>0){let e=t===`light`?UK:HK;i.push(`${e} {\n${r.join(`
5
+ `)}\n}`)}let a=i.join(`
6
+
7
+ `).trim();if(!a){GK().deleteDynamicRule(BK);return}GK().setDynamicRule(BK,a)}function XK(){return{parentOrigin:null,port:null,configuration:{kind:`unconfigured`},preferencesRevision:0,sessionObserver:null,nearClient:null,walletRuntime:null,prefsUnsubscribe:null,lifecycleSource:null,lifecycleUnsubscribe:null,lifecycleListener:null,expiredSessionsByWallet:new Map,surfaceMeasurementBinding:{kind:`disabled`}}}function ZK(e){if(!e.parentOrigin)throw Error(`Wallet service requires an authenticated parent origin.`);e.walletRuntime&&e.walletRuntime.parentOrigin!==e.parentOrigin&&(e.walletRuntime.dispose(),e.walletRuntime=null,e.sessionObserver?.dispose(),e.sessionObserver=null);let{configuration:t}=e;if(t.kind===`unconfigured`)throw Error(`Wallet service not configured. Call PM_SET_CONFIG first.`);let n=Ke(t.config.network.chains);return e.nearClient||=new af(n),e.walletRuntime||(qf(!0),e.walletRuntime=new LK(t.config,e.parentOrigin,e.nearClient),QK(e)),e.walletRuntime}function QK(e){try{let t=e.walletRuntime;if(!t)return;let n=t.theme;(n===`light`||n===`dark`)&&document.documentElement.setAttribute(`data-seams-theme`,n)}catch{}}function $K(e,t){let n=nt(e.configuration.kind===`configured`?e.configuration.config:null),r=nt(t.config);e.configuration=t;let i=t.config.ui.appearance,a=i.theme.mode;try{document.documentElement.setAttribute(`data-seams-theme`,a),document.documentElement.lang=i.locale??`en`,YK(i)}catch{}if(e.walletRuntime&&r===n)try{e.walletRuntime.setAppearance(i)}catch{}if(it(eq(t.assetsBaseUrl)),r!==n){let t=e.walletRuntime;e.walletRuntime=null,e.sessionObserver?.dispose(),e.sessionObserver=null,e.lifecycleSource=null,e.surfaceMeasurementBinding={kind:`disabled`},e.prefsUnsubscribe?.(),e.lifecycleUnsubscribe?.(),e.prefsUnsubscribe=null,e.lifecycleUnsubscribe=null,e.nearClient=null,t?.dispose()}}function eq(e){let t=window.location.origin;try{let n=new URL(e,t);if(n.origin===t)return n.href.endsWith(`/`)?n.href:`${n.href}/`}catch{}return new URL(`/sdk/`,t).href}function tq(e,t){e.lifecycleSource!==t&&(e.lifecycleUnsubscribe?.(),e.lifecycleSource=t,e.lifecycleUnsubscribe=t.onSdkLifecycleEvent(iq.bind(null,e,t)))}function nq(e,t){e.lifecycleListener=t,e.walletRuntime&&tq(e,e.walletRuntime)}function rq(e){throw Error(`Unhandled SDK lifecycle event: ${String(e)}`)}function iq(e,t,n){if(e.lifecycleSource===t)switch(n.event){case`signing_session.expired`:{let t=e.expiredSessionsByWallet.get(n.walletId);if(t?.has(n.walletSessionId))return;t?t.add(n.walletSessionId):e.expiredSessionsByWallet.set(n.walletId,new Set([n.walletSessionId])),e.lifecycleListener?.(n);return}case`registration.near_provisioning_changed`:e.lifecycleListener?.(n);return;default:return rq(n)}}let aq=null;const oq=new Map;let sq=null;const cq=new Set([`PM_REGISTER_WALLET`,`PM_ADD_WALLET_SIGNER`,`PM_ADD_PASSKEY`,`PM_ACTIVATE_AUTH_METHOD`,`PM_EXTERNAL_OWNER_AUTH`,`PM_OWNER_NEAR_TRANSACTION`,`PM_ADD_EMAIL_OTP`,`PM_REVOKE_AUTH_METHOD`,`PM_REVOKE_LINKED_DEVICE`,`PM_SIGN_TX_WITH_ACTIONS`,`PM_SIGN_AND_SEND_TX`,`PM_SIGN_DELEGATE_ACTION`,`PM_SIGN_NEP413`,`PM_UNLOCK`,`PM_UNLOCK_AUTH_METHOD`,`PM_SIGN_TEMPO`,`PM_ROTATE_WALLET_RECOVERY_CODES`,`PM_GET_WALLET_RECOVERY_CODE_STATUS`,`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`,`PM_SYNC_ACCOUNT_FLOW`,`PM_EXPORT_KEYPAIR_UI`,`PM_SCAN_AND_LINK_DEVICE`,`PM_START_DEVICE2_LINKING_FLOW`]);function lq(e,t){e.post({type:`SURFACE_MEASUREMENT`,payload:t})}function uq(e){if(e.type!==`PM_EXPORT_KEYPAIR_UI`)return;let t=e.payload?.options?.variant;return t===`modal`||t===`drawer`?t:`drawer`}function dq(e){let t;try{t=xt(e.req.requestId)}catch{return null}let n=uq(e.req);return{requestId:t,binding:{kind:`wallet_iframe`,...e.transactionReview?{transactionReview:e.transactionReview}:{},requestId:t,postMeasurement:lq.bind(null,e),...n?{hostSurfaceVariant:n}:{}}}}function fq(e){return cq.has(e.req.type)}function pq(e,t){let n=e.surfaceMeasurementBinding;n.kind!==`wallet_iframe`||n.requestId!==t||(e.surfaceMeasurementBinding={kind:`disabled`},e.walletRuntime?.setWalletIframeSurfaceMeasurementBinding({kind:`disabled`}))}function mq(e,t){e.surfaceMeasurementBinding=t,ZK(e).setWalletIframeSurfaceMeasurementBinding(t)}function hq(e){return sq!==e.executionGeneration&&(oq.clear(),sq=e.executionGeneration),aq||=XK(),e.onConfigurationChanged=gq.bind(null,e),aq.parentOrigin=e.parentOrigin,aq.port!==e.port&&(aq.sessionObserver?.dispose(),aq.sessionObserver=null),aq.port=e.port,e.parentOrigin!==null&&Ow(e.parentOrigin),nq(aq,Oq.bind(null,aq)),e.configuration.kind===`configured`&&$K(aq,e.configuration),aq}function gq(e){!aq||e.configuration.kind===`unconfigured`||hq(e)}function _q(e){let t=e.walletRuntime,n=ZK(e);if(tq(e,n),t===n)return yq(e,n),n;let r=n.preferences;e.prefsUnsubscribe?.();let i=Cq.bind(null,e,n),a=r.onConfirmationConfigChange?.(i)||null,o=r.onCurrentWalletChange?.(i)||null;return e.prefsUnsubscribe=()=>{try{a?.()}catch{}try{o?.()}catch{}},yq(e,n),Promise.resolve().then(i).catch(()=>{}),n}function vq(e,t,n,r){e.walletRuntime!==t||e.port!==n||n.postMessage(r)}function yq(e,t){if(e.sessionObserver)return e.sessionObserver;if(!e.port)throw Error(`Wallet session observation requires a connected parent`);return e.sessionObserver=new zp(t,vq.bind(null,e,t,e.port),e.expiredSessionsByWallet,qS.bind(null,t.getContext())),e.sessionObserver}function bq(e,t,n,r){return yq(e,wq(e,t)).observe(n,r)}function xq(e,t){return yq(e,wq(e,t)).publishCurrentSession()}function Sq(e,t){return{walletId:t.preferences.getCurrentWalletId(),confirmationConfig:t.preferences.getConfirmationConfig(),revision:e.preferencesRevision}}function Cq(e,t){e.walletRuntime===t&&(e.preferencesRevision+=1,e.port?.postMessage({type:`PREFERENCES_CHANGED`,payload:Sq(e,t)}))}function wq(e,t){if(t.executionGeneration!==t.state.executionGeneration)throw Error(`Wallet configuration changed during request`);return _q(e)}function Tq(e,t){return Sq(e,wq(e,t))}function Eq(e,t){return{getWalletRuntime:wq.bind(null,e,t),readPreferences:Tq.bind(null,e,t),observeSession:bq.bind(null,e,t),publishCurrentSession:xq.bind(null,e,t),post:Dq.bind(null,t),postProgress:(e,n)=>{e&&Dq(t,{type:`PROGRESS`,requestId:e,payload:n})},isCancelled:t.isCancelled,respondIfCancelled:t.respondIfCancelled}}function Dq(e,t){e.executionGeneration===e.state.executionGeneration&&($f(t),e.post(t))}function Oq(e,t){e.sessionObserver?.onLifecycleEvent(t)}async function kq(e,t){if(e.respondIfCancelled(e.req.requestId))return;let n=hq(e.state),r=yq(n,wq(n,e));r.beginOperation(),ep(e.req,e.post);let i=fq(e)?dq(e):null;try{let r=wq(n,e);await Va(e.req,r.preferences.getCurrentWalletId());let a=oq.get(t);a||(a=t(Eq(n,e)),oq.set(t,a));let o=a[e.req.type];if(!o)throw Error(`Unsupported wallet iframe request type: ${e.req.type}`);i&&mq(n,i.binding),await o(e.req),e.executionGeneration===e.state.executionGeneration&&Zf(e.req)}catch(t){throw e.executionGeneration===e.state.executionGeneration&&Qf(e.req.requestId,t),t}finally{r.endOperation(),i&&e.executionGeneration===e.state.executionGeneration&&pq(n,i.requestId)}}async function Aq(e,t){let n=hq(e),r=n.configuration;if(r.kind!==`configured`)throw Error(`Wallet service is not configured.`);let i=Ka(t,null);if(i===null)return{kind:`disabled`};_q(n);let a=await K.resolveSelectedWalletAuthority(i);if(a.kind!==`resolved`||a.authMethod.kind!==`voiceid`)return{kind:`disabled`};if(!await za(i,a.authMethod.walletAuthMethodId))throw Error(`VoiceID is turned off. Unlock with another method.`);return await(await cp(r.config.authMethods,`voiceid`)).review(t,r)}export{hp as _,Rw as a,op as b,Mw as c,Fx as d,iS as f,Sp as g,Rp as h,kq as handleWalletHostRuntimeRequestWithHandlers,Iw as i,KC as l,_b as m,xE as n,kw as o,Mx as p,ZE as r,Aw as s,pD as t,zb as u,Z as v,Aq as walletAuthMethodReviewPolicy,sp as y};