UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

1 lines • 286 kB
"use strict";var e=require("react/jsx-runtime"),t=require("mipd"),r=require("react"),n=require("react-device-detect"),i=require("viem/utils"),a=require("@privy-io/js-sdk-core"),o=require("@privy-io/popup"),s=require("./internal-context-CeWKmK5u.js"),l=require("./EmbeddedWalletConnectingScreen-JRafXI8d.js"),c=require("uuid"),d=require("jose"),u=require("eventemitter3"),h=require("@coinbase/wallet-sdk"),p=require("@privy-io/ethereum"),y=require("./events-context-7-Gs8c_9.js"),m=require("ofetch"),w=require("js-cookie"),g=require("zustand"),v=require("@marsidev/react-turnstile"),f=require("styled-components"),C=require("./useActiveWallet-C5D3a-je.js"),E=require("@heroicons/react/24/outline/DevicePhoneMobileIcon"),A=require("@heroicons/react/24/outline/FingerPrintIcon"),P=require("@heroicons/react/24/outline/PhoneIcon"),k=require("@heroicons/react/24/outline/ShieldCheckIcon"),T=require("@heroicons/react/24/outline/CalendarIcon"),x=require("@heroicons/react/24/outline/ExclamationTriangleIcon"),b=require("viem"),S=require("@headlessui/react"),_=require("@privy-io/urls"),I=require("./usePrivy-BdYU4BZI.js"),U=require("lucide-react"),W=require("./SignRequestScreen-Dy02euV9.js"),R=require("@heroicons/react/24/outline/EnvelopeIcon"),N=require("@heroicons/react/24/outline/QuestionMarkCircleIcon"),O=require("@heroicons/react/24/solid/CheckBadgeIcon"),M=require("@heroicons/react/24/solid/IdentificationIcon"),j=require("@heroicons/react/24/outline/ChevronRightIcon"),F=require("@heroicons/react/24/outline/MinusCircleIcon"),L=require("@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon"),D=require("@heroicons/react/24/outline/ClockIcon"),q=require("@heroicons/react/24/outline/CheckCircleIcon"),B=require("@heroicons/react/24/solid/ShieldCheckIcon"),H=require("@heroicons/react/24/outline/GlobeAltIcon"),z=require("./frame-B2orQ_lK.js"),K=require("@privy-io/routes"),V=require("x402/client"),$=require("@privy-io/api-base"),Y=require("viem/accounts"),G=require("./use-sign-with-user-signer-BtJVKMQr.js"),Z=require("./getEmbeddedConnectedWallet-6TsVZJkD.js");function J(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function X(e){if(e&&"object"==typeof e&&"default"in e)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}require("fast-password-entropy"),require("secure-password-utilities"),require("secure-password-utilities/wordlists"),require("@heroicons/react/24/outline/UserCircleIcon"),require("@heroicons/react/24/outline/ArrowLeftIcon"),require("@heroicons/react/24/outline/ArrowRightIcon"),require("@heroicons/react/24/outline/XMarkIcon"),require("@heroicons/react/20/solid/CheckIcon"),require("@heroicons/react/24/outline/WalletIcon"),require("@heroicons/react/24/outline/ExclamationCircleIcon"),require("@heroicons/react/24/outline/Square2StackIcon"),require("@heroicons/react/24/outline"),require("@tanstack/react-virtual"),require("@heroicons/react/24/outline/CheckIcon"),require("qrcode"),require("@scure/base"),require("@walletconnect/ethereum-provider"),require("@heroicons/react/24/outline/CreditCardIcon"),require("@heroicons/react/24/outline/QrCodeIcon"),require("@heroicons/react/24/solid/ArrowsRightLeftIcon"),require("@heroicons/react/24/outline/InformationCircleIcon"),require("@heroicons/react/24/outline/ClipboardDocumentCheckIcon"),require("@heroicons/react/24/outline/ClipboardDocumentIcon"),require("@heroicons/react/24/outline/ChevronDownIcon"),require("@heroicons/react/24/solid/CheckCircleIcon"),require("@heroicons/react/24/outline/LockClosedIcon"),require("@heroicons/react/24/outline/PencilSquareIcon"),require("@heroicons/react/24/outline/ArrowPathIcon"),require("@heroicons/react/24/outline/EyeIcon"),require("@heroicons/react/24/outline/EyeSlashIcon"),require("@heroicons/react/24/outline/KeyIcon"),require("@heroicons/react/24/outline/ArrowDownTrayIcon"),require("@heroicons/react/24/outline/DocumentDuplicateIcon"),require("@heroicons/react/24/solid/XCircleIcon"),require("tinycolor2");var Q=/*#__PURE__*/J(r),ee=/*#__PURE__*/J(a),te=/*#__PURE__*/X(d),re=/*#__PURE__*/J(u),ne=/*#__PURE__*/J(w),ie=/*#__PURE__*/J(E),ae=/*#__PURE__*/J(A),oe=/*#__PURE__*/J(P),se=/*#__PURE__*/J(k),le=/*#__PURE__*/J(T),ce=/*#__PURE__*/J(x),de=/*#__PURE__*/J(R),ue=/*#__PURE__*/J(N),he=/*#__PURE__*/J(O),pe=/*#__PURE__*/J(M),ye=/*#__PURE__*/J(j),me=/*#__PURE__*/J(F),we=/*#__PURE__*/J(L),ge=/*#__PURE__*/J(D),ve=/*#__PURE__*/J(q),fe=/*#__PURE__*/J(B),Ce=/*#__PURE__*/J(H);function Ee(e){return e?{"privy-ui":"t"}:void 0}class Ae{async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new s.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(s.passwordlessAuthenticatePath,{email:this.meta.email,code:this.meta.emailCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw s.formatApiError(e)}}async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode)throw new s.PrivyClientError("Email and email code must be set prior to calling authenticate.");try{return await this.api.post(s.passwordlessLinkPath,{email:this.meta.email,code:this.meta.emailCode})}catch(e){throw s.formatApiError(e)}}async sendCodeEmail({email:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.email=e),t&&(this.meta.captchaToken=t),!this.meta.email)throw new s.PrivyClientError("Email must be set when initialzing authentication.");let n=Ee(r);try{return await this.api.post(s.passwordlessInitPath,{email:this.meta.email,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw s.formatApiError(e)}}constructor({email:e,captchaToken:t,disableSignup:r}){this.meta={email:e,captchaToken:t,disableSignup:r??!1}}}class Pe extends Ae{async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.email||!this.meta.emailCode||!this.meta.oldAddress)throw new s.PrivyClientError("Email, email code, and an old email address must be set prior to calling update.");try{return await this.api.post(s.updateEmailPath,{oldAddress:this.meta.oldAddress,newAddress:this.meta.email,code:this.meta.emailCode})}catch(e){throw s.formatApiError(e)}}constructor(e,t,r){super({email:t,captchaToken:r}),this.meta={email:t,captchaToken:r,oldAddress:e,disableSignup:!1}}}class ke{get meta(){return this._meta}async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new s.PrivyClientError("Auth flow must be initialized first");try{let e=await this.api.post(s.farcasterAuthenticatePath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});if(!e)throw new s.PrivyClientError("No response from authentication");return e}catch(e){throw s.formatApiError(e)}}async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(s.farcasterLinkPath,{channel_token:this.meta.channelToken,message:this.message,signature:this.signature,fid:this.fid})}catch(e){throw s.formatApiError(e)}}async _startChannelOnce(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");let e=await this.api.post(s.farcasterInitPath,{token:this.captchaToken});n.isMobile&&!n.isIOS&&e.connect_uri&&l.openHref(e.connect_uri,"_blank"),this._meta={...this._meta,connectUri:e.connect_uri,channelToken:e.channel_token}}async initializeFarcasterConnect(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");await this.startChannelOnce.execute()}async _pollForReady(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.channelToken)throw new s.PrivyClientError("Auth flow must be initialized first");let e=await this.api.get(s.farcasterStatusPath,{headers:{"farcaster-channel-token":this.meta.channelToken}});return"completed"===e.state&&(this.message=e.message,this.signature=e.signature,this.fid=e.fid,!0)}constructor(e,t=!1){this._meta={disableSignup:!1},this.captchaToken=e,this.startChannelOnce=new l.RunEffectOnce(this._startChannelOnce.bind(this)),this.pollForReady=new l.RunEffectOnce(this._pollForReady.bind(this)),this._meta.disableSignup=t}}function Te(){return"undefined"!=typeof window&&"chrome-extension:"===window.location.protocol&&"chrome"in window}function xe(){if(!Te())return;let e=window.chrome;return e?.runtime?.id}function be(){if(!Te())return!1;let e=window.chrome;return"function"==typeof e?.identity?.launchWebAuthFlow}async function Se(e){return new Promise(((t,r)=>{be()?window.chrome.identity.launchWebAuthFlow({url:e,interactive:!0},(async e=>{try{let r=function(){if(!Te())return;let e=window.chrome;return e?.runtime?.lastError?.message}();if(r||!e){let e=`WebAuthFlow failed: ${r||"Response URI missing"}`;throw Error(e)}let n=new URL(e),i=xe();if(!i)throw Error("Invalid extension context");if("chrome-extension:"===n.protocol){if(n.hostname!==i)throw Error("Invalid responseUri origin")}else{if("https:"!==n.protocol)throw Error("Invalid responseUri protocol");{let e=n.hostname.split(".");if(3!==e.length||"chromiumapp"!==e[1]||"org"!==e[2]||e[0]!==i)throw Error("Invalid responseUri origin")}}let a=n.searchParams.get("privy_oauth_state"),o=n.searchParams.get("privy_oauth_code");if(!a||!o)throw Error("Invalid responseUri - missing required parameters");t({privyOAuthState:a,privyOAuthCode:o})}catch(e){r(e)}})):r(Error("Chrome identity API not available"))}))}class _e{addCaptchaToken(e){this.meta.captchaToken=e}isActive(){return!!(this.meta.authorizationCode&&this.meta.stateCode&&this.meta.provider)}async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new s.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenticate.");if("undefined"===this.meta.authorizationCode)throw new s.PrivyClientError("User denied confirmation during OAuth flow");let e=l.getCodeVerifier();try{let t=await this.api.post(s.oAuthAuthenticatePath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"});return l.p.del(y.CODE_VERIFIER_KEY),l.p.del(y.HEADLESS_OAUTH_KEY),l.p.del(y.OAUTH_DISABLE_SIGNUP_KEY),t}catch(e){let t=s.formatApiError(e);if(t.privyErrorCode)throw new s.PrivyClientError(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new s.PrivyClientError("Invalid code during oauth flow.",void 0,s.PrivyErrorCode.OAUTH_USER_DENIED);throw new s.PrivyClientError("Invalid code during OAuth flow.",void 0,s.PrivyErrorCode.UNKNOWN_AUTH_ERROR)}}async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.authorizationCode||!this.meta.stateCode)throw new s.PrivyClientError("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling link.");if("undefined"===this.meta.authorizationCode)throw new s.PrivyClientError("User denied confirmation during OAuth flow");let e=l.p.get(y.CODE_VERIFIER_KEY);if(!e)throw new s.PrivyClientError("Authentication error.");try{let t=await this.api.post(s.oAuthLinkPath,{authorization_code:this.meta.authorizationCode,state_code:this.meta.stateCode,code_verifier:e});return l.p.del(y.CODE_VERIFIER_KEY),t}catch(e){throw s.formatApiError(e)}}async getAuthorizationUrl(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.provider)throw new s.PrivyClientError("Provider must be set when initializing OAuth authentication.");let e=l.createCodeVerifier();l.p.put(y.CODE_VERIFIER_KEY,e);let t=l.createStateCode();l.p.put(y.STATE_CODE_KEY,t);let r=await l.deriveCodeChallengeFromCodeVerifier(e);this.meta.withPrivyUi||l.p.put(y.HEADLESS_OAUTH_KEY,!0),this.meta.disableSignup?l.p.put(y.OAUTH_DISABLE_SIGNUP_KEY,!0):l.p.del(y.OAUTH_DISABLE_SIGNUP_KEY);let n=Ee(this.meta.withPrivyUi),i=window.location.href,a=function(){let e=xe();if(e)return`https://${e}.chromiumapp.org`}();a&&(i=a);try{return await this.api.post(s.oAuthInitPath,{provider:this.meta.provider,redirect_to:this.meta.customOAuthRedirectUrl||i,token:this.meta.captchaToken,code_challenge:r,state_code:t},{headers:{...n}})}catch(e){throw s.formatApiError(e)}}constructor(e){this.meta=e}}const Ie=({style:t})=>/*#__PURE__*/e.jsx(Ce.default,{style:{color:"var(--privy-color-error)",...t}});let Ue={google:{name:"Google",component:l.Google},discord:{name:"Discord",component:l.Discord},github:{name:"Github",component:l.Github},linkedin:{name:"LinkedIn",component:l.LinkedIn},twitter:{name:"Twitter",component:l.Twitter},spotify:{name:"Spotify",component:l.Spotify},instagram:{name:"Instagram",component:l.Instagram},tiktok:{name:"Tiktok",component:l.Tiktok},line:{name:"LINE",component:l.Line},twitch:{name:"Twitch",component:l.Twitch},apple:{name:"Apple",component:l.Apple}},We=({iconUrl:e,...t})=>Q.default.createElement("svg",{width:"33",height:"32",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},Q.default.createElement("foreignObject",{x:"2",y:"2",width:"29",height:"28"},Q.default.createElement("img",{src:e,width:"29",height:"28",style:{display:"block",objectFit:"contain",borderRadius:"4px"},alt:"Provider icon"})));const Re=(e,t)=>{if(e in Ue)return Ue[e];if(l.isCustomOAuthProvider(e)&&t){let r=t.find((t=>t.provider===e));if(r)return{name:r.provider_display_name,component:e=>Q.default.createElement(We,{...e,iconUrl:r.provider_icon_url})}}return{name:"Unknown",component:Ie}};function Ne(){let e=new URLSearchParams(window.location.search),t=e.get("privy_oauth_code"),r=e.get("privy_oauth_state"),n=e.get("privy_oauth_provider");if(!t||!r||!n)return{inProgress:!1};let i=!1;try{i=!!window.opener.location.origin}catch{}return{inProgress:!0,authorizationCode:t,stateCode:r,provider:n,withPrivyUi:!l.p.get(y.HEADLESS_OAUTH_KEY),popupFlow:null!==window.opener&&i,disableSignup:!!l.p.get(y.OAUTH_DISABLE_SIGNUP_KEY)}}class Oe{async initRegisterFlow(e){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!0,this.meta.initRegisterResponse=await this.initRegisterOnce.execute(e)}async initAuthenticationFlow(e){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");this.authenticateForRegistration=!1,this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute(e)}async initLinkFlow(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");this.meta.initLinkResponse=await this.initLinkOnce.execute()}async register(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new s.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initRegisterResponse||(this.meta.initRegisterResponse=await this.initRegisterOnce.execute());try{let t=this.meta.initRegisterResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(s.passkeyRegisterPath,{relying_party:this.meta.initRegisterResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new s.PrivyClientError("Passkey request timed out or rejected by user.",void 0,s.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw s.formatApiError(e)}}async authenticate(){if(this.authenticateForRegistration)return this.register();let e=await import("@simplewebauthn/browser");if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new s.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initAuthenticateResponse||(this.meta.initAuthenticateResponse=await this.initAuthenticateOnce.execute());let t=this.meta.allowedCredentialsIds?.map((e=>({type:"public-key",id:e})))??this.meta.initAuthenticateResponse.options.allow_credentials;try{let r=await e.startAuthentication({optionsJSON:this._transformInitAuthenticateOptionsToCamelCase({...this.meta.initAuthenticateResponse.options,allow_credentials:t})});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(s.passkeyAuthenticatePath,{relying_party:this.meta.initAuthenticateResponse.relying_party,challenge:this.meta.initAuthenticateResponse.options.challenge,authenticator_response:this._transformAuthenticationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new s.PrivyClientError("Passkey request timed out or rejected by user.",void 0,s.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw s.formatApiError(e)}}async link(){let e=await import("@simplewebauthn/browser");if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!e.browserSupportsWebAuthn())throw new s.PrivyClientError("WebAuthn is not supported in this browser");this.meta.initLinkResponse||(this.meta.initLinkResponse=await this.initLinkOnce.execute());try{let t=this.meta.initLinkResponse.options,r=await e.startRegistration({optionsJSON:this._transformInitLinkOptionsToCamelCase(t)});return this.meta.setPasskeyAuthState?.({status:"submitting-response"}),await this.api.post(s.passkeyLinkPath,{relying_party:this.meta.initLinkResponse.relying_party,authenticator_response:this._transformRegistrationResponseToSnakeCase(r)})}catch(e){if("NotAllowedError"===e.name)throw new s.PrivyClientError("Passkey request timed out or rejected by user.",void 0,s.PrivyErrorCode.PASSKEY_NOT_ALLOWED);throw s.formatApiError(e)}}async _initRegisterOnce(e){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");let t=Ee(e);return await this.api.post(s.passkeyInitRegisterPath,{token:this.meta.captchaToken},{headers:{...t}})}async _initAuthenticateOnce(e){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");let t=Ee(e);return await this.api.post(s.passkeyInitAuthenticatePath,{token:this.meta.captchaToken},{headers:{...t}})}async _initLinkOnce(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");return await this.api.post(s.passkeyInitLinkPath,{})}_transformInitLinkOptionsToCamelCase(e){return{rp:e.rp,user:{id:e.user.id,name:e.user.name,displayName:e.user.display_name},challenge:e.challenge,pubKeyCredParams:e.pub_key_cred_params.map((e=>({type:e.type,alg:e.alg}))),timeout:e.timeout,excludeCredentials:e.exclude_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports}))),authenticatorSelection:{authenticatorAttachment:e.authenticator_selection?.authenticator_attachment,requireResidentKey:e.authenticator_selection?.require_resident_key,residentKey:e.authenticator_selection?.resident_key,userVerification:e.authenticator_selection?.user_verification},attestation:e.attestation,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props?.rk,hmacCreateSecret:e.extensions?.hmac_create_secret},hints:this.meta.hints}}_transformRegistrationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,attestation_object:e.response.attestationObject,authenticator_data:e.response.authenticatorData},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}_transformInitAuthenticateOptionsToCamelCase(e){return{rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification}}_transformAuthenticationResponseToSnakeCase(e){return{id:e.id,raw_id:e.rawId,response:{client_data_json:e.response.clientDataJSON,authenticator_data:e.response.authenticatorData,signature:e.response.signature,user_handle:e.response.userHandle},authenticator_attachment:e.authenticatorAttachment,client_extension_results:{app_id:e.clientExtensionResults.appid,cred_props:e.clientExtensionResults.credProps,hmac_create_secret:e.clientExtensionResults.hmacCreateSecret},type:e.type}}constructor({captchaToken:e,setPasskeyAuthState:t,hints:r}){this.authenticateForRegistration=!1,this.initRegisterOnce=new l.RunEffectOnce(this._initRegisterOnce.bind(this)),this.initAuthenticateOnce=new l.RunEffectOnce(this._initAuthenticateOnce.bind(this)),this.initLinkOnce=new l.RunEffectOnce(this._initLinkOnce.bind(this)),this.meta={captchaToken:e,setPasskeyAuthState:t,hints:r}}}class Me{async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new s.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(s.passwordlessSmsAuthenticatePath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode,mode:this.meta.disableSignup?"no-signup":"login-or-sign-up"})}catch(e){throw s.formatApiError(e)}}async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode)throw new s.PrivyClientError("phone number and sms code must be set prior to calling authenticate.");try{return await this.api.post(s.passwordlessSmsLinkPath,{phoneNumber:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw s.formatApiError(e)}}async sendSmsCode({phoneNumber:e,captchaToken:t,withPrivyUi:r}){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(e&&(this.meta.phoneNumber=e),t&&(this.meta.captchaToken=t),!this.meta.phoneNumber)throw new s.PrivyClientError("phone nNumber must be set when initialzing authentication.");let n=Ee(r);try{return await this.api.post(s.passwordlessSmsInitPath,{phoneNumber:this.meta.phoneNumber,token:this.meta.captchaToken},{headers:{...n}})}catch(e){throw s.formatApiError(e)}}constructor({phoneNumber:e,captchaToken:t,disableSignup:r}){this.meta={phoneNumber:e,captchaToken:t,disableSignup:r??!1}}}class je extends Me{async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");if(!this.meta.phoneNumber||!this.meta.smsCode||!this.meta.oldPhoneNumber)throw new s.PrivyClientError("Phone number, sms code, and an old phone number must be set prior to calling update.");try{return await this.api.post(s.updatePhonePath,{old_phone_number:this.meta.oldPhoneNumber,new_phone_number:this.meta.phoneNumber,code:this.meta.smsCode})}catch(e){throw s.formatApiError(e)}}constructor(e,t,r){super({phoneNumber:t,captchaToken:r}),this.meta={phoneNumber:t,captchaToken:r,oldPhoneNumber:e,disableSignup:!1}}}class Fe{static parse(e){try{return new Fe(e)}catch(e){return null}}static throwIfNotWellFormedJwt(e){return te.decodeJwt(e),e}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){return Date.now()>=1e3*(this.expiration-e)}constructor(e){this.value=e,this._decoded=te.decodeJwt(e)}}class Le extends Fe{static parse(e){try{return new Le(e)}catch(e){return null}}get appId(){return this._decoded.aid?this._decoded.aid:this.audience}}let De,qe;class Be extends l.EthereumWalletConnector{async initialize(){await this.importPromise,await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:l.BASE_ACCOUNT_DATA_URI,id:"com.coinbase.wallet"}}async promptConnection(){try{await this.importPromise;let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new s.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw l.formatConnectorError(e)}}constructor(e,t,r,n,i){super("base_account",e,t,r),this.connectorType="base_account",this.walletClientType="base_account",this.displayName="Base",this.setBaseAccountSdk=i,this.proxyProvider=new l.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.baseAccountConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},De?(this.proxyProvider.setWalletProvider(De.getProvider()),this.setBaseAccountSdk(De),console.log("Base Account SDK Initialized")):this.importPromise=import("@base-org/account").then((({createBaseAccountSDK:e})=>{De=e(this.baseAccountConfig),this.proxyProvider.setWalletProvider(De.getProvider()),this.setBaseAccountSdk(De),console.log("Base Account SDK Initialized")})).catch(console.error)}}let He=[1,11155111,137,10,8453,84532,42161,7777777,43114,56];class ze extends l.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}disconnect(){this.proxyProvider.walletProvider.disconnect(),this.onDisconnect()}get walletBranding(){return{name:this.displayName,icon:l.COINBASE_WALLET_DATA_URI,id:"com.coinbase.wallet"}}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new s.PrivyConnectorError("Unable to retrieve accounts");this.connected=!0,await this.syncAccounts([e[0]])}catch(e){throw l.formatConnectorError(e)}}updateConnectionPreference(e){this.coinbaseWalletConfig={...this.coinbaseWalletConfig,preference:{...this.coinbaseWalletConfig.preference,options:e}},this.walletClientType="smartWalletOnly"===e?"coinbase_smart_wallet":"coinbase_wallet",qe=h.createCoinbaseWalletSDK({...this.coinbaseWalletConfig}),this.proxyProvider.setWalletProvider(qe.getProvider())}constructor(e,t,r,n){if(super("coinbase_wallet",e,t,r),this.connectorType="coinbase_wallet",this.displayName="Coinbase Wallet",this.proxyProvider=new l.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.coinbaseWalletConfig={...n,appChainIds:[t.id].concat(e.map((e=>e.id)))},this.walletClientType="smartWalletOnly"===this.coinbaseWalletConfig.preference?.options?"coinbase_smart_wallet":"coinbase_wallet","coinbase_smart_wallet"===this.walletClientType&&(this.displayName="Coinbase Smart Wallet"),!qe){let e="eoaOnly"!==this.coinbaseWalletConfig.preference?.options?(this.coinbaseWalletConfig.appChainIds??[]).filter((e=>!He.includes(e))):[];e.length>0&&!e.every((e=>a.DEFAULT_SUPPORTED_CHAIN_IDS.has(e)))&&console.info(`The configured chains are not supported by Coinbase Smart Wallet: ${e.join(", ")}`),qe=h.createCoinbaseWalletSDK(this.coinbaseWalletConfig)}this.proxyProvider.setWalletProvider(qe.getProvider())}}class Ke extends l.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return await this.isConnected()?(await this.proxyProvider.request({method:"wallet_switchEthereumChain",params:[l.toHex(e?.chainId||"0x1")]}),this.getConnectedWallet()):null}get walletBranding(){return{name:"Privy Wallet",icon:l.Blobby,id:"io.privy.wallet"}}disconnect(){this.connected=!1}async promptConnection(){}constructor({provider:e,chains:t,defaultChain:r,rpcConfig:n,imported:i,walletIndex:a}){super("privy",t,r,n),this.connectorType="embedded",this.proxyProvider=e,this.walletIndex=a,i&&(this.connectorType="embedded_imported"),this.subscribeListeners()}}const Ve=["eth_sign","eth_populateTransactionRequest","eth_signTransaction","personal_sign","eth_signTypedData_v4","csw_signUserOperation","secp256k1_sign"];class $e extends Error{constructor(e,t,r){super(e),this.code=t,this.data=r}}class Ye extends re.default{async handleSendTransaction(e){if(!e.params||!Array.isArray(e.params))throw new $e(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await mi()||!this.address)throw new $e("Disconnected",4900);let{hash:r}=await fi(t,{address:this.address});return r}async handleSignTransaction(e){if(!e.params||!Array.isArray(e.params))throw new $e(`Invalid params for ${e.method}`,4200);let t=e.params[0];if(!await mi()||!this.address)throw new $e("Disconnected",4900);let{signature:r}=await vi(t,{address:this.address});return r}handleSwitchEthereumChain(e){let t;if(!e.params||!Array.isArray(e.params))throw new $e(`Invalid params for ${e.method}`,4200);if("string"==typeof e.params[0])t=e.params[0];else{if(!("chainId"in e.params[0])||"string"!=typeof e.params[0].chainId)throw new $e(`Invalid params for ${e.method}`,4200);t=e.params[0].chainId}this.chainId=Number(t),this.publicClient=l.getPublicClient(this.chainId,this.chains,this.rpcConfig,{appId:this.appId}),this.emit("chainChanged",t)}async handlePersonalSign(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for personal_sign");let t=e.params[0],r=e.params[1],{signature:n}=await wi({message:t},{address:r});return n}async handleSignedTypedData(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_signTypedData_v4");let t=e.params[0],r="string"==typeof e.params[1]?JSON.parse(e.params[1]):e.params[1],{signature:n}=await gi(l.generateTypedDataWithDomainType(r),{address:t});return n}async handleEstimateGas(e){if(!e.params||!Array.isArray(e.params))throw Error("Invalid params for eth_estimateGas");delete e.params[0].gasPrice,delete e.params[0].maxFeePerGas,delete e.params[0].maxPriorityFeePerGas;let t={...e.params[0],chainId:l.toHex(this.chainId)};return await this.publicClient.estimateGas({account:t.from??this.address,...p.toViemTransactionSerializable(t)})}async request(e){switch(console.debug("Embedded1193Provider.request() called with args",e),e.method){case"eth_accounts":case"eth_requestAccounts":return this.address?[this.address]:[];case"eth_chainId":return l.toHex(this.chainId);case"eth_estimateGas":return this.handleEstimateGas(e);case"eth_sendTransaction":return this.handleSendTransaction(e);case"eth_signTransaction":return this.handleSignTransaction(e);case"wallet_switchEthereumChain":return this.handleSwitchEthereumChain(e);case"personal_sign":return this.handlePersonalSign(e);case"eth_signTypedData_v4":return this.handleSignedTypedData(e)}if(!(e=>Ve.includes(e))(e.method))return this.publicClient.request({method:e.method,params:e.params});{let t=await mi();if(await Ci({address:this.address}),!t||!this.address)throw new $e("Disconnected",4900);try{let r={method:e.method,params:e.params},n=this.walletAccount;return n&&l.getIsUnifiedWallet(n)?this.handleWalletApiRequest(r,n,t):(await this.walletProxy.rpc({accessToken:t,entropyId:this.entropyId,entropyIdVerifier:this.entropyIdVerifier,chainType:"ethereum",hdWalletIndex:this.walletIndex,request:r})).response.data}catch(e){throw console.error(e),new $e("Disconnected",4900)}}}async handleWalletApiRequest(e,t,r){let n=this.privyClient;if(!n)throw new $e("Disconnected",4900);if("secp256k1_sign"===e.method){let i=await a.rpc(n,(async({message:e})=>this.walletProxy.signWithUserSigner({accessToken:r,message:e})),{chain_type:"ethereum",method:"secp256k1_sign",wallet_id:t.id,params:{hash:e.params[0]}});if("secp256k1_sign"!==i.method)throw new $e(`Invalid params for ${e.method}`,4200);return i.data.signature}throw new $e(`Method not supported: ${e.method}`,4200)}constructor({walletProxy:e,address:t,entropyId:r,entropyIdVerifier:n,rpcConfig:i,chains:a,appId:o,chainId:s=1,walletIndex:c,privyClient:d,walletAccount:u}){super(),this.walletProxy=e,this.address=t,this.entropyId=r,this.entropyIdVerifier=n,this.chainId=s,this.rpcConfig=i,this.chains=a,this.publicClient=l.getPublicClient(s,this.chains,i,{appId:o}),this.rpcTimeoutDuration=l.getRpcTimeout(i,"privy"),this.appId=o,this.walletIndex=c,this.privyClient=d,this.walletAccount=u}}function Ge(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}var Ze=0;class Je extends l.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return{name:this.providerDetail.info.name,icon:this.providerDetail.info.icon,id:this.providerDetail.info.rdns}}disconnect(){console.warn(`Programmatic disconnect with ${this.providerDetail.info.name} is not yet supported.`)}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new s.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw l.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i||"unknown",e,t,r),this.connectorType="injected",this.proxyProvider=new l.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.providerDetail=n;let a=n.provider;this.proxyProvider.setWalletProvider(a)}}var Xe="__private_"+Ze+++"__walletBranding";class Qe extends l.EthereumWalletConnector{async initialize(){await this.syncAccounts(),this.initialized=!0,this.emit("initialized")}async connect(e){return e.showPrompt&&await this.promptConnection(),await this.isConnected()?this.getConnectedWallet():null}get walletBranding(){return Ge(this,Xe)[Xe]??{name:"Browser Extension",icon:l.BrowserExtensionWallet,id:"extension"}}disconnect(){console.warn("Programmatic disconnect with browser wallets is not yet supported.")}async promptConnection(){try{let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new s.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw l.formatConnectorError(e)}}constructor(e,t,r,n,i){super(i??"unknown",e,t,r),Object.defineProperty(this,Xe,{writable:!0,value:void 0}),this.connectorType="injected",this.proxyProvider=new l.PrivyProxyProvider(void 0,this.rpcTimeoutDuration),this.subscribeListeners(),this.proxyProvider.setWalletProvider(n),"metamask"===i?Ge(this,Xe)[Xe]={name:"MetaMask",icon:l.Metamask,id:"io.metamask"}:"phantom"===i&&(Ge(this,Xe)[Xe]={name:"Phantom",icon:l.Phantom,id:"phantom"})}}class et extends Je{disconnect(){console.warn("MetaMask does not support programmatic disconnect.")}async promptConnection(){try{n.isMobile||await this.proxyProvider.request({method:"wallet_requestPermissions",params:[{eth_accounts:{}}]});let e=await this.proxyProvider.request({method:"eth_requestAccounts"});if(!e||0===e.length||!e[0])throw new s.PrivyConnectorError("Unable to retrieve accounts");await this.syncAccounts([e[0]])}catch(e){throw l.formatConnectorError(e)}}}class tt extends re.default{get wallets(){let e=new Set;return this.walletConnectors.flatMap((e=>e.wallets)).sort(((e,t)=>e.connectedAt&&t.connectedAt?t.connectedAt-e.connectedAt:0)).filter((t=>{let r=`${t.address}${t.walletClientType}${t.connectorType}${t.meta.id}`;return!e.has(r)&&(e.add(r),!0)}))}async initialize(e){if(this.initialized&&!e||(e&&this.removeAllConnectors(),this.externalWalletConfig.disableAllExternalWallets))return;let t=l.detectInjectedConnectors({store:this.store,walletList:this.walletList,externalWalletConfig:this.externalWalletConfig,walletChainType:this.walletChainType}).then((e=>{e.forEach((({type:e,eip6963InjectedProvider:t,legacyInjectedProvider:r})=>{this.createEthereumWalletConnector({connectorType:"injected",walletClientType:e,providers:{eip6963InjectedProvider:t,legacyInjectedProvider:r}})}))}));for(let e of(this.walletList.includes("coinbase_wallet")&&this.createEthereumWalletConnector({connectorType:"coinbase_wallet",walletClientType:"coinbase_wallet"}),this.walletList.includes("base_account")&&this.createEthereumWalletConnector({connectorType:"base_account",walletClientType:"base_account"}),Object.values(l.mobileWalletsConfig)))!e.isInstalled&&this.walletList.includes(e.client)&&(["ethereum-only","ethereum-and-solana"].includes(this.walletChainType)&&e.chainTypes.includes("ethereum")&&this.createEthereumWalletConnector({connectorType:"null",walletClientType:e.client,walletConfig:e}),["ethereum-and-solana","solana-only"].includes(this.walletChainType)&&e.chainTypes.includes("solana")&&this.addSolanaWalletConnector(new l.SolanaNullConnector({id:e.client,name:e.name})));this.externalWalletConfig.walletConnect.enabled&&(this.walletList.includes("wallet_connect_qr")||l.shouldFetchWcRegistryListings(this.walletList))&&"solana-only"!==this.walletChainType&&this.createEthereumWalletConnector({connectorType:"wallet_connect_v2",walletClientType:"unknown"});let r=this.walletList.includes("wallet_connect_qr_solana"),n=this.externalWalletConfig.solana.connectors?.get()||[],i=async e=>{if(!r)return;let t=e.find((e=>"walletconnect_solana"===e.walletBranding?.id));t&&t.wallet&&await t.wallet.initialize({walletConnectCloudProjectId:this.walletConnectCloudProjectId,privyAppName:this.privyAppName})};i(n),n.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector),this.externalWalletConfig.solana.connectors?._setOnConnectorsUpdated?.((e=>{i(e),e?.filter((e=>r||"walletconnect_solana"!==e.walletBranding?.id)).forEach(this.addSolanaWalletConnector)})),await t,this.initialized=!0}findWalletConnector(e,t,r){return"wallet_connect_v2"===e?this.walletConnectors.filter(l.isEthereumWalletConnector).find((t=>t.connectorType===e&&(!r||t.wallets.some((e=>e.address===r)))))??null:this.walletConnectors.filter(l.isEthereumWalletConnector).find((n=>n.connectorType===e&&n.walletClientType===t&&(!r||n.wallets.some((e=>e.address===r)))))??null}findSolanaWalletConnector(e){return this.walletConnectors.filter(l.isSolanaWalletConnector).find((t=>"unknown"===t.walletClientType?t.walletBranding.id===e:t.walletClientType===e))??null}findEmbeddedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded"===e.connectorType))}findImportedWalletConnectors(){return this.walletConnectors.filter((e=>"embedded_imported"===e.connectorType))}onInitialized(e){e.wallets.forEach((e=>{let t=this.storedConnections.find((t=>t.address===e.address&&t.connectorType===e.connectorType&&("solana"===e.type&&"unknown"===t.walletClientType&&"unknown"===e.walletClientType?e.meta.id===t.id:t.walletClientType===e.walletClientType)));t&&(e.connectedAt=t.connectedAt)})),this.emit("walletsUpdated"),this.emit("connectorInitialized")}onWalletsUpdated(e){e.initialized&&this.emit("walletsUpdated")}addEmbeddedWalletConnectors({walletProxy:e,user:t,embeddedWallets:r,defaultChain:n,appId:i,privyClient:a}){let{entropyId:o,entropyIdVerifier:s}=l.getEntropyDetailsForUser(t);for(let t of r){let r=this.findEmbeddedWalletConnectors().find((e=>e.walletIndex===t.walletIndex));if(r&&l.isEthereumWalletConnector(r))r.proxyProvider.walletProxy=e;else{let r=new Ke({provider:new Ye({walletProxy:e,address:t.address,entropyId:o,entropyIdVerifier:s,rpcConfig:this.rpcConfig,chains:this.chains,appId:i,chainId:n.id,walletIndex:t.walletIndex,privyClient:a,walletAccount:t}),chains:this.chains,defaultChain:n,rpcConfig:this.rpcConfig,imported:!1,walletIndex:t.walletIndex});this.addWalletConnector(r)}}}addImportedWalletConnector(e,t,r,n){let i=this.findWalletConnector("embedded_imported","privy",t);if(i&&l.isEthereumWalletConnector(i))i.proxyProvider.walletProxy=e;else{let i=new Ke({provider:new Ye({walletProxy:e,address:t,entropyId:t,entropyIdVerifier:"ethereum-address-verifier",walletIndex:0,rpcConfig:this.rpcConfig,chains:this.chains,appId:n,chainId:r.id}),chains:this.chains,walletIndex:0,defaultChain:r,rpcConfig:this.rpcConfig,imported:!0});this.addWalletConnector(i)}}removeEmbeddedWalletConnectors(){this.walletConnectors=this.walletConnectors.filter((e=>"embedded"!==e.connectorType)),this.storedConnections=l.loadConnectionHistory(),this.emit("walletsUpdated")}removeImportedWalletConnectors(){let e=this.findImportedWalletConnectors();e.length&&(e.forEach((e=>{let t=this.walletConnectors.indexOf(e);this.walletConnectors.splice(t,1)})),this.storedConnections=l.loadConnectionHistory(),this.emit("walletsUpdated"))}async createEthereumWalletConnector({connectorType:e,walletClientType:t,providers:r,walletConfig:n}){let i=this.findWalletConnector(e,t);if(i&&l.isEthereumWalletConnector(i))return i instanceof l.WalletConnectV2WalletConnector&&i.resetConnection(t),i;let a=(()=>"injected"!==e?"coinbase_wallet"===e?new ze(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.coinbaseWallet.config):"base_account"===e?new Be(this.chains,this.defaultChain,this.rpcConfig,this.externalWalletConfig.baseAccount.config,this.setBaseAccountSdk):"null"!==e?new l.WalletConnectV2WalletConnector({walletConnectCloudProjectId:this.walletConnectCloudProjectId,rpcConfig:this.rpcConfig,chains:this.chains,defaultChain:this.defaultChain,shouldEnforceDefaultChainOnConnect:this.shouldEnforceDefaultChainOnConnect,privyAppId:this.privyAppId,privyAppName:this.privyAppName,walletClientType:t}):n?new l.EthereumNullConnector({id:n.client,name:n.name,defaultChain:this.defaultChain,walletClientType:n.client}):null:"metamask"===t&&r?.eip6963InjectedProvider?new et(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,"metamask"):"metamask"===t&&r?.legacyInjectedProvider?new Qe(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"metamask"):"phantom"===t&&r?.legacyInjectedProvider?new Qe(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider,"phantom"):r?.legacyInjectedProvider&&"unknown_browser_extension"===t?new Qe(this.chains,this.defaultChain,this.rpcConfig,r?.legacyInjectedProvider):r?.eip6963InjectedProvider?new Je(this.chains,this.defaultChain,this.rpcConfig,r?.eip6963InjectedProvider,t):void 0)();return a&&this.addWalletConnector(a),a||null}addWalletConnector(e){this.walletConnectors.push(e),e.on("initialized",(()=>this.onInitialized(e))),e.on("walletsUpdated",(()=>this.onWalletsUpdated(e))),e.initialize().catch((e=>{console.debug("Failed to initialize connector",e)}))}setWalletList(e){this.walletList=e,this.initialized&&this.initialize(!0).catch(console.error)}removeAllConnectors(){for(let e of this.walletConnectors)e.removeAllListeners();this.walletConnectors=[]}constructor(e,t,r,n,i,a,o,s,c,d,u,h){super(),this.addSolanaWalletConnector=async e=>{let t=this.findSolanaWalletConnector(e.walletClientType);if(!t||"null"===t.connectorType){if("null"===t?.connectorType){let e=this.walletConnectors.indexOf(t);this.walletConnectors.splice(e,1)}this.addWalletConnector(e)}},this.privyAppId=e,this.walletConnectCloudProjectId=t,this.rpcConfig=r,this.chains=n,this.defaultChain=i,this.walletConnectors=[],this.initialized=!1,this.store=a,this.walletList=o,this.shouldEnforceDefaultChainOnConnect=s,this.externalWalletConfig=c,this.privyAppName=d,this.walletChainType=h||"ethereum-only",this.setBaseAccountSdk=u,this.storedConnections=l.loadConnectionHistory()}}let rt=[s.sessionsRefreshPath,s.sessionsLogoutPath,s.analyticsEventsPath];class nt{async get(e,t){try{return await this.baseFetch(e,t)}catch(e){throw s.formatApiError(e)}}async post(e,t,r){try{return await this.baseFetch(e,{method:"POST",...t?{body:t}:{},...r})}catch(e){throw s.formatApiError(e)}}async delete(e,t){try{return await this.baseFetch(e,{method:"DELETE",...t})}catch(e){throw s.formatApiError(e)}}constructor({appId:e,appClientId:t,client:r,defaults:n}){this.appId=e,this.appClientId=t,this.clientAnalyticsId=r.clientAnalyticsId,this.sdkVersion=y.VERSION,this.client=r,this.defaults=n,this.fallbackApiUrl=r.fallbackApiUrl,this.baseFetch=m.ofetch.create({baseURL:this.defaults.baseURL,timeout:this.defaults.timeout,retry:3,retryDelay:500,retryStatusCodes:[408,409,425,500,502,503,504],credentials:"include",onRequest:async({request:e,options:t})=>{let r=new Headers(t.headers);r.set("privy-app-id",this.appId),this.appClientId&&r.set("privy-client-id",this.appClientId),r.set("privy-ca-id",this.clientAnalyticsId||""),r.set("privy-client",`react-auth:${this.sdkVersion}`);let n=rt.includes(e.toString());if(!r.has("authorization")){let e=await this.client.getAccessToken({disableAutoRefresh:n});null!==e&&r.set("authorization",`Bearer ${e}`)}t.headers=r,t.retryDelay&&"number"==typeof t.retryDelay&&(t.retryDelay=3*t.retryDelay)},onRequestError:({error:e})=>{if(e instanceof DOMException&&"AbortError"===e.name)throw new s.PrivyTimeoutError}})}}let it=/paymaster\.biconomy\.io\/api/i,at={mode:"SPONSORED",calculateGasLimits:!0,expiryDuration:300,sponsorshipInfo:{webhookData:{},smartAccountInfo:{name:"BICONOMY",version:"2.0.0"}}};const ot=(e,t)=>e&&it.test(e)?at:t&&t.policy_id?{policyId:t.policy_id}:void 0,st=e=>({rpId:e.rp_id,challenge:e.challenge,allowCredentials:e.allow_credentials?.map((e=>({id:e.id,type:e.type,transports:e.transports})))||[],timeout:e.timeout,extensions:{appid:e.extensions?.app_id,credProps:e.extensions?.cred_props,hmacCreateSecret:e.extensions?.hmac_create_secret},userVerification:e.user_verification});class lt{async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(s.customJwtAccountAuthenticatePath,{token:this.meta.token})}catch(e){throw s.formatApiError(e)}}async link(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(s.customJwtAccountLinkPath,{token:this.meta.token})}catch(e){throw s.formatApiError(e)}}constructor(e){this.meta={token:e}}}class ct{getOrCreateGuestCredential(e){let t=y.getGuestCredentialStorageKey(e);if(l.e$1()){if(l.p.get(t))return l.p.get(t);{let e=d.base64url.encode(l.randomBytes(32));return l.p.put(t,e),e}}return d.base64url.encode(l.randomBytes(32))}async authenticate(){if(!this.api)throw new s.PrivyClientError("Auth flow has no API instance");try{return await this.api.post(s.guestAccountAuthenticatePath,{guest_credential:this.meta.guestCredential})}catch(e){throw s.formatApiError(e)}}async link(){throw Error("Linking is not supported for the guest flow")}constructor(e){this.meta={guestCredential:this.getOrCreateGuestCredential(e)}}}function dt(){return!(n.isSafari&&window.location.origin.startsWith("http://localhost"))}const ut=g.create((()=>({identityToken:null})));var ht,pt=((ht={}).PRIVY="privy_access_token",ht.CUSTOMER="customer_access_token",ht);class yt{get token(){return this.privyAccessToken||this.customerAccessToken}getToken(e){return"privy_access_token"===e?this.privyAccessToken:this.customerAccessToken}get customerAccessToken(){return this._getToken(y.CUSTOMER_ACCESS_TOKEN_STORAGE_KEY)}get privyAccessToken(){return this._getToken(y.PRIVY_ACCESS_TOKEN_STORAGE_KEY)}_getToken(e){try{let t=l.p.get(e);return"string"==typeof t?Fe.throwIfNotWellFormedJwt(t):null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=l.p.get(y.REFRESH_TOKEN_STORAGE_KEY);return"string"==typeof e?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}getProviderAccessToken(e){try{let t=l.p.get(y.getProviderAccessTokenStorageKey(e));if("string"!=typeof t)return null;{let r=new Fe(t);return r.isExpired()?(l.p.del(y.getProviderAccessTokenStorageKey(e)),null):r.value}}catch(e){return console.error(e),null}}get mightHaveServerCookies(){try{let e=ne.default.get(y.SESSION_COOKIE_KEY);return void 0!==e&&e.length>0}catch(e){console.error(e)}return!1}hasRefreshCredentials(e="privy_access_token"){let t="string"==typeof this.getToken(e),r="string"==typeof this.refreshToken&&this.refreshToken!==y.DEPRECATED_REFRESH_TOKEN;return this.mightHaveServerCookies||t&&r}hasActiveAccessToken(e){let t=Fe.parse(this.getToken(e));return null!==t&&!t.isExpired(30)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}destroy(){return this.destroyOnce.execute()}storeProviderAccessToken(e,t){"string"==typeof t?l.p.put(y.getProviderAccessTokenStorageKey(e),t):l.p.del(y.getProviderAccessTokenStorageKey(e))}updateIdentityToken(e){"string"==typeof e?this.storeIdentityToken(e):this.clearIdentityToken()}async _authenticate(e){try{let t=await e.authenticate(),{user:r,is_new_user:n,oauth_tokens:i}=t;this.handleTokenResponse(t);let a=i?{provider:i.provider,accessToken:i.access_token,accessTokenExpiresInSeconds:i.access_token_expires_in_seconds,refreshToken:i.refresh_token,refreshTokenExpiresInSeconds:i.refresh_token_expires_in_seconds,scopes:i.scopes}:void 0;return this._trackAuthenticateEvents(e,n),{user:l.convertUserResponseToUser(r),isNewUser:n,oAuthTokens:a}}catch(e){throw console.warn("Error authenticating session"),s.formatPrivyError(e)}}_trackAuthenticateEvents(e,t){let r=function(e){return e instanceof Ae?"email":e instanceof Me?"sms":e instanceof l.SiweFlow?"siwe":e instanceof ct?"guest":e instanceof lt?"custom_auth":e instanceof _e?e.meta.provider:null}(e);r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate",payload:{method:r,isNewUser:t}}),"siwe"===r&&this.client&&this.client.createAnalyticsEvent({eventName:"sdk_authenticate_siwe",payload:{connectorType:e.meta.connectorType,walletClientType:e.meta.walletClientType}})}async _link(e){try{let t=await e.link(),r=t.oauth_tokens,n=r?{provider:r.provider,accessToken:r.access_token,accessTokenExpiresInSeconds:r.access_token_expires_in_seconds,refreshToken:r.refresh_token,refreshTokenExpiresInSeconds:r.refresh_token_expires_in