@stytch/vanilla-js 6.0.8 → 6.0.9

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 (31) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cjs/{StytchSSRProxy-CYec4c7H.js → StytchSSRProxy-DjO95TII.js} +2 -2
  3. package/dist/cjs/{StytchSSRProxy-CYec4c7H.js.map → StytchSSRProxy-DjO95TII.js.map} +1 -1
  4. package/dist/cjs/b2b/index.cjs +2 -2
  5. package/dist/cjs/b2b/index.headless.cjs +1 -1
  6. package/dist/cjs/index.cjs +3 -3
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/index.headless.cjs +1 -1
  9. package/dist/cjs/{shadcn-DyU73sgU.js → shadcn-DnwRqCY0.js} +2 -2
  10. package/dist/cjs/{shadcn-DyU73sgU.js.map → shadcn-DnwRqCY0.js.map} +1 -1
  11. package/dist/cjs-dev/{StytchSSRProxy-DzmpC9_x.js → StytchSSRProxy-t6BtsVJa.js} +2 -2
  12. package/dist/cjs-dev/{StytchSSRProxy-DzmpC9_x.js.map → StytchSSRProxy-t6BtsVJa.js.map} +1 -1
  13. package/dist/cjs-dev/b2b/index.cjs +2 -2
  14. package/dist/cjs-dev/b2b/index.headless.cjs +1 -1
  15. package/dist/cjs-dev/index.cjs +3 -3
  16. package/dist/cjs-dev/index.cjs.map +1 -1
  17. package/dist/cjs-dev/index.headless.cjs +1 -1
  18. package/dist/cjs-dev/{shadcn-B1WlFgq_.js → shadcn-C7p3HE31.js} +2 -2
  19. package/dist/cjs-dev/{shadcn-B1WlFgq_.js.map → shadcn-C7p3HE31.js.map} +1 -1
  20. package/dist/esm/packages/web/src/NetworkClient.mjs +1 -1
  21. package/dist/esm/packages/web/src/ui/b2c/screens/Secondary/usePasswordlessAuthenticate.mjs +1 -1
  22. package/dist/esm/packages/web/src/ui/b2c/screens/Secondary/usePasswordlessAuthenticate.mjs.map +1 -1
  23. package/dist/esm-dev/packages/web/src/NetworkClient.mjs +1 -1
  24. package/dist/esm-dev/packages/web/src/ui/b2c/screens/Secondary/usePasswordlessAuthenticate.mjs +1 -1
  25. package/dist/esm-dev/packages/web/src/ui/b2c/screens/Secondary/usePasswordlessAuthenticate.mjs.map +1 -1
  26. package/dist/iife/b2b/index.headless.js +1 -1
  27. package/dist/iife/b2b/index.js +1 -1
  28. package/dist/iife/index.headless.js +1 -1
  29. package/dist/iife/index.js +2 -2
  30. package/dist/iife/index.js.map +1 -1
  31. package/package.json +1 -1
@@ -12,7 +12,7 @@ See ${i} for more information.
12
12
  `+(a?`request_id: ${a}
13
13
  `:"")+(o?`Details:
14
14
  `+JSON.stringify(o)+"\n":"")),this.error_type=r,this.error_message=s,this.error_url=i,this.request_id=a,this.status_code=t,this.error_details=o}static from(e){return e instanceof d?e:e&&"object"==typeof e&&"number"==typeof e.status_code&&"string"==typeof e.error_type&&"string"==typeof e.error_message&&"string"==typeof e.error_url?new d({status_code:e.status_code,error_type:e.error_type,error_message:e.error_message,error_url:e.error_url,request_id:"string"==typeof e.request_id?e.request_id:void 0,error_details:"object"==typeof e.error_details?e.error_details:void 0}):new d({status_code:400,error_type:"unknown_error",error_message:e instanceof Error?e.message:"Unknown error: "+String(e),error_url:"",request_id:void 0,error_details:void 0})}}class p extends l{options;constructor(e,t,r){super(e,t),this.options=r}}class _ extends p{constructor(){super("NoCurrentSessionError","There is no session currently available. Make sure the user is authenticated with a valid session.")}}class m extends p{nativeStack;constructor(e){super(e.name?e.name:"Internal Error",e.message?e.message:"An internal error has occurred. Please contact Stytch if this occurs."),this.nativeStack=e.nativeStackAndroid||e.nativeStackIOS}}class y extends p{constructor(){super("NoBiometricsRegistrationError","There is no biometric registration available. Authenticate with another method and add a new biometric registration first.")}}class g extends p{constructor(){super("BiometricsUnavailableError","Biometrics is not available on the device.")}}class w extends p{constructor(){super("KeyInvalidatedError","The biometrics enrollment on the device has changed.")}}class S extends p{constructor(){super("KeystoreUnavailableError","The Android keystore is unavailable on the device. Consider setting allowFallbackToCleartext to true.")}}class b extends p{constructor(){super("NoBiometricsEnrolledError","There is no biometric factor enrolled on the device. Add a biometric factor in the device settings.")}}class f extends p{constructor(){super("UserCancellationError","The user canceled the prompt. Ask the user to try again.")}}class k extends p{constructor(){super("UserLockedOutError","The user has been locked out due to too many failed attempts. Ask the user to try again later.")}}class C extends p{constructor(){super("DeviceCredentialsNotAllowedError","The device credentials allowment is mismatched. Change the allowDeviceCredentials parameter to be the same in both the register and authenticate methods.")}}class A extends p{constructor(){super("MissingAuthorizationCredentialIDTokenError","The authorization credential is missing an ID token.")}}class v extends p{constructor(){super("InvalidAuthorizationCredentialError","The authorization credential is invalid. Verify that OAuth is set up correctly in the developer console, and call the start flow method.")}}class P extends p{constructor(){super("NoCredentialsPresentError","The user did not provide credentials for a Google OneTap attempt")}}class T extends p{constructor(){super("MissingPublicKeyError","Failed to retrieve the public key. Add a new biometric registration.")}}class E extends p{constructor(){super("ChallengeSigningFailedError","Failed to sign the challenge with the key.")}}class D extends p{constructor(){super("SDKNotConfiguredError","Stytch client is not confiured. You must call the configure method before using the SDK")}}class O extends p{constructor(){super("FailedCodeChallengeError","Failed to create a code challenge")}}class I extends p{constructor(){super("PasskeysUnsupportedError","Passkeys are not supported on this device")}}class B extends p{constructor(){super("FailedToDecryptDataError","Failed to decrypt user data")}}class R extends p{constructor(){super("BiometricsFailedError","Biometric authentication failed")}}class U extends p{constructor(){super("InvalidStartUrlError","The start URL was invalid or improperly formatted.")}}class L extends p{constructor(){super("InvalidRedirectSchemeError","The scheme from the given redirect urls was invalid. Possible reasons include: nil scheme, non-custom scheme (using http or https), or differing schemes for login/signup urls.")}}class F extends p{constructor(){super("MissingUrlError","The underlying web authentication service failed to return a URL.")}}class N extends p{constructor(){super("InvalidCredentialTypeError","The public key credential type was not of the expected type.")}}class K extends p{constructor(){super("MissingAttestationObjectError","The public key credential is missing the attestation object.")}}class x extends p{constructor(){super("JSONDataNotConvertibleToStringError","JSON data unable to be converted to String type.")}}class M extends p{constructor(){super("RandomNumberGenerationFailed","Random number generation failed")}}class $ extends p{constructor(){super("PasskeysInvalidEncoding","Invalid passkey encoding")}}class j extends p{constructor(){super("PasskeysMisconfigured","Passkeys are misconfigured. Verify that you have added the correct associated domain for your application, and that the signing information is correct.")}}class W extends p{constructor(){super("SignInWithAppleMisconfigured","Sign In With Apple is misconfigured. Verify that you have correctly configured Apple OAuth in the Stytch Dashboard and added the Sign In With Apple capability to your project.")}}class q extends p{constructor(){super("MissingCipherIv","The expected cipher Iv was not found when attempting to decrypt an existing biometric key.")}}class G extends p{constructor(){super("InvalidPrivateKeyLength","The private key was of an incorrect length.")}}class z extends p{constructor(){super("BiometricRegistrationIdIsNullOrBlank","Attempted to set a blank or null biometric registration ID. This is not allowed, and indicates no registration was created on the server. Consider deleting any local keys that may have been generated.")}}class H extends p{constructor(){super("DFPNotConfigured","You have attempted to retrieve a telemetry ID before the DFP client has been configured.")}}let J={Google:"google",Microsoft:"microsoft",Apple:"apple",Github:"github",GitLab:"gitlab",Facebook:"facebook",Discord:"discord",Salesforce:"salesforce",Slack:"slack",Amazon:"amazon",Bitbucket:"bitbucket",LinkedIn:"linkedin",Coinbase:"coinbase",Twitch:"twitch",Twitter:"twitter",TikTok:"tiktok",Snapchat:"snapchat",Figma:"figma",Yahoo:"yahoo"},V={embedded:"embedded",floating:"floating",embeddedOnly:"embeddedOnly",floatingOrEmbedded:"floatingOrEmbedded",forceLegacyEmbedded:"forceLegacyEmbedded"};var Y,X,Z,Q,ee=((Z={}).MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",Z.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",Z.OTPsAuthenticate="OTP_AUTHENTICATE",Z.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",Z.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE",Z.PasswordCreate="PASSWORD_CREATE",Z.PasswordAuthenticate="PASSWORD_AUTHENTICATE",Z.PasswordResetByEmailStart="PASSWORD_RESET_BY_EMAIL_START",Z.PasswordResetByEmail="PASSWORD_RESET_BY_EMAIL",Z.PasskeyRegister="PASSKEY_REGISTER",Z.PasskeyAuthenticate="PASSKEY_AUTHENTICATE",Z.PasskeySkip="PASSKEY_SKIP",Z.PasskeyDone="PASSKEY_DONE",Z.AuthenticateFlowComplete="AUTHENTICATE_FLOW_COMPLETE",Z.OAuthAuthorizeFlowStart="OAUTH_AUTHORIZE_FLOW_START",Z.OAuthAuthorizeFlowComplete="OAUTH_AUTHORIZE_FLOW_COMPLETE",Z.OAuthAuthorizeFlowConsentDenied="OAUTH_AUTHORIZE_FLOW_CONSENT_DENIED",Z.B2BMagicLinkEmailLoginOrSignup="B2B_MAGIC_LINK_EMAIL_LOGIN_OR_SIGNUP",Z.B2BMagicLinkAuthenticate="B2B_MAGIC_LINK_AUTHENTICATE",Z.B2BMagicLinkEmailDiscoverySend="B2B_MAGIC_LINK_EMAIL_DISCOVERY_SEND",Z.B2BMagicLinkDiscoveryAuthenticate="B2B_MAGIC_LINK_DISCOVERY_AUTHENTICATE",Z.B2BSSOStart="B2B_SSO_START",Z.B2BSSOAuthenticate="B2B_SSO_AUTHENTICATE",Z.B2BSSODiscoverConnections="B2B_SSO_DISCOVER_CONNECTIONS",Z.B2BOAuthAuthenticate="B2B_OAUTH_AUTHENTICATE",Z.B2BOAuthDiscoveryAuthenticate="B2B_OAUTH_DISCOVERY_AUTHENTICATE",Z.B2BDiscoveryOrganizationsCreate="B2B_DISCOVERY_ORGANIZATIONS_CREATE",Z.B2BDiscoveryIntermediateSessionExchange="B2B_DISCOVERY_INTERMEDIATE_SESSION_EXCHANGE",Z.B2BPasswordAuthenticate="B2B_PASSWORD_AUTHENTICATE",Z.B2BPasswordDiscoveryAuthenticate="B2B_PASSWORD_DISCOVERY_AUTHENTICATE",Z.B2BPasswordResetByEmailStart="B2B_PASSWORD_RESET_BY_EMAIL_START",Z.B2BPasswordResetByEmail="B2B_PASSWORD_RESET_BY_EMAIL",Z.B2BPasswordResetBySession="B2B_PASSWORD_RESET_BY_SESSION",Z.B2BSMSOTPSend="B2B_SMS_OTP_SEND",Z.B2BSMSOTPAuthenticate="B2B_SMS_OTP_AUTHENTICATE",Z.B2BTOTPCreate="B2B_TOTP_CREATE",Z.B2BTOTPAuthenticate="B2B_TOTP_AUTHENTICATE",Z.B2BRecoveryCodesRecover="B2B_RECOVERY_CODES_RECOVER",Z.B2BPasswordDiscoveryResetStart="B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL_START",Z.B2BDiscoveryPasswordReset="B2B_PASSWORD_DISCOVERY_RESET_BY_EMAIL",Z.B2BImpersonationAuthenticate="B2B_IMPERSONATION_AUTHENTICATE",Z.B2BOTPsEmailAuthenticate="B2B_OTPS_EMAIL_AUTHENTICATE",Z.B2BOTPsEmailDiscoveryAuthenticate="B2B_OTPS_EMAIL_DISCOVERY_AUTHENTICATE",Z.B2BOTPsEmailDiscoverySend="B2B_OTPS_EMAIL_DISCOVERY_SEND",Z.B2BOTPsEmailLoginOrSignup="B2B_OTPS_EMAIL_LOGIN_OR_SIGNUP",Z.B2BOrganizationsGetBySlug="B2B_ORGANIZATIONS_GET_BY_SLUG",Z),et=((Y={})[Y.emailMagicLinks=0]="emailMagicLinks",Y[Y.oauth=1]="oauth",Y[Y.otp=2]="otp",Y[Y.passwords=3]="passwords",Y),er=((X={}).RequiredCaptcha="CAPTCHA required",X);class es extends Error{type;constructor(e){super(e),this.type=e}}async function ei({method:e,finalURL:t,basicAuthHeader:r,xSDKClientHeader:s,xSDKParentHostHeader:i,body:a,retryCallback:o}){let n={method:e,finalURL:t,basicAuthHeader:r,xSDKClientHeader:s,xSDKParentHostHeader:i,body:a};try{return await ea(n)}catch(e){if(e instanceof es)return n=await o(e,n),await ea(n);throw e}}async function ea({method:e,finalURL:t,basicAuthHeader:r,xSDKClientHeader:s,xSDKParentHostHeader:i,body:a}){let o,n,c={Authorization:r,"Content-Type":"application/json","X-SDK-Client":s};i&&(c["X-SDK-Parent-Host"]=i);let l={method:e,headers:c,body:a&&JSON.stringify(a),credentials:"include"};try{o=await fetch(t,l)}catch(e){if("Failed to fetch"===e.message)throw new h("Unable to contact our servers.");throw e}if(o.status<=299)try{return(await o.json()).data}catch{throw new h("Invalid JSON response from our servers.")}if(200!==o.status&&o.headers.get("content-type")?.includes("application/json")){let e;try{e=await o.json()}catch{throw new h("Invalid or no response from server")}if("body"in e||"params"in e||"query"in e)throw new u(e);throw new d(e)}try{n=await o.text()}catch{throw new h("Invalid response from our servers.")}if(n.includes("Captcha required"))throw new es("CAPTCHA required");throw new h("Invalid response from our servers.")}async function eo({method:e,finalURL:t,basicAuthHeader:r,xSDKClientHeader:s,xSDKParentHostHeader:i,body:a}){let o={...a||{},__Authorization:r,"__X-SDK-Client":s};i&&(o["__X-SDK-Parent-Host"]=i);let n=Object.entries(o).map(([e,t])=>{let r=document.createElement("input");return r.type="hidden",r.name=e,r.value=t,r}),c=document.createElement("form");c.method=e,c.action=t,c.append(...n),document.body.appendChild(c),c.submit()}for(var en=new Uint8Array(16),ec=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,el=[],eh=0;eh<256;++eh)el.push((eh+256).toString(16).substr(1));function eu(e,t,r){var s=(e=e||{}).random||(e.rng||function(){if(!Q&&!(Q="u">typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"u">typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Q(en)})();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(el[e[t+0]]+el[e[t+1]]+el[e[t+2]]+el[e[t+3]]+"-"+el[e[t+4]]+el[e[t+5]]+"-"+el[e[t+6]]+el[e[t+7]]+"-"+el[e[t+8]]+el[e[t+9]]+"-"+el[e[t+10]]+el[e[t+11]]+el[e[t+12]]+el[e[t+13]]+el[e[t+14]]+el[e[t+15]]).toLowerCase();if(!("string"==typeof r&&ec.test(r)))throw TypeError("Stringified UUID is invalid");return r}(s)}let ed=e=>{try{let t=new URL(e);return`https://${t.hostname}`}catch{}try{let t=new URL(`https://${e}`);return`https://${t.hostname}`}catch{}},ep=["%c[Stytch]%c","background: #19303d; color: #13E5C0; padding: 2px;border-radius: 4px",""],e_=(...e)=>console.warn(...ep,...e),em=(...e)=>console.error(...ep,...e),ey=`
15
- You can find your public token at https://stytch.com/dashboard/api-keys.`,eg={};async function ew(e,t){var r,s;return void 0!==eg[e]||(eg[e]=(r=e,s=t,new Promise((e,t)=>{var i;let a,o=function(e){let t=document.querySelectorAll(`script[src="${e}"]`);if(t[0])return t[0]}(r);if(o&&"true"===o.dataset.loaded)try{e(s())}catch(e){return t(Error(`${r} already loaded, but module was not found in global scope: ${e}`))}let n=(i=r,(a=document.createElement("script")).setAttribute("src",i),a.setAttribute("async","true"),a.setAttribute("defer","true"),document.head.appendChild(a),a);n.addEventListener("load",()=>{n.dataset.loaded="true";try{e(s())}catch(e){t(Error(`${r} was loaded, but module was not found in global scope: ${e}`))}}),n.addEventListener("error",e=>{t(Error(`${r} could not be loaded: ${e}`))})}))),eg[e]}let eS=e=>{let{__user:t,...r}=e;return r};class eb{bootstrapPromise;state;constructor(e,t,r,s,i=()=>Promise.resolve(void 0)){this.bootstrapPromise=s,this.state=s.then(async s=>s.runDFPProtectedAuth?(await ew(`${r}/telemetry.js`,()=>window.GetTelemetryID),{publicToken:e,dfpBackendURL:t,enabled:!0,mode:s.dfpProtectedAuthMode||"OBSERVATION",loaded:!0,executeRecaptcha:i}):{publicToken:e,dfpBackendURL:t,enabled:!1,loaded:!1,executeRecaptcha:i})}isEnabled=async()=>this.state.then(e=>e.enabled);getTelemetryID=async()=>{let{publicToken:e,enabled:t,dfpBackendURL:r}=await this.state;if(t)return await window.GetTelemetryID(e,`${r}/submit`)};getDFPTelemetryIDAndCaptcha=async()=>{let e,t,{enabled:r,executeRecaptcha:s,mode:i}=await this.state;return r||(t=await s()),"DECISIONING"===i?e=await this.getTelemetryID():"OBSERVATION"===i&&(e=await this.getTelemetryID(),t=await s()),{dfp_telemetry_id:e,captcha_token:t}};retryWithCaptchaAndDFP=async(e,t)=>{let{enabled:r,executeRecaptcha:s}=await this.state;if(e.type===er.RequiredCaptcha&&r)return t.body&&(t.body.dfp_telemetry_id=await this.getTelemetryID(),t.body.captcha_token=await s()),t;throw Error("Unable to query captcha and/or dfp telemetry ID")}}class ef{static inflate(e,t){let r=new e(t);return Object.assign(r,t),Object.setPrototypeOf(r,e.prototype),r}static unmarshall(e){if("name"in e)switch(e.name){case"SDKAPIUnreachableError":return ef.inflate(i,e);case"StytchSDKSchemaError":return ef.inflate(o,e);case"StytchAPIUnreachableError":return ef.inflate(h,e);case"StytchAPISchemaError":return ef.inflate(u,e);case"StytchSDKAPIError":return ef.inflate(n,e);case"StytchAPIError":return ef.inflate(d,e);case"TypeError":return ef.inflate(TypeError,e);case"SyntaxError":return ef.inflate(SyntaxError,e);case"ReferenceError":return ef.inflate(ReferenceError,e);case"RangeError":return ef.inflate(RangeError,e);case"EvalError":return ef.inflate(EvalError,e);case"URIError":return ef.inflate(URIError,e)}return ef.inflate(Error,e)}}class ek{maxBatchSize;logEventURL;batch;constructor(e){this.maxBatchSize=e.maxBatchSize,this.logEventURL=e.logEventURL,setInterval(this.flush.bind(this),e.intervalDurationMs),this.batch=[]}logEvent(e,t){this.batch.push({telemetry:e,event:t}),this.batch.length>=this.maxBatchSize&&this.flush()}async flush(){if(!this.batch.length)return;let e=this.batch;this.batch=[];try{await fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}}let eC=(e,t,r)=>{let s=[];for(let[i,o]of Object.entries(r)){if(null==o)continue;let r=t[i];if(!o.startsWith("optional")||null!=r)switch(o){case"object":case"optionalObject":("object"!=typeof r||Array.isArray(r)||null===r)&&s.push(new a(e,`${i} must be an object.`));break;case"string":case"optionalString":"string"!=typeof r&&s.push(new a(e,`${i} must be a string.`));break;case"number":case"optionalNumber":"number"!=typeof r&&s.push(new a(e,`${i} must be a number.`));break;case"stringArray":case"optionalStringArray":Array.isArray(r)&&r.every(e=>"string"==typeof e)||s.push(new a(e,`${i} must be an array of strings.`));break;case"boolean":case"optionalBoolean":"boolean"!=typeof r&&s.push(new a(e,`${i} must be a boolean.`))}}if(s.length>0)if(1===s.length)throw s[0];else throw AggregateError(s)};Promise.resolve({pkceRequiredForEmailMagicLinks:!1}),Promise.resolve({pkceRequiredForPasswordResets:!1});class eA{roles;resources;rolesByID;constructor(e,t){this.roles=e,this.resources=t,this.rolesByID={},e.forEach(e=>this.rolesByID[e.role_id]=e)}static fromJSON(e){return new eA(e.roles,e.resources)}mergeWithCustomRoles(e){return new eA([...this.roles,...e],this.resources)}callerIsAuthorized(e,t,r){return!!e.map(e=>this.rolesByID[e]).filter(e=>e).flatMap(e=>e.permissions).filter(e=>e.resource_id===t).find(e=>e.actions.includes(r)||e.actions.includes("*"))}allPermissionsForCaller(e){let t=Object.create(null);return this.resources.forEach(r=>{t[r.resource_id]={},r.actions.forEach(s=>{t[r.resource_id][s]=this.callerIsAuthorized(e,r.resource_id,s)})}),t}}let ev=Promise.resolve({siweRequiredForCryptoWallets:!1});class eP{_networkClient;_apiNetworkClient;_subscriptionService;executeRecaptcha;dfpProtectedAuth;_config;authenticate;constructor(e,t,r,s=()=>Promise.resolve(void 0),i,a=ev){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=r,this.executeRecaptcha=s,this.dfpProtectedAuth=i,this._config=a,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.cryptoWallets.authenticate",e,{signature:"string",crypto_wallet_address:"string",crypto_wallet_type:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._apiNetworkClient.retriableFetchSDK({url:"/crypto_wallets/authenticate",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,crypto_wallet_address:e.crypto_wallet_address,crypto_wallet_type:e.crypto_wallet_type,signature:e.signature,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async authenticateStart(e){eC("stytch.cryptoWallets.authenticateStart",e,{crypto_wallet_address:"string",crypto_wallet_type:"string"}),e.siwe_params&&eC("stytch.cryptoWallets.authenticateStart",e.siwe_params,{uri:"optionalString",chain_id:"optionalString",issued_at:"optionalString",statement:"optionalString",not_before:"optionalString",message_request_id:"optionalString",resources:"optionalStringArray"});let t=!!this._subscriptionService.getSession(),r=await this.executeRecaptcha(),{siweRequiredForCryptoWallets:s}=await this._config,i={crypto_wallet_address:e.crypto_wallet_address,crypto_wallet_type:e.crypto_wallet_type};s&&"ethereum"==e.crypto_wallet_type&&(i.siwe_params={...e.siwe_params,uri:e.siwe_params?.uri||window.location.origin});let a={...i,captcha_token:r};return this._apiNetworkClient.fetchSDK({url:t?"/crypto_wallets/authenticate/start/secondary":"/crypto_wallets/authenticate/start/primary",method:"POST",body:a})}}class eT{_networkClient;constructor(e){this._networkClient=e}oauthAuthorizeStart=async e=>this._networkClient.fetchSDK({url:"/idp/oauth/authorize/start",method:"POST",body:e});oauthAuthorizeSubmit=async e=>this._networkClient.fetchSDK({url:"/idp/oauth/authorize/submit",method:"POST",body:e});oauthLogoutStart=async e=>this._networkClient.fetchSDK({url:"/oauth/logout/start",method:"POST",body:e})}class eE{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.impersonation.authenticate",e,{impersonation_token:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/impersonation/authenticate",body:{...e,dfp_telemetry_id:t,captcha_token:r},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}let eD=Promise.resolve({pkceRequiredForEmailMagicLinks:!1});class eO{_networkClient;_subscriptionService;_pkceManager;_passwordResetPKCEManager;_config;dfpProtectedAuth;email;authenticate;constructor(e,t,r,s,i=eD,a){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._passwordResetPKCEManager=s,this._config=i,this.dfpProtectedAuth=a,this.email={loginOrCreate:async(e,t={})=>{let r,{pkceRequiredForEmailMagicLinks:s}=await this._config;s&&(r=await this.getCodeChallenge());let{dfp_telemetry_id:i,captcha_token:a}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),o={...t,email:e,code_challenge:r,captcha_token:a,dfp_telemetry_id:i};return this._networkClient.retriableFetchSDK({url:"/magic_links/email/login_or_create",body:o,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t={})=>{let r,{pkceRequiredForEmailMagicLinks:s}=await this._config;s&&(r=await this.getCodeChallenge());let{dfp_telemetry_id:i,captcha_token:a}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),o={...t,email:e,code_challenge:r,captcha_token:a,dfp_telemetry_id:i},n=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:n?"/magic_links/email/send/secondary":"/magic_links/email/send/primary",body:o,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}},this.authenticate=this._subscriptionService.withUpdateSession(async(e,t)=>{eC("stytch.magicLinks.authenticate",{token:e,...t},{token:"string",session_duration_minutes:"number"});let r=await this._passwordResetPKCEManager.getPKPair(),s=null;if(r?.code_verifier)try{s=await this.handlePKCEForAuthenticate(this._passwordResetPKCEManager,{token:e,...t})}catch(e){if(e.message.includes("pkce"))console.log("Authenticate with passwords pkce namespace failed. Falling back to authenticate with magic_links namespace.");else throw e}return s||(s=await this.handlePKCEForAuthenticate(this._pkceManager,{token:e,...t})),eS(s)})}async getCodeChallenge(){let e=await this._pkceManager.getPKPair();return e?e.code_challenge:(e=await this._pkceManager.startPKCETransaction()).code_challenge}async handlePKCEForAuthenticate(e,t){let r=await e.getPKPair(),s={code_verifier:r?.code_verifier,...t},i=await this._networkClient.fetchSDK({url:"/magic_links/authenticate",body:s,method:"POST"});return e.clearPKPair(),i}}let eI=class{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;authenticate;constructor(e,t,r,s,i){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._dynamicConfig=s,this._config=i,this.authenticate=this._subscriptionService.withUpdateSession(async(e,t)=>{eC("stytch.oauth.authenticate",{token:e,...t},{token:"string",session_duration_minutes:"number"});let r=await this._pkceManager.getPKPair();r||e_("No code verifier found in local storage for OAuth flow.\nConsider using stytch.oauth.$provider.start() to add PKCE to your OAuth flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let s=await this._networkClient.fetchSDK({url:"/oauth/authenticate",method:"POST",body:{token:e,code_verifier:r?.code_verifier,...t}});return this._pkceManager.clearPKPair(),eS(s)})}google={start:this.startOAuthFlow(J.Google)};apple={start:this.startOAuthFlow(J.Apple)};microsoft={start:this.startOAuthFlow(J.Microsoft)};github={start:this.startOAuthFlow(J.Github)};gitlab={start:this.startOAuthFlow(J.GitLab)};facebook={start:this.startOAuthFlow(J.Facebook)};discord={start:this.startOAuthFlow(J.Discord)};salesforce={start:this.startOAuthFlow(J.Salesforce)};slack={start:this.startOAuthFlow(J.Slack)};amazon={start:this.startOAuthFlow(J.Amazon)};bitbucket={start:this.startOAuthFlow(J.Bitbucket)};linkedin={start:this.startOAuthFlow(J.LinkedIn)};coinbase={start:this.startOAuthFlow(J.Coinbase)};twitch={start:this.startOAuthFlow(J.Twitch)};twitter={start:this.startOAuthFlow(J.Twitter)};tiktok={start:this.startOAuthFlow(J.TikTok)};snapchat={start:this.startOAuthFlow(J.Snapchat)};figma={start:this.startOAuthFlow(J.Figma)};yahoo={start:this.startOAuthFlow(J.Yahoo)};async attach(e){return eC("stytch.oauth.attach",{provider:e},{provider:"string"}),await this._networkClient.fetchSDK({url:"/oauth/attach",method:"POST",body:{provider:e}})}async getBaseApiUrl(){let{cnameDomain:e}=await this._dynamicConfig;return e?`https://${e}`:this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}startOAuthFlow(e){return async({login_redirect_url:t,signup_redirect_url:r,custom_scopes:s,provider_params:i,oauth_attach_token:a}={})=>{let{cnameDomain:o,pkceRequiredForOAuth:n}=await this._dynamicConfig,c=await this.getBaseApiUrl();this._networkClient.logEvent({name:"start_oauth_flow",details:{provider_type:e,custom_scopes:s,cname_domain:o,pkce:n,provider_params:i}});let l=new URL(`${c}/v1/public/oauth/${e}/start`);if(l.searchParams.set("public_token",this._config.publicToken),n){let e=await this._pkceManager.startPKCETransaction();l.searchParams.set("code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();if(s&&(eC("startOAuthFlow",{custom_scopes:s},{custom_scopes:"stringArray"}),l.searchParams.set("custom_scopes",s.join(" "))),i)for(let e in eC("startOAuthFlow",{provider_params:i},{provider_params:"optionalObject"}),i)l.searchParams.set("provider_"+e,i[e]);t&&l.searchParams.set("login_redirect_url",t),r&&l.searchParams.set("signup_redirect_url",r),a&&l.searchParams.set("oauth_attach_token",a),this.navigate(l)}}navigate(e){window.location.href=e.toString()}};class eB{_networkClient;_subscriptionService;executeRecaptcha;dfpProtectedAuth;authenticate;constructor(e,t,r=()=>Promise.resolve(void 0),s){this._networkClient=e,this._subscriptionService=t,this.executeRecaptcha=r,this.dfpProtectedAuth=s,this.authenticate=this._subscriptionService.withUpdateSession(async(e,t,r)=>{eC("stytch.otps.authenticate",{code:e,...r},{code:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:s,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),a={token:e,method_id:t,dfp_telemetry_id:s,captcha_token:i,...r};return eS(await this._networkClient.retriableFetchSDK({url:"/otps/authenticate",body:a,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}sms={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r};return this._networkClient.retriableFetchSDK({url:"/otps/sms/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r},a=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:a?"/otps/sms/send/secondary":"/otps/sms/send/primary",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}};whatsapp={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,dfp_telemetry_id:r,captcha_token:s};return this._networkClient.retriableFetchSDK({url:"/otps/whatsapp/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r},a=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:a?"/otps/whatsapp/send/secondary":"/otps/whatsapp/send/primary",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}};email={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,email:e,captcha_token:s,dfp_telemetry_id:r};return this._networkClient.retriableFetchSDK({url:"/otps/email/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let r=await this.executeRecaptcha(),s={...t,email:e,captcha_token:r},i=!!this._subscriptionService.getSession();return this._networkClient.fetchSDK({url:i?"/otps/email/send/secondary":"/otps/email/send/primary",body:s,method:"POST"})}}}let eR=Promise.resolve({pkceRequiredForPasswordResets:!1});class eU{_networkClient;_subscriptionService;_pkceManager;_config;dfpProtectedAuth;create;authenticate;resetByEmail;resetByExistingPassword;resetBySession;constructor(e,t,r,s=eR,i){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._config=s,this.dfpProtectedAuth=i,this.create=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.create",e,{password:"string",email:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords",method:"POST",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.authenticate",e,{password:"string",email:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords/authenticate",method:"POST",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.resetByEmail=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByEmail",e,{token:"string",password:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._pkceManager.getPKPair(),i=s?.code_verifier,a=await this._networkClient.retriableFetchSDK({url:"/passwords/email/reset",method:"POST",body:{token:e.token,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,code_verifier:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),eS(a)}),this.resetByExistingPassword=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByExistingPassword",e,{email:"string",existing_password:"string",new_password:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords/existing_password/reset",method:"POST",body:{email:e.email,existing_password:e.existing_password,new_password:e.new_password,session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.resetBySession=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetBySession",e,{password:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/passwords/session/reset",method:"POST",body:{password:e.password,session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async getCodeChallenge(){let{pkceRequiredForPasswordResets:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async resetByEmailStart(e){eC("stytch.passwords.resetByEmailStart",e,{email:"string",login_redirect_url:"optionalString",reset_password_redirect_url:"optionalString",reset_password_template_id:"optionalString",reset_password_expiration_minutes:"optionalNumber",locale:"optionalString"});let t=await this.getCodeChallenge(),{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/passwords/email/reset/start",method:"POST",body:{email:e.email,login_redirect_url:e.login_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,locale:e.locale,code_challenge:t,captcha_token:s,dfp_telemetry_id:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async strengthCheck(e){return eC("stytch.passwords.strengthCheck",e,{email:"optionalString",password:"string"}),this._networkClient.fetchSDK({url:"/passwords/strength_check",method:"POST",body:{email:e.email,password:e.password}})}}class eL{_subscriptionService;cachedPolicy;policyPromise;constructor(e,t,r){this._subscriptionService=r,this.cachedPolicy=e.rbacPolicy?eA.fromJSON(e.rbacPolicy):null,this.policyPromise=t.then(e=>e.rbacPolicy?(this.cachedPolicy=eA.fromJSON(e.rbacPolicy),this.cachedPolicy):(em("Unable to retrieve RBAC policy from servers. Assuming caller has no permissions."),new eA([],[])))}allPermissions(){return this.policyPromise.then(e=>e.allPermissionsForCaller(this.roleIds()))}isAuthorizedSync=(e,t)=>!!this.cachedPolicy?.callerIsAuthorized(this.roleIds(),e,t);isAuthorized=(e,t)=>this.policyPromise.then(r=>r.callerIsAuthorized(this.roleIds(),e,t));roleIds(){let e=this._subscriptionService.getUser();return e?e.roles??[]:[]}}class eF{_networkClient;_subscriptionService;authenticate;exchangeAccessToken;attest;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.authenticate=this._subscriptionService.withUpdateSession(this._authenticate),this.exchangeAccessToken=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.exchangeAccessToken",e,{access_token:"string",session_duration_minutes:"number"}),eS(await this._networkClient.fetchSDK({url:"/sessions/exchange_access_token",body:e,method:"POST"})))),this.attest=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.attest",e,{profile_id:"string",token:"string",session_duration_minutes:"optionalNumber"}),this._networkClient.fetchSDK({url:"/sessions/attest",body:e,method:"POST"})))}getSync=()=>this._subscriptionService.getSession();getInfo=()=>({session:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>{let t=this._subscriptionService.getSession();return this._subscriptionService.subscribeToState(r=>{r?.session!==t&&e(t=r?.session??null)})};revoke=async e=>{try{let e=await this._networkClient.fetchSDK({url:"/sessions/revoke",method:"POST"});return this._subscriptionService.destroyState(),e}catch(t){throw e?.forceClear?this._subscriptionService.destroyState():c.includes(t.error_type)&&this._subscriptionService.destroyState(),t}};_authenticate=async e=>{let t=this._subscriptionService.getSession(),r=()=>t?.session_id!==this._subscriptionService.getSession()?.session_id;try{let t={session_duration_minutes:e?.session_duration_minutes},s=await this._networkClient.fetchSDK({url:"/sessions/authenticate",body:t,method:"POST"});if(r())return this._authenticate(e);return eS(s)}catch(t){if(r())return this._authenticate(e);throw c.includes(t.error_type)&&this._subscriptionService.destroySession(),t}};getTokens(){return this._subscriptionService.getTokens()}updateSession(e){eC("stytch.session.updateSession",e,{session_token:"string",session_jwt:"optionalString"}),this._subscriptionService.updateTokens(e)}}class eN{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;recover;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.totps.authenticate",e,{session_duration_minutes:"number",totp_code:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/totps/authenticate",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,totp_code:e.totp_code,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.recover=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.totps.recover",e,{session_duration_minutes:"number",recovery_code:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/totps/recover",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,recovery_code:e.recovery_code,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async create(e){eC("stytch.totps.create",e,{expiration_minutes:"number"});let t=await this._networkClient.fetchSDK({url:"/totps",method:"POST",body:{expiration_minutes:e.expiration_minutes}});return this._subscriptionService.updateUser(t.__user),eS(t)}async recoveryCodes(){return this._networkClient.fetchSDK({url:"/totps/recovery_codes",method:"POST"})}}class eK{_networkClient;_subscriptionService;constructor(e,t){this._networkClient=e,this._subscriptionService=t}get=async()=>{let e=(({request_id:e,status_code:t,...r})=>r)(await this._networkClient.fetchSDK({url:"/users/me",method:"GET"}));return this._subscriptionService.updateUser(e),e};getSync=()=>this._subscriptionService.getUser();getInfo=()=>({user:this.getSync(),fromCache:this._subscriptionService.getFromCache()});update=async e=>{eC("stytch.user.update",e,{untrusted_metadata:"optionalObject"});let t=await this._networkClient.fetchSDK({url:"/users/me",body:e,method:"PUT"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteEmail=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/emails/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deletePhoneNumber=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/phone_numbers/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteTOTP=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/totps/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteCryptoWallet=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/crypto_wallets/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteOAuthRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/oauth/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteWebauthnRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/webauthn_registrations/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteBiometricRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/biometric_registrations/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};onChange=e=>{let t=this._subscriptionService.getUser();return this._subscriptionService.subscribeToState(r=>{r?.user!==t&&e(t=r?.user??null)})};getConnectedApps=async()=>await this._networkClient.fetchSDK({url:"/users/connected_apps",method:"GET"});revokedConnectedApp=async e=>await this._networkClient.fetchSDK({url:`/users/connected_apps/${e}/revoke`,method:"POST"})}function ex(e){let t="==".slice(0,(4-e.length%4)%4),r=atob(e.replace(/-/g,"+").replace(/_/g,"/")+t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return s}function eM(e){let t=new Uint8Array(e),r="";for(let e of t)r+=String.fromCharCode(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var e$="copy",ej="convert";function eW(e,t,r){if(t===e$)return r;if(t===ej)return e(r);if(t instanceof Array)return r.map(r=>eW(e,t[0],r));if(t instanceof Object){let s={};for(let[i,a]of Object.entries(t)){if(a.derive){let e=a.derive(r);void 0!==e&&(r[i]=e)}if(!(i in r)){if(a.required)throw Error(`Missing key: ${i}`);continue}if(null==r[i]){s[i]=null;continue}s[i]=eW(e,a.schema,r[i])}return s}}function eq(e,t){return{required:!0,schema:e,derive:t}}function eG(e){return{required:!0,schema:e}}function ez(e){return{required:!1,schema:e}}var eH={type:eG(e$),id:eG(ej),transports:ez(e$)},eJ={appid:ez(e$),appidExclude:ez(e$),credProps:ez(e$)},eV={appid:ez(e$),appidExclude:ez(e$),credProps:ez(e$)},eY={publicKey:eG({rp:eG(e$),user:eG({id:eG(ej),name:eG(e$),displayName:eG(e$)}),challenge:eG(ej),pubKeyCredParams:eG(e$),timeout:ez(e$),excludeCredentials:ez([eH]),authenticatorSelection:ez(e$),attestation:ez(e$),extensions:ez(eJ)}),signal:ez(e$)},eX={type:eG(e$),id:eG(e$),rawId:eG(ej),authenticatorAttachment:ez(e$),response:eG({clientDataJSON:eG(ej),attestationObject:eG(ej),transports:eq(e$,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:eq(eV,e=>e.getClientExtensionResults())},eZ={mediation:ez(e$),publicKey:eG({challenge:eG(ej),timeout:ez(e$),rpId:ez(e$),allowCredentials:ez([eH]),userVerification:ez(e$),extensions:ez(eJ)}),signal:ez(e$)},eQ={type:eG(e$),id:eG(e$),rawId:eG(ej),authenticatorAttachment:ez(e$),response:eG({clientDataJSON:eG(ej),authenticatorData:eG(ej),signature:eG(ej),userHandle:eG(ej)}),clientExtensionResults:eq(eV,e=>e.getClientExtensionResults())};async function e0(e){let t=await navigator.credentials.create(eW(ex,eY,e));return eW(eM,eX,t)}async function e1(e){let t=await navigator.credentials.get(eW(ex,eZ,e));return eW(eM,eQ,t)}class e2{_networkClient;_subscriptionService;dfpProtectedAuth;register;authenticate;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.register=this._subscriptionService.withUpdateSession(async e=>{e&&eC("stytch.webauthn.register",e,{domain:"optionalString",authenticator_type:"optionalString",is_passkey:"optionalBoolean",session_duration_minutes:"number",override_id:"optionalString",override_name:"optionalString",override_display_name:"optionalString",use_base64_url_encoding:"optionalBoolean"});let t=JSON.parse((await this._networkClient.fetchSDK({url:"/webauthn/register/start",method:"POST",body:{domain:e?.domain??window.location.hostname,authenticator_type:e?.authenticator_type??void 0,return_passkey_credential_options:e?.is_passkey,override_id:e?.override_id,override_name:e?.override_name,override_display_name:e?.override_display_name,user_agent:navigator.userAgent,use_base64_url_encoding:e?.use_base64_url_encoding}})).public_key_credential_creation_options),r=await e0({publicKey:t});return eS(await this._networkClient.fetchSDK({url:"/webauthn/register",method:"POST",body:{public_key_credential:JSON.stringify(r),session_duration_minutes:e?.session_duration_minutes}}))}),this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.webauthn.authenticate",e,{domain:"optionalString",session_duration_minutes:"number",is_passkey:"optionalBoolean",signal:"optionalObject",conditional_mediation:"optionalBoolean",disable_input_check:"optionalBoolean"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();if(e.conditional_mediation){if(!await this.browserSupportsAutofill())return em("Browser does not support WebAuthn autofill"),null;if(!e.disable_input_check&&!this.checkEligibleInputs())return null}let s=!!this._subscriptionService.getSession(),i=(await this._networkClient.fetchSDK({url:s?"/webauthn/authenticate/start/secondary":"/webauthn/authenticate/start/primary",method:"POST",body:{domain:e.domain??window.location.hostname,return_passkey_credential_options:e?.is_passkey}})).public_key_credential_request_options,a=new AbortController,o={publicKey:JSON.parse(i),signal:e.signal??a.signal},n={...o,mediation:"conditional"},c=await e1(e.conditional_mediation?n:o);return eS(await this._networkClient.retriableFetchSDK({url:"/webauthn/authenticate",method:"POST",body:{public_key_credential:JSON.stringify(c),session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async update(e){eC("stytch.webauthn.update",e,{webauthn_registration_id:"string",name:"string"});let t="/webauthn/update/"+e.webauthn_registration_id;return await this._networkClient.fetchSDK({url:t,method:"PUT",body:{name:e.name}})}async browserSupportsAutofill(){return await window.PublicKeyCredential?.isConditionalMediationAvailable?.()??!1}checkEligibleInputs=()=>!(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)||(em('No <input> with `"webauthn"` in its `autocomplete` attribute was detected'),!1)}class e6{iframeURL;frame;constructor(e){this.iframeURL=e,this.createIframe()}createIframe(){let e=document.querySelector(`[src~="${this.iframeURL}"]`);if(e?e_(s):((e=document.createElement("iframe")).src=this.iframeURL,e.style.position="absolute",e.style.width="0",e.style.height="0",e.style.border="0",e.role="none",document.body.appendChild(e)),"true"===e.dataset.loaded){this.frame=Promise.resolve(e);return}this.frame=new Promise(t=>{e.addEventListener("load",()=>{e.dataset.loaded="true",t(e)},{once:!0})})}async call(e,t){let r=await this.frame,s=new MessageChannel;return new Promise((i,a)=>{s.port1.onmessage=e=>{let t=e.data;s.port1.close(),t.success?i(t.payload):a(ef.unmarshall(t.error))},r.contentWindow?.postMessage({method:e,args:t},this.iframeURL,[s.port2])})}}class e4{_networkClient;dfpProtectedAuth;constructor(e,t){this._networkClient=e,this.dfpProtectedAuth=t}searchUser(e){return this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha().then(({dfp_telemetry_id:t,captcha_token:r})=>this._networkClient.fetchSDK({url:"/users/search",method:"POST",body:{email:e,dfp_telemetry_id:t,captcha_token:r}}))}searchMember(e,t){return this._networkClient.fetchSDK({url:"/b2b/organizations/members/search",method:"POST",body:{email_address:e,organization_id:t}})}}class e3{hasWarned=!1;registry=new Map;register(e,t){let r=this.registry.get(e);r&&r!==t&&(this.hasWarned||(e_(s),this.hasWarned=!0),r.cancelBackgroundRefresh()),this.registry.set(e,t)}unregister(e,t){let r=this.registry.get(e);r&&r===t&&this.registry.delete(e)}}class e5{_subscriptionService;_headlessSessionClient;_publicToken;_options;static REFRESH_INTERVAL_MS=18e4;timeout=null;lastAuthenticationSessionDuration;static registry=new e3;register(){e5.registry.register(this._publicToken,this)}unregister(){e5.registry.unregister(this._publicToken,this)}constructor(e,t,r,s){this._subscriptionService=e,this._headlessSessionClient=t,this._publicToken=r,this._options=s,this._subscriptionService.subscribeToState(this._onDataChange)}performBackgroundRefresh(){this._reauthenticateWithBackoff().then(()=>{this.scheduleBackgroundRefresh()}).catch(e=>{e_("Session background refresh failed. Signalling to app that user is logged out.",{error:e}),this._subscriptionService.destroySession()})}scheduleBackgroundRefresh(){this.cancelBackgroundRefresh(),this.register(),this.timeout=setTimeout(()=>{this.performBackgroundRefresh()},e5.REFRESH_INTERVAL_MS)}cancelBackgroundRefresh(){null!==this.timeout&&(this.unregister(),clearTimeout(this.timeout),this.timeout=null)}_onDataChange=e=>{null!=e&&e.sessionDurationMinutes&&(this.lastAuthenticationSessionDuration=e.sessionDurationMinutes),e?.session?this.scheduleBackgroundRefresh():this.cancelBackgroundRefresh()};_reauthenticateWithBackoff=async()=>{let e=0;for(;;)try{let e={session_duration_minutes:this._options.keepSessionAlive?this.lastAuthenticationSessionDuration:void 0};return await this._headlessSessionClient.authenticate(e)}catch(t){if(e5.isUnrecoverableError(t))return Promise.reject(t);e++,await new Promise(t=>setTimeout(t,e5.timeoutForAttempt(e)))}};static timeoutForAttempt(e){return e=Math.min(e,7),Math.floor(350*Math.random())-175+2e3*2**e}static isUnrecoverableError(e){return c.includes(e.error_type)}}class e8{_subscriptionService;emptyState;constructor(e,t){this._subscriptionService=e,this.emptyState=t}onStateChange=e=>this._subscriptionService.subscribeToState(t=>{e(t??this.emptyState)})}let e9="bootstrap",e7=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class te{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,r){this._publicToken=e,this._networkClient=t,this._dataLayer=r,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(te.mapBootstrapData).then(e=>(this._dataLayer.setItem(e9,JSON.stringify(e)),e)).catch(e=>(em(e),e7()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(e9);if(null===e)return e7();try{return JSON.parse(e)}catch{return e7()}}getAsync(){return this._bootstrapDataPromise}}class tt{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,ew(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:r}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(r,{action:"LOGIN"})}}class tr{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new e6(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}class ts extends eI{_oneTap;constructor(e,t,r,s,i,a){super(e,t,r,s,i),this._oneTap=a}startOneTap=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:r}=t,s=this._oneTap.createOnSuccessHandler({signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return r.render({style:{position:V.floating},onOneTapCancelled:e.onOneTapCancelled,callback:s,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={start:this.startOneTap}}class ti{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,r,s,i){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=i,this.baseURL=r,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=s),this.eventLogger=new ek({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:r={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:r.error_code,error_description:r.error_description,http_status_code:r.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${eu()}`,app_session_id:`app-session-id-${eu()}`,persistent_id:`persistent-id-${eu()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"@stytch/vanilla-js@6.0.8"}}}async fetchSDK({url:e,body:t,method:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,i="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),a=window.btoa(JSON.stringify(this.createTelemetryBlob())),o=window.location.origin;return ea({basicAuthHeader:i,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:a,xSDKParentHostHeader:o})}async submitFormSDK({url:e,body:t,method:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,i="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),a=window.btoa(JSON.stringify(this.createTelemetryBlob())),o=window.location.origin;return eo({basicAuthHeader:i,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:a,xSDKParentHostHeader:o})}async retriableFetchSDK({url:e,body:t,method:r,retryCallback:s}){let i=this._subscriptionDataLayer.readSessionCookie().session_token,a="Basic "+window.btoa(this._publicToken+":"+(i||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return ei({basicAuthHeader:a,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:o,xSDKParentHostHeader:n,retryCallback:s})}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}let ta="u">typeof window&&"IdentityCredential"in window,to=e=>e===V.forceLegacyEmbedded?"force":e===V.embeddedOnly||e===V.embedded||e===V.floatingOrEmbedded;class tn{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:r,cancelOnTapOutside:s=!0}){let i,a=to(r.position),o="force"===(i=to(r.position))||i&&!ta,n={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==a,cancel_on_tap_outside:s};return o&&(n.prompt_parent_id="google-parent-prompt",n.cancel_on_tap_outside=!1),this._googleClient.initialize(n),new Promise(e=>{this._googleClient.prompt(r=>{if(r.isSkippedMoment()){let s=r.getSkippedReason?.()??"unknown_reason";return"user_cancel"===s&&t?.(),e({success:!1,reason:s})}return!r.isNotDisplayed&&o||r.isNotDisplayed?.()?e({success:!1,reason:r.getNotDisplayedReason?.()??"unknown_reason"}):r.isDismissedMoment()?void 0:(this.styleFrame(o),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEach(e=>{e.src.includes(t)&&(e.style.width="100%")})}}class tc{_publicToken;clientsideServices;googleConfig;constructor(e,t){this._publicToken=e,this.clientsideServices=t}async createOneTapClient(){let e;try{({googleClientId:e}=await this.fetchGoogleStart())}catch(e){return{success:!1,reason:d.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new tn(await ew(r,()=>window.google.accounts.id),e)}}createOnSuccessHandler=({loginRedirectUrl:e,signupRedirectUrl:t,onSuccess:r})=>async s=>{let{credential:i}=s,{redirect_url:a}=await this.submitGoogleOneTapToken({credential:i,loginRedirectUrl:e,signupRedirectUrl:t});r(a)};fetchGoogleStart(){return this.googleConfig||(this.googleConfig=this.clientsideServices.oneTapStart({publicToken:this._publicToken})),this.googleConfig}async submitGoogleOneTapToken({credential:e,loginRedirectUrl:t,signupRedirectUrl:r}){let{oauthCallbackId:s}=await this.fetchGoogleStart();return this.clientsideServices.oneTapSubmit({publicToken:this._publicToken,idToken:e,loginRedirectURL:t,oauthCallbackID:s,signupRedirectURL:r})}redirectOnSuccess=e=>{window.location.href=e};static willGoogleOneTapShowEmbedded(e=navigator.userAgent){let t=(e,t)=>-1!==e.indexOf(t),r=t(e,"iPad")||t(e,"Android")&&!t(e,"Mobile")||t(e,"Silk"),s=t(e,"iPod")||t(e,"iPhone")||t(e,"Android")||t(e,"IEMobile");return!r&&s}}function tl(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class th{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await th.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{e_("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let r=Array.from(t).map(tl).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:r}}}function tu(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)e[s]=r[s]}return e}var td=function e(t,r){function s(e,s,i){if("u">typeof document){"number"==typeof(i=tu({},r,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var o in i)i[o]&&(a+="; "+o,!0!==i[o]&&(a+="="+i[o].split(";")[0]));return document.cookie=e+"="+t.write(s,e)+a}}return Object.create({set:s,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],s={},i=0;i<r.length;i++){var a=r[i].split("="),o=a.slice(1).join("=");try{var n=decodeURIComponent(a[0]);if(s[n]=t.read(o,n),e===n)break}catch(e){}}return e?s[e]:s}},remove:function(e,t){s(e,"",tu({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,tu({},this.attributes,t))},withConverter:function(t){return e(tu({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let tp=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[r]=t.split("=");return e===r}).length>1,t_=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function tm(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,r){let s=t_(t,r);try{return e.getItem(s)}catch{return null}},setItem(t,r,s){let i=t_(t,r);try{s&&e.setItem(i,s)}catch{}},removeItem(t,r){let s=t_(t,r);try{e.removeItem(s)}catch{}}}}let ty=tm(globalThis.localStorage),tg=tm(globalThis.sessionStorage);function tw(e,t){return{getItem:r=>e.getItem(t,r),setItem(r,s){e.setItem(t,r,s)},removeItem(r){e.removeItem(t,r)}}}let tS="seen_domains";class tb{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let r;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=tw(ty,e),this.browserSessionStorage=tw(tg,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const s=this._localStorage.getItem("");if(!s)return;try{r=JSON.parse(s)}catch{this.syncToLocalStorage();return}this.state=r}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:td.get(this.opaqueTokenCookieName),session_jwt:td.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return td.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:r,session_jwt:s}=e,i=tb.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});i.domain&&this.addSeenDomain(i.domain),td.set(this.opaqueTokenCookieName,r,i),td.set(this.jwtCookieName,s,i);let a=tb.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});a.domain&&this.addSeenDomain(a.domain),tp(this.jwtCookieName)&&td.remove(this.jwtCookieName,a),tp(this.opaqueTokenCookieName)&&td.remove(this.opaqueTokenCookieName,a),tp(this.jwtCookieName)&&e_("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),tp(this.opaqueTokenCookieName)&&e_("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),r=tb.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});td.set(this.istCookieName,e,r)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}removeCookies(e){let t=this.getSeenDomains(),r=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(s=>{r.forEach(r=>{let i=tb.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:s,domain:r});e.forEach(e=>{td.remove(e,i)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(tS);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(tS,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:r,expiresAt:s}){let i={expires:new Date(s),sameSite:"lax"};return e&&(i.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?i.secure=!1:(r&&(i.domain=t||window.location.host),i.secure=!0),i}}class tf extends tb{}let tk=Symbol.for("__stytch_DataLayer"),tC=(e,t)=>{Object.values(e).forEach(e=>e(t))},tA=(({KEYS_TO_EXCLUDE:e=[]}={})=>{let t=(r,s)=>typeof r==typeof s&&(null===r||null===s?r===s:"object"==typeof r?!(Object.keys(r).length!==Object.keys(s).length||Object.keys(r).some(e=>!(e in s)))&&Object.entries(r).filter(([t])=>!e.includes(t)).every(([e,r])=>t(r,s[e])):r===s);return t})({KEYS_TO_EXCLUDE:["last_accessed_at"]});class tv{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:r}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!r){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==t_(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let r=this._datalayer.state,s=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=s;let i=this.getFromCache();if(this.setCacheRefreshed(),i||!tA(r,s)){let e;e=null==s||t.fromCache?s:{...s,sessionDurationMinutes:t.sessionDurationMinutes},tC(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let r=this._datalayer.state,s=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=s;let i=this.getFromCache();this.setCacheRefreshed();let a=!tA(r,s);(i||a)&&(tC(this._datalayer.subscriptions,s),a&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:r}=e,s={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:r};"string"==typeof t||"string"==typeof r?(this._datalayer.writeSessionCookie(s),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let r;return t=this._datalayer.subscriptions,t[r=Math.random().toString(36).slice(-10)]=e,()=>delete t[r]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class tP extends tv{updateUser=e=>this.updateState({user:e});getUser=()=>this.getState()?.user??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{let{session:r,user:s,session_jwt:i,session_token:a}=e;a&&i?this.updateStateAndTokens({state:{session:r,user:s},session_jwt:i,session_token:a,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes}):this.updateStateAndTokens({state:{session:r,user:s},session_token:!0,session_jwt:!0,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async(...t)=>{let r=await e(...t);if(null!=r){let e=t.find(e=>null!=e&&"string"!=typeof e);this.updateSession(r,{sessionDurationMinutes:e?.session_duration_minutes})}return r}}let tT=Symbol.for("stytch__internal_b2c");class tE{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;user;magicLinks;session;otps;oauth;cryptoWallets;totps;webauthn;passwords;impersonation;rbac;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchClient()` instead.");(e=>{"string"!=typeof e?e_(`Public token is malformed. Expected a string, got ${typeof e}.${ey}`):""===e?e_(`Public token is malformed. Expected "public-token-...", got an empty string.${ey}`):e.startsWith("public-token-")||e_(`Public token is malformed. Expected "public-token-...", got ${e}.${ey}`)})(e);const r=e??"",s=((e,t={})=>{let{cookieOptions:r,keepSessionAlive:s}=t;return eC(e,t,{keepSessionAlive:"optionalBoolean"}),r&&eC(`${e}.cookieOptions`,r,{opaqueTokenCookieName:"optionalString",jwtCookieName:"optionalString",istCookieName:"optionalString",path:"optionalString",domain:"optionalString"}),{cookieOptions:r,keepSessionAlive:s,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.customBaseUrl?"customBaseUrl":"testApiDomain";e_(`Unable to use custom API domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.customBaseUrl?"customBaseUrl":"apiDomain";e_(`Unable to use custom API domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";e_(`Unable to use custom DFPPA domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";e_(`Unable to use custom DFP CDN domain \`${t}\`. ${r} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),i=((e,t={})=>{let{customBaseUrl:r,endpointOptions:s}=t;return e.includes("public-token-test")?!!(r||s?.testApiDomain):!!(r||s?.apiDomain)})(r,t);this._dataLayer=((e,t)=>{let r,s=((r=window)[tk]||(r[tk]={}),r[tk]);return s[e]||(s[e]=new tf(e,t)),s[e]})(r,s),this._subscriptionService=new tP(r,this._dataLayer,{usingCustomApiEndpoint:i}),this._stateChangeClient=new e8(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const a=()=>({stytch_user_id:this._dataLayer.state?.user?.user_id,stytch_session_id:this._dataLayer.state?.session?.session_id}),o=new th(this._dataLayer,"passwords"),n=new ti(r,this._dataLayer,s.endpoints.liveAPIURL,s.endpoints.testAPIURL,a);this._networkClient=n;const c=new te(r,this._networkClient,this._dataLayer),l=new tt(c.getAsync()),h=new eb(r,s.endpoints.dfpBackendURL,s.endpoints.dfpCdnURL,c.getAsync(),l.executeRecaptcha),u=new tr(s.endpoints.clientsideServicesIframeURL),d=new tc(r,u),p=new e4(this._networkClient,h);this.user=new eK(this._networkClient,this._subscriptionService),this.session=new eF(this._networkClient,this._subscriptionService),this.magicLinks=new eO(this._networkClient,this._subscriptionService,new th(this._dataLayer,"magic_links"),o,c.getAsync(),h),this.otps=new eB(this._networkClient,this._subscriptionService,l.executeRecaptcha,h),this.oauth=new ts(this._networkClient,this._subscriptionService,new th(this._dataLayer,"oauth"),c.getAsync(),{publicToken:r,testAPIURL:s.endpoints.testAPIURL,liveAPIURL:s.endpoints.liveAPIURL},d),this.cryptoWallets=new eP(this._networkClient,this._networkClient,this._subscriptionService,l.executeRecaptcha,h,c.getAsync()),this.totps=new eN(this._networkClient,this._subscriptionService,h),this.webauthn=new e2(this._networkClient,this._subscriptionService,h),this.passwords=new eU(this._networkClient,this._subscriptionService,o,c.getAsync(),h),this.impersonation=new eE(this._networkClient,this._subscriptionService,h),this.rbac=new eL(c.getSync(),c.getAsync(),this._subscriptionService),this.idp=new eT(this._networkClient),this._sessionManager=new e5(this._subscriptionService,this.session,r,{keepSessionAlive:s.keepSessionAlive}),(i||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh(),this._networkClient.logEvent({name:"sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),c.getAsync().then(e=>{"B2B"===e.vertical&&em("This application is using a Stytch client for Consumer projects, but the public token is for a Stytch B2B project. Use a B2B Stytch client instead, or verify that the public token is correct.")});const{authenticateByUrl:_,parseAuthenticateUrl:m}=(e=>{let t=Object.keys(e),r=(e=window.location.href)=>{let r=new URL(e),s=r.searchParams.get("stytch_token_type"),i=r.searchParams.get("token");return i&&s?t.includes(s)?{handled:!0,token:i,tokenType:s}:{handled:!1,token:i,tokenType:s}:null};return{authenticateByUrl:async({clearParams:t,...s},i=window.location.href)=>{let a,o,n,c=t??i===window.location.href,l=r(i);if(null==l)return null;if(!l.handled)return l;let{token:h,tokenType:u}=l,d=e[u];return c&&((o=(a=new URL(window.location.toString())).searchParams).delete("token"),o.delete("stytch_token_type"),n=a,window.history.replaceState(null,document.title,n)),{handled:!0,tokenType:u,data:await d(h,s)}},parseAuthenticateUrl:r}})({magic_links:(e,t)=>this.magicLinks.authenticate(e,t),oauth:(e,t)=>this.oauth.authenticate(e,t),impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=_,this.parseAuthenticateUrl=m,((e,t)=>{Object.assign(e,{[tT]:t})})(this,{bootstrap:c,clientsideServices:u,captcha:l,oneTap:d,searchManager:p,publicToken:r,dataLayer:this._dataLayer,networkClient:this._networkClient})}}let tD=Symbol("__stytch_SSRStubKey"),tO=e=>new Proxy(()=>{},{get:(t,r)=>r===tD||tO(e+"."+String(r)),apply(){throw Error(`[Stytch] Invalid server-side function call to ${e}.
15
+ You can find your public token at https://stytch.com/dashboard/api-keys.`,eg={};async function ew(e,t){var r,s;return void 0!==eg[e]||(eg[e]=(r=e,s=t,new Promise((e,t)=>{var i;let a,o=function(e){let t=document.querySelectorAll(`script[src="${e}"]`);if(t[0])return t[0]}(r);if(o&&"true"===o.dataset.loaded)try{e(s())}catch(e){return t(Error(`${r} already loaded, but module was not found in global scope: ${e}`))}let n=(i=r,(a=document.createElement("script")).setAttribute("src",i),a.setAttribute("async","true"),a.setAttribute("defer","true"),document.head.appendChild(a),a);n.addEventListener("load",()=>{n.dataset.loaded="true";try{e(s())}catch(e){t(Error(`${r} was loaded, but module was not found in global scope: ${e}`))}}),n.addEventListener("error",e=>{t(Error(`${r} could not be loaded: ${e}`))})}))),eg[e]}let eS=e=>{let{__user:t,...r}=e;return r};class eb{bootstrapPromise;state;constructor(e,t,r,s,i=()=>Promise.resolve(void 0)){this.bootstrapPromise=s,this.state=s.then(async s=>s.runDFPProtectedAuth?(await ew(`${r}/telemetry.js`,()=>window.GetTelemetryID),{publicToken:e,dfpBackendURL:t,enabled:!0,mode:s.dfpProtectedAuthMode||"OBSERVATION",loaded:!0,executeRecaptcha:i}):{publicToken:e,dfpBackendURL:t,enabled:!1,loaded:!1,executeRecaptcha:i})}isEnabled=async()=>this.state.then(e=>e.enabled);getTelemetryID=async()=>{let{publicToken:e,enabled:t,dfpBackendURL:r}=await this.state;if(t)return await window.GetTelemetryID(e,`${r}/submit`)};getDFPTelemetryIDAndCaptcha=async()=>{let e,t,{enabled:r,executeRecaptcha:s,mode:i}=await this.state;return r||(t=await s()),"DECISIONING"===i?e=await this.getTelemetryID():"OBSERVATION"===i&&(e=await this.getTelemetryID(),t=await s()),{dfp_telemetry_id:e,captcha_token:t}};retryWithCaptchaAndDFP=async(e,t)=>{let{enabled:r,executeRecaptcha:s}=await this.state;if(e.type===er.RequiredCaptcha&&r)return t.body&&(t.body.dfp_telemetry_id=await this.getTelemetryID(),t.body.captcha_token=await s()),t;throw Error("Unable to query captcha and/or dfp telemetry ID")}}class ef{static inflate(e,t){let r=new e(t);return Object.assign(r,t),Object.setPrototypeOf(r,e.prototype),r}static unmarshall(e){if("name"in e)switch(e.name){case"SDKAPIUnreachableError":return ef.inflate(i,e);case"StytchSDKSchemaError":return ef.inflate(o,e);case"StytchAPIUnreachableError":return ef.inflate(h,e);case"StytchAPISchemaError":return ef.inflate(u,e);case"StytchSDKAPIError":return ef.inflate(n,e);case"StytchAPIError":return ef.inflate(d,e);case"TypeError":return ef.inflate(TypeError,e);case"SyntaxError":return ef.inflate(SyntaxError,e);case"ReferenceError":return ef.inflate(ReferenceError,e);case"RangeError":return ef.inflate(RangeError,e);case"EvalError":return ef.inflate(EvalError,e);case"URIError":return ef.inflate(URIError,e)}return ef.inflate(Error,e)}}class ek{maxBatchSize;logEventURL;batch;constructor(e){this.maxBatchSize=e.maxBatchSize,this.logEventURL=e.logEventURL,setInterval(this.flush.bind(this),e.intervalDurationMs),this.batch=[]}logEvent(e,t){this.batch.push({telemetry:e,event:t}),this.batch.length>=this.maxBatchSize&&this.flush()}async flush(){if(!this.batch.length)return;let e=this.batch;this.batch=[];try{await fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}}let eC=(e,t,r)=>{let s=[];for(let[i,o]of Object.entries(r)){if(null==o)continue;let r=t[i];if(!o.startsWith("optional")||null!=r)switch(o){case"object":case"optionalObject":("object"!=typeof r||Array.isArray(r)||null===r)&&s.push(new a(e,`${i} must be an object.`));break;case"string":case"optionalString":"string"!=typeof r&&s.push(new a(e,`${i} must be a string.`));break;case"number":case"optionalNumber":"number"!=typeof r&&s.push(new a(e,`${i} must be a number.`));break;case"stringArray":case"optionalStringArray":Array.isArray(r)&&r.every(e=>"string"==typeof e)||s.push(new a(e,`${i} must be an array of strings.`));break;case"boolean":case"optionalBoolean":"boolean"!=typeof r&&s.push(new a(e,`${i} must be a boolean.`))}}if(s.length>0)if(1===s.length)throw s[0];else throw AggregateError(s)};Promise.resolve({pkceRequiredForEmailMagicLinks:!1}),Promise.resolve({pkceRequiredForPasswordResets:!1});class eA{roles;resources;rolesByID;constructor(e,t){this.roles=e,this.resources=t,this.rolesByID={},e.forEach(e=>this.rolesByID[e.role_id]=e)}static fromJSON(e){return new eA(e.roles,e.resources)}mergeWithCustomRoles(e){return new eA([...this.roles,...e],this.resources)}callerIsAuthorized(e,t,r){return!!e.map(e=>this.rolesByID[e]).filter(e=>e).flatMap(e=>e.permissions).filter(e=>e.resource_id===t).find(e=>e.actions.includes(r)||e.actions.includes("*"))}allPermissionsForCaller(e){let t=Object.create(null);return this.resources.forEach(r=>{t[r.resource_id]={},r.actions.forEach(s=>{t[r.resource_id][s]=this.callerIsAuthorized(e,r.resource_id,s)})}),t}}let ev=Promise.resolve({siweRequiredForCryptoWallets:!1});class eP{_networkClient;_apiNetworkClient;_subscriptionService;executeRecaptcha;dfpProtectedAuth;_config;authenticate;constructor(e,t,r,s=()=>Promise.resolve(void 0),i,a=ev){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=r,this.executeRecaptcha=s,this.dfpProtectedAuth=i,this._config=a,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.cryptoWallets.authenticate",e,{signature:"string",crypto_wallet_address:"string",crypto_wallet_type:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._apiNetworkClient.retriableFetchSDK({url:"/crypto_wallets/authenticate",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,crypto_wallet_address:e.crypto_wallet_address,crypto_wallet_type:e.crypto_wallet_type,signature:e.signature,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async authenticateStart(e){eC("stytch.cryptoWallets.authenticateStart",e,{crypto_wallet_address:"string",crypto_wallet_type:"string"}),e.siwe_params&&eC("stytch.cryptoWallets.authenticateStart",e.siwe_params,{uri:"optionalString",chain_id:"optionalString",issued_at:"optionalString",statement:"optionalString",not_before:"optionalString",message_request_id:"optionalString",resources:"optionalStringArray"});let t=!!this._subscriptionService.getSession(),r=await this.executeRecaptcha(),{siweRequiredForCryptoWallets:s}=await this._config,i={crypto_wallet_address:e.crypto_wallet_address,crypto_wallet_type:e.crypto_wallet_type};s&&"ethereum"==e.crypto_wallet_type&&(i.siwe_params={...e.siwe_params,uri:e.siwe_params?.uri||window.location.origin});let a={...i,captcha_token:r};return this._apiNetworkClient.fetchSDK({url:t?"/crypto_wallets/authenticate/start/secondary":"/crypto_wallets/authenticate/start/primary",method:"POST",body:a})}}class eT{_networkClient;constructor(e){this._networkClient=e}oauthAuthorizeStart=async e=>this._networkClient.fetchSDK({url:"/idp/oauth/authorize/start",method:"POST",body:e});oauthAuthorizeSubmit=async e=>this._networkClient.fetchSDK({url:"/idp/oauth/authorize/submit",method:"POST",body:e});oauthLogoutStart=async e=>this._networkClient.fetchSDK({url:"/oauth/logout/start",method:"POST",body:e})}class eE{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.impersonation.authenticate",e,{impersonation_token:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/impersonation/authenticate",body:{...e,dfp_telemetry_id:t,captcha_token:r},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}let eD=Promise.resolve({pkceRequiredForEmailMagicLinks:!1});class eO{_networkClient;_subscriptionService;_pkceManager;_passwordResetPKCEManager;_config;dfpProtectedAuth;email;authenticate;constructor(e,t,r,s,i=eD,a){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._passwordResetPKCEManager=s,this._config=i,this.dfpProtectedAuth=a,this.email={loginOrCreate:async(e,t={})=>{let r,{pkceRequiredForEmailMagicLinks:s}=await this._config;s&&(r=await this.getCodeChallenge());let{dfp_telemetry_id:i,captcha_token:a}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),o={...t,email:e,code_challenge:r,captcha_token:a,dfp_telemetry_id:i};return this._networkClient.retriableFetchSDK({url:"/magic_links/email/login_or_create",body:o,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t={})=>{let r,{pkceRequiredForEmailMagicLinks:s}=await this._config;s&&(r=await this.getCodeChallenge());let{dfp_telemetry_id:i,captcha_token:a}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),o={...t,email:e,code_challenge:r,captcha_token:a,dfp_telemetry_id:i},n=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:n?"/magic_links/email/send/secondary":"/magic_links/email/send/primary",body:o,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}},this.authenticate=this._subscriptionService.withUpdateSession(async(e,t)=>{eC("stytch.magicLinks.authenticate",{token:e,...t},{token:"string",session_duration_minutes:"number"});let r=await this._passwordResetPKCEManager.getPKPair(),s=null;if(r?.code_verifier)try{s=await this.handlePKCEForAuthenticate(this._passwordResetPKCEManager,{token:e,...t})}catch(e){if(e.message.includes("pkce"))console.log("Authenticate with passwords pkce namespace failed. Falling back to authenticate with magic_links namespace.");else throw e}return s||(s=await this.handlePKCEForAuthenticate(this._pkceManager,{token:e,...t})),eS(s)})}async getCodeChallenge(){let e=await this._pkceManager.getPKPair();return e?e.code_challenge:(e=await this._pkceManager.startPKCETransaction()).code_challenge}async handlePKCEForAuthenticate(e,t){let r=await e.getPKPair(),s={code_verifier:r?.code_verifier,...t},i=await this._networkClient.fetchSDK({url:"/magic_links/authenticate",body:s,method:"POST"});return e.clearPKPair(),i}}let eI=class{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;authenticate;constructor(e,t,r,s,i){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._dynamicConfig=s,this._config=i,this.authenticate=this._subscriptionService.withUpdateSession(async(e,t)=>{eC("stytch.oauth.authenticate",{token:e,...t},{token:"string",session_duration_minutes:"number"});let r=await this._pkceManager.getPKPair();r||e_("No code verifier found in local storage for OAuth flow.\nConsider using stytch.oauth.$provider.start() to add PKCE to your OAuth flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let s=await this._networkClient.fetchSDK({url:"/oauth/authenticate",method:"POST",body:{token:e,code_verifier:r?.code_verifier,...t}});return this._pkceManager.clearPKPair(),eS(s)})}google={start:this.startOAuthFlow(J.Google)};apple={start:this.startOAuthFlow(J.Apple)};microsoft={start:this.startOAuthFlow(J.Microsoft)};github={start:this.startOAuthFlow(J.Github)};gitlab={start:this.startOAuthFlow(J.GitLab)};facebook={start:this.startOAuthFlow(J.Facebook)};discord={start:this.startOAuthFlow(J.Discord)};salesforce={start:this.startOAuthFlow(J.Salesforce)};slack={start:this.startOAuthFlow(J.Slack)};amazon={start:this.startOAuthFlow(J.Amazon)};bitbucket={start:this.startOAuthFlow(J.Bitbucket)};linkedin={start:this.startOAuthFlow(J.LinkedIn)};coinbase={start:this.startOAuthFlow(J.Coinbase)};twitch={start:this.startOAuthFlow(J.Twitch)};twitter={start:this.startOAuthFlow(J.Twitter)};tiktok={start:this.startOAuthFlow(J.TikTok)};snapchat={start:this.startOAuthFlow(J.Snapchat)};figma={start:this.startOAuthFlow(J.Figma)};yahoo={start:this.startOAuthFlow(J.Yahoo)};async attach(e){return eC("stytch.oauth.attach",{provider:e},{provider:"string"}),await this._networkClient.fetchSDK({url:"/oauth/attach",method:"POST",body:{provider:e}})}async getBaseApiUrl(){let{cnameDomain:e}=await this._dynamicConfig;return e?`https://${e}`:this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}startOAuthFlow(e){return async({login_redirect_url:t,signup_redirect_url:r,custom_scopes:s,provider_params:i,oauth_attach_token:a}={})=>{let{cnameDomain:o,pkceRequiredForOAuth:n}=await this._dynamicConfig,c=await this.getBaseApiUrl();this._networkClient.logEvent({name:"start_oauth_flow",details:{provider_type:e,custom_scopes:s,cname_domain:o,pkce:n,provider_params:i}});let l=new URL(`${c}/v1/public/oauth/${e}/start`);if(l.searchParams.set("public_token",this._config.publicToken),n){let e=await this._pkceManager.startPKCETransaction();l.searchParams.set("code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();if(s&&(eC("startOAuthFlow",{custom_scopes:s},{custom_scopes:"stringArray"}),l.searchParams.set("custom_scopes",s.join(" "))),i)for(let e in eC("startOAuthFlow",{provider_params:i},{provider_params:"optionalObject"}),i)l.searchParams.set("provider_"+e,i[e]);t&&l.searchParams.set("login_redirect_url",t),r&&l.searchParams.set("signup_redirect_url",r),a&&l.searchParams.set("oauth_attach_token",a),this.navigate(l)}}navigate(e){window.location.href=e.toString()}};class eB{_networkClient;_subscriptionService;executeRecaptcha;dfpProtectedAuth;authenticate;constructor(e,t,r=()=>Promise.resolve(void 0),s){this._networkClient=e,this._subscriptionService=t,this.executeRecaptcha=r,this.dfpProtectedAuth=s,this.authenticate=this._subscriptionService.withUpdateSession(async(e,t,r)=>{eC("stytch.otps.authenticate",{code:e,...r},{code:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:s,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),a={token:e,method_id:t,dfp_telemetry_id:s,captcha_token:i,...r};return eS(await this._networkClient.retriableFetchSDK({url:"/otps/authenticate",body:a,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}sms={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r};return this._networkClient.retriableFetchSDK({url:"/otps/sms/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r},a=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:a?"/otps/sms/send/secondary":"/otps/sms/send/primary",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}};whatsapp={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,dfp_telemetry_id:r,captcha_token:s};return this._networkClient.retriableFetchSDK({url:"/otps/whatsapp/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,phone_number:e,captcha_token:s,dfp_telemetry_id:r},a=!!this._subscriptionService.getSession();return this._networkClient.retriableFetchSDK({url:a?"/otps/whatsapp/send/secondary":"/otps/whatsapp/send/primary",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}};email={loginOrCreate:async(e,t)=>{let{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),i={...t,email:e,captcha_token:s,dfp_telemetry_id:r};return this._networkClient.retriableFetchSDK({url:"/otps/email/login_or_create",body:i,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},send:async(e,t)=>{let r=await this.executeRecaptcha(),s={...t,email:e,captcha_token:r},i=!!this._subscriptionService.getSession();return this._networkClient.fetchSDK({url:i?"/otps/email/send/secondary":"/otps/email/send/primary",body:s,method:"POST"})}}}let eR=Promise.resolve({pkceRequiredForPasswordResets:!1});class eU{_networkClient;_subscriptionService;_pkceManager;_config;dfpProtectedAuth;create;authenticate;resetByEmail;resetByExistingPassword;resetBySession;constructor(e,t,r,s=eR,i){this._networkClient=e,this._subscriptionService=t,this._pkceManager=r,this._config=s,this.dfpProtectedAuth=i,this.create=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.create",e,{password:"string",email:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords",method:"POST",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.authenticate",e,{password:"string",email:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords/authenticate",method:"POST",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.resetByEmail=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByEmail",e,{token:"string",password:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._pkceManager.getPKPair(),i=s?.code_verifier,a=await this._networkClient.retriableFetchSDK({url:"/passwords/email/reset",method:"POST",body:{token:e.token,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:r,code_verifier:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),eS(a)}),this.resetByExistingPassword=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetByExistingPassword",e,{email:"string",existing_password:"string",new_password:"string",session_duration_minutes:"number"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/passwords/existing_password/reset",method:"POST",body:{email:e.email,existing_password:e.existing_password,new_password:e.new_password,session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.resetBySession=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.passwords.resetBySession",e,{password:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/passwords/session/reset",method:"POST",body:{password:e.password,session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async getCodeChallenge(){let{pkceRequiredForPasswordResets:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async resetByEmailStart(e){eC("stytch.passwords.resetByEmailStart",e,{email:"string",login_redirect_url:"optionalString",reset_password_redirect_url:"optionalString",reset_password_template_id:"optionalString",reset_password_expiration_minutes:"optionalNumber",locale:"optionalString"});let t=await this.getCodeChallenge(),{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/passwords/email/reset/start",method:"POST",body:{email:e.email,login_redirect_url:e.login_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,locale:e.locale,code_challenge:t,captcha_token:s,dfp_telemetry_id:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async strengthCheck(e){return eC("stytch.passwords.strengthCheck",e,{email:"optionalString",password:"string"}),this._networkClient.fetchSDK({url:"/passwords/strength_check",method:"POST",body:{email:e.email,password:e.password}})}}class eL{_subscriptionService;cachedPolicy;policyPromise;constructor(e,t,r){this._subscriptionService=r,this.cachedPolicy=e.rbacPolicy?eA.fromJSON(e.rbacPolicy):null,this.policyPromise=t.then(e=>e.rbacPolicy?(this.cachedPolicy=eA.fromJSON(e.rbacPolicy),this.cachedPolicy):(em("Unable to retrieve RBAC policy from servers. Assuming caller has no permissions."),new eA([],[])))}allPermissions(){return this.policyPromise.then(e=>e.allPermissionsForCaller(this.roleIds()))}isAuthorizedSync=(e,t)=>!!this.cachedPolicy?.callerIsAuthorized(this.roleIds(),e,t);isAuthorized=(e,t)=>this.policyPromise.then(r=>r.callerIsAuthorized(this.roleIds(),e,t));roleIds(){let e=this._subscriptionService.getUser();return e?e.roles??[]:[]}}class eF{_networkClient;_subscriptionService;authenticate;exchangeAccessToken;attest;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.authenticate=this._subscriptionService.withUpdateSession(this._authenticate),this.exchangeAccessToken=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.exchangeAccessToken",e,{access_token:"string",session_duration_minutes:"number"}),eS(await this._networkClient.fetchSDK({url:"/sessions/exchange_access_token",body:e,method:"POST"})))),this.attest=this._subscriptionService.withUpdateSession(async e=>(eC("stytch.session.attest",e,{profile_id:"string",token:"string",session_duration_minutes:"optionalNumber"}),this._networkClient.fetchSDK({url:"/sessions/attest",body:e,method:"POST"})))}getSync=()=>this._subscriptionService.getSession();getInfo=()=>({session:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>{let t=this._subscriptionService.getSession();return this._subscriptionService.subscribeToState(r=>{r?.session!==t&&e(t=r?.session??null)})};revoke=async e=>{try{let e=await this._networkClient.fetchSDK({url:"/sessions/revoke",method:"POST"});return this._subscriptionService.destroyState(),e}catch(t){throw e?.forceClear?this._subscriptionService.destroyState():c.includes(t.error_type)&&this._subscriptionService.destroyState(),t}};_authenticate=async e=>{let t=this._subscriptionService.getSession(),r=()=>t?.session_id!==this._subscriptionService.getSession()?.session_id;try{let t={session_duration_minutes:e?.session_duration_minutes},s=await this._networkClient.fetchSDK({url:"/sessions/authenticate",body:t,method:"POST"});if(r())return this._authenticate(e);return eS(s)}catch(t){if(r())return this._authenticate(e);throw c.includes(t.error_type)&&this._subscriptionService.destroySession(),t}};getTokens(){return this._subscriptionService.getTokens()}updateSession(e){eC("stytch.session.updateSession",e,{session_token:"string",session_jwt:"optionalString"}),this._subscriptionService.updateTokens(e)}}class eN{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;recover;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.totps.authenticate",e,{session_duration_minutes:"number",totp_code:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/totps/authenticate",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,totp_code:e.totp_code,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))}),this.recover=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.totps.recover",e,{session_duration_minutes:"number",recovery_code:"string"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return eS(await this._networkClient.retriableFetchSDK({url:"/totps/recover",method:"POST",body:{session_duration_minutes:e.session_duration_minutes,recovery_code:e.recovery_code,captcha_token:r,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async create(e){eC("stytch.totps.create",e,{expiration_minutes:"number"});let t=await this._networkClient.fetchSDK({url:"/totps",method:"POST",body:{expiration_minutes:e.expiration_minutes}});return this._subscriptionService.updateUser(t.__user),eS(t)}async recoveryCodes(){return this._networkClient.fetchSDK({url:"/totps/recovery_codes",method:"POST"})}}class eK{_networkClient;_subscriptionService;constructor(e,t){this._networkClient=e,this._subscriptionService=t}get=async()=>{let e=(({request_id:e,status_code:t,...r})=>r)(await this._networkClient.fetchSDK({url:"/users/me",method:"GET"}));return this._subscriptionService.updateUser(e),e};getSync=()=>this._subscriptionService.getUser();getInfo=()=>({user:this.getSync(),fromCache:this._subscriptionService.getFromCache()});update=async e=>{eC("stytch.user.update",e,{untrusted_metadata:"optionalObject"});let t=await this._networkClient.fetchSDK({url:"/users/me",body:e,method:"PUT"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteEmail=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/emails/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deletePhoneNumber=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/phone_numbers/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteTOTP=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/totps/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteCryptoWallet=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/crypto_wallets/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteOAuthRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/oauth/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteWebauthnRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/webauthn_registrations/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};deleteBiometricRegistration=async e=>{let t=await this._networkClient.fetchSDK({url:`/users/biometric_registrations/${e}`,method:"DELETE"}),r=(({request_id:e,status_code:t,...r})=>r)(t.__user);return this._subscriptionService.updateUser(r),eS(t)};onChange=e=>{let t=this._subscriptionService.getUser();return this._subscriptionService.subscribeToState(r=>{r?.user!==t&&e(t=r?.user??null)})};getConnectedApps=async()=>await this._networkClient.fetchSDK({url:"/users/connected_apps",method:"GET"});revokedConnectedApp=async e=>await this._networkClient.fetchSDK({url:`/users/connected_apps/${e}/revoke`,method:"POST"})}function ex(e){let t="==".slice(0,(4-e.length%4)%4),r=atob(e.replace(/-/g,"+").replace(/_/g,"/")+t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return s}function eM(e){let t=new Uint8Array(e),r="";for(let e of t)r+=String.fromCharCode(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var e$="copy",ej="convert";function eW(e,t,r){if(t===e$)return r;if(t===ej)return e(r);if(t instanceof Array)return r.map(r=>eW(e,t[0],r));if(t instanceof Object){let s={};for(let[i,a]of Object.entries(t)){if(a.derive){let e=a.derive(r);void 0!==e&&(r[i]=e)}if(!(i in r)){if(a.required)throw Error(`Missing key: ${i}`);continue}if(null==r[i]){s[i]=null;continue}s[i]=eW(e,a.schema,r[i])}return s}}function eq(e,t){return{required:!0,schema:e,derive:t}}function eG(e){return{required:!0,schema:e}}function ez(e){return{required:!1,schema:e}}var eH={type:eG(e$),id:eG(ej),transports:ez(e$)},eJ={appid:ez(e$),appidExclude:ez(e$),credProps:ez(e$)},eV={appid:ez(e$),appidExclude:ez(e$),credProps:ez(e$)},eY={publicKey:eG({rp:eG(e$),user:eG({id:eG(ej),name:eG(e$),displayName:eG(e$)}),challenge:eG(ej),pubKeyCredParams:eG(e$),timeout:ez(e$),excludeCredentials:ez([eH]),authenticatorSelection:ez(e$),attestation:ez(e$),extensions:ez(eJ)}),signal:ez(e$)},eX={type:eG(e$),id:eG(e$),rawId:eG(ej),authenticatorAttachment:ez(e$),response:eG({clientDataJSON:eG(ej),attestationObject:eG(ej),transports:eq(e$,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:eq(eV,e=>e.getClientExtensionResults())},eZ={mediation:ez(e$),publicKey:eG({challenge:eG(ej),timeout:ez(e$),rpId:ez(e$),allowCredentials:ez([eH]),userVerification:ez(e$),extensions:ez(eJ)}),signal:ez(e$)},eQ={type:eG(e$),id:eG(e$),rawId:eG(ej),authenticatorAttachment:ez(e$),response:eG({clientDataJSON:eG(ej),authenticatorData:eG(ej),signature:eG(ej),userHandle:eG(ej)}),clientExtensionResults:eq(eV,e=>e.getClientExtensionResults())};async function e0(e){let t=await navigator.credentials.create(eW(ex,eY,e));return eW(eM,eX,t)}async function e1(e){let t=await navigator.credentials.get(eW(ex,eZ,e));return eW(eM,eQ,t)}class e2{_networkClient;_subscriptionService;dfpProtectedAuth;register;authenticate;constructor(e,t,r){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=r,this.register=this._subscriptionService.withUpdateSession(async e=>{e&&eC("stytch.webauthn.register",e,{domain:"optionalString",authenticator_type:"optionalString",is_passkey:"optionalBoolean",session_duration_minutes:"number",override_id:"optionalString",override_name:"optionalString",override_display_name:"optionalString",use_base64_url_encoding:"optionalBoolean"});let t=JSON.parse((await this._networkClient.fetchSDK({url:"/webauthn/register/start",method:"POST",body:{domain:e?.domain??window.location.hostname,authenticator_type:e?.authenticator_type??void 0,return_passkey_credential_options:e?.is_passkey,override_id:e?.override_id,override_name:e?.override_name,override_display_name:e?.override_display_name,user_agent:navigator.userAgent,use_base64_url_encoding:e?.use_base64_url_encoding}})).public_key_credential_creation_options),r=await e0({publicKey:t});return eS(await this._networkClient.fetchSDK({url:"/webauthn/register",method:"POST",body:{public_key_credential:JSON.stringify(r),session_duration_minutes:e?.session_duration_minutes}}))}),this.authenticate=this._subscriptionService.withUpdateSession(async e=>{eC("stytch.webauthn.authenticate",e,{domain:"optionalString",session_duration_minutes:"number",is_passkey:"optionalBoolean",signal:"optionalObject",conditional_mediation:"optionalBoolean",disable_input_check:"optionalBoolean"});let{dfp_telemetry_id:t,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();if(e.conditional_mediation){if(!await this.browserSupportsAutofill())return em("Browser does not support WebAuthn autofill"),null;if(!e.disable_input_check&&!this.checkEligibleInputs())return null}let s=!!this._subscriptionService.getSession(),i=(await this._networkClient.fetchSDK({url:s?"/webauthn/authenticate/start/secondary":"/webauthn/authenticate/start/primary",method:"POST",body:{domain:e.domain??window.location.hostname,return_passkey_credential_options:e?.is_passkey}})).public_key_credential_request_options,a=new AbortController,o={publicKey:JSON.parse(i),signal:e.signal??a.signal},n={...o,mediation:"conditional"},c=await e1(e.conditional_mediation?n:o);return eS(await this._networkClient.retriableFetchSDK({url:"/webauthn/authenticate",method:"POST",body:{public_key_credential:JSON.stringify(c),session_duration_minutes:e.session_duration_minutes,dfp_telemetry_id:t,captcha_token:r},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP}))})}async update(e){eC("stytch.webauthn.update",e,{webauthn_registration_id:"string",name:"string"});let t="/webauthn/update/"+e.webauthn_registration_id;return await this._networkClient.fetchSDK({url:t,method:"PUT",body:{name:e.name}})}async browserSupportsAutofill(){return await window.PublicKeyCredential?.isConditionalMediationAvailable?.()??!1}checkEligibleInputs=()=>!(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)||(em('No <input> with `"webauthn"` in its `autocomplete` attribute was detected'),!1)}class e6{iframeURL;frame;constructor(e){this.iframeURL=e,this.createIframe()}createIframe(){let e=document.querySelector(`[src~="${this.iframeURL}"]`);if(e?e_(s):((e=document.createElement("iframe")).src=this.iframeURL,e.style.position="absolute",e.style.width="0",e.style.height="0",e.style.border="0",e.role="none",document.body.appendChild(e)),"true"===e.dataset.loaded){this.frame=Promise.resolve(e);return}this.frame=new Promise(t=>{e.addEventListener("load",()=>{e.dataset.loaded="true",t(e)},{once:!0})})}async call(e,t){let r=await this.frame,s=new MessageChannel;return new Promise((i,a)=>{s.port1.onmessage=e=>{let t=e.data;s.port1.close(),t.success?i(t.payload):a(ef.unmarshall(t.error))},r.contentWindow?.postMessage({method:e,args:t},this.iframeURL,[s.port2])})}}class e4{_networkClient;dfpProtectedAuth;constructor(e,t){this._networkClient=e,this.dfpProtectedAuth=t}searchUser(e){return this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha().then(({dfp_telemetry_id:t,captcha_token:r})=>this._networkClient.fetchSDK({url:"/users/search",method:"POST",body:{email:e,dfp_telemetry_id:t,captcha_token:r}}))}searchMember(e,t){return this._networkClient.fetchSDK({url:"/b2b/organizations/members/search",method:"POST",body:{email_address:e,organization_id:t}})}}class e3{hasWarned=!1;registry=new Map;register(e,t){let r=this.registry.get(e);r&&r!==t&&(this.hasWarned||(e_(s),this.hasWarned=!0),r.cancelBackgroundRefresh()),this.registry.set(e,t)}unregister(e,t){let r=this.registry.get(e);r&&r===t&&this.registry.delete(e)}}class e5{_subscriptionService;_headlessSessionClient;_publicToken;_options;static REFRESH_INTERVAL_MS=18e4;timeout=null;lastAuthenticationSessionDuration;static registry=new e3;register(){e5.registry.register(this._publicToken,this)}unregister(){e5.registry.unregister(this._publicToken,this)}constructor(e,t,r,s){this._subscriptionService=e,this._headlessSessionClient=t,this._publicToken=r,this._options=s,this._subscriptionService.subscribeToState(this._onDataChange)}performBackgroundRefresh(){this._reauthenticateWithBackoff().then(()=>{this.scheduleBackgroundRefresh()}).catch(e=>{e_("Session background refresh failed. Signalling to app that user is logged out.",{error:e}),this._subscriptionService.destroySession()})}scheduleBackgroundRefresh(){this.cancelBackgroundRefresh(),this.register(),this.timeout=setTimeout(()=>{this.performBackgroundRefresh()},e5.REFRESH_INTERVAL_MS)}cancelBackgroundRefresh(){null!==this.timeout&&(this.unregister(),clearTimeout(this.timeout),this.timeout=null)}_onDataChange=e=>{null!=e&&e.sessionDurationMinutes&&(this.lastAuthenticationSessionDuration=e.sessionDurationMinutes),e?.session?this.scheduleBackgroundRefresh():this.cancelBackgroundRefresh()};_reauthenticateWithBackoff=async()=>{let e=0;for(;;)try{let e={session_duration_minutes:this._options.keepSessionAlive?this.lastAuthenticationSessionDuration:void 0};return await this._headlessSessionClient.authenticate(e)}catch(t){if(e5.isUnrecoverableError(t))return Promise.reject(t);e++,await new Promise(t=>setTimeout(t,e5.timeoutForAttempt(e)))}};static timeoutForAttempt(e){return e=Math.min(e,7),Math.floor(350*Math.random())-175+2e3*2**e}static isUnrecoverableError(e){return c.includes(e.error_type)}}class e9{_subscriptionService;emptyState;constructor(e,t){this._subscriptionService=e,this.emptyState=t}onStateChange=e=>this._subscriptionService.subscribeToState(t=>{e(t??this.emptyState)})}let e8="bootstrap",e7=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class te{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,r){this._publicToken=e,this._networkClient=t,this._dataLayer=r,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(te.mapBootstrapData).then(e=>(this._dataLayer.setItem(e8,JSON.stringify(e)),e)).catch(e=>(em(e),e7()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(e8);if(null===e)return e7();try{return JSON.parse(e)}catch{return e7()}}getAsync(){return this._bootstrapDataPromise}}class tt{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,ew(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:r}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(r,{action:"LOGIN"})}}class tr{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new e6(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}class ts extends eI{_oneTap;constructor(e,t,r,s,i,a){super(e,t,r,s,i),this._oneTap=a}startOneTap=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:r}=t,s=this._oneTap.createOnSuccessHandler({signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return r.render({style:{position:V.floating},onOneTapCancelled:e.onOneTapCancelled,callback:s,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={start:this.startOneTap}}class ti{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,r,s,i){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=i,this.baseURL=r,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=s),this.eventLogger=new ek({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:r={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:r.error_code,error_description:r.error_description,http_status_code:r.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${eu()}`,app_session_id:`app-session-id-${eu()}`,persistent_id:`persistent-id-${eu()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"@stytch/vanilla-js@6.0.9"}}}async fetchSDK({url:e,body:t,method:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,i="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),a=window.btoa(JSON.stringify(this.createTelemetryBlob())),o=window.location.origin;return ea({basicAuthHeader:i,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:a,xSDKParentHostHeader:o})}async submitFormSDK({url:e,body:t,method:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,i="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),a=window.btoa(JSON.stringify(this.createTelemetryBlob())),o=window.location.origin;return eo({basicAuthHeader:i,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:a,xSDKParentHostHeader:o})}async retriableFetchSDK({url:e,body:t,method:r,retryCallback:s}){let i=this._subscriptionDataLayer.readSessionCookie().session_token,a="Basic "+window.btoa(this._publicToken+":"+(i||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return ei({basicAuthHeader:a,body:t,finalURL:this.buildSDKUrl(e),method:r,xSDKClientHeader:o,xSDKParentHostHeader:n,retryCallback:s})}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}let ta="u">typeof window&&"IdentityCredential"in window,to=e=>e===V.forceLegacyEmbedded?"force":e===V.embeddedOnly||e===V.embedded||e===V.floatingOrEmbedded;class tn{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:r,cancelOnTapOutside:s=!0}){let i,a=to(r.position),o="force"===(i=to(r.position))||i&&!ta,n={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==a,cancel_on_tap_outside:s};return o&&(n.prompt_parent_id="google-parent-prompt",n.cancel_on_tap_outside=!1),this._googleClient.initialize(n),new Promise(e=>{this._googleClient.prompt(r=>{if(r.isSkippedMoment()){let s=r.getSkippedReason?.()??"unknown_reason";return"user_cancel"===s&&t?.(),e({success:!1,reason:s})}return!r.isNotDisplayed&&o||r.isNotDisplayed?.()?e({success:!1,reason:r.getNotDisplayedReason?.()??"unknown_reason"}):r.isDismissedMoment()?void 0:(this.styleFrame(o),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEach(e=>{e.src.includes(t)&&(e.style.width="100%")})}}class tc{_publicToken;clientsideServices;googleConfig;constructor(e,t){this._publicToken=e,this.clientsideServices=t}async createOneTapClient(){let e;try{({googleClientId:e}=await this.fetchGoogleStart())}catch(e){return{success:!1,reason:d.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new tn(await ew(r,()=>window.google.accounts.id),e)}}createOnSuccessHandler=({loginRedirectUrl:e,signupRedirectUrl:t,onSuccess:r})=>async s=>{let{credential:i}=s,{redirect_url:a}=await this.submitGoogleOneTapToken({credential:i,loginRedirectUrl:e,signupRedirectUrl:t});r(a)};fetchGoogleStart(){return this.googleConfig||(this.googleConfig=this.clientsideServices.oneTapStart({publicToken:this._publicToken})),this.googleConfig}async submitGoogleOneTapToken({credential:e,loginRedirectUrl:t,signupRedirectUrl:r}){let{oauthCallbackId:s}=await this.fetchGoogleStart();return this.clientsideServices.oneTapSubmit({publicToken:this._publicToken,idToken:e,loginRedirectURL:t,oauthCallbackID:s,signupRedirectURL:r})}redirectOnSuccess=e=>{window.location.href=e};static willGoogleOneTapShowEmbedded(e=navigator.userAgent){let t=(e,t)=>-1!==e.indexOf(t),r=t(e,"iPad")||t(e,"Android")&&!t(e,"Mobile")||t(e,"Silk"),s=t(e,"iPod")||t(e,"iPhone")||t(e,"Android")||t(e,"IEMobile");return!r&&s}}function tl(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class th{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await th.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{e_("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let r=Array.from(t).map(tl).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:r}}}function tu(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)e[s]=r[s]}return e}var td=function e(t,r){function s(e,s,i){if("u">typeof document){"number"==typeof(i=tu({},r,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var o in i)i[o]&&(a+="; "+o,!0!==i[o]&&(a+="="+i[o].split(";")[0]));return document.cookie=e+"="+t.write(s,e)+a}}return Object.create({set:s,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],s={},i=0;i<r.length;i++){var a=r[i].split("="),o=a.slice(1).join("=");try{var n=decodeURIComponent(a[0]);if(s[n]=t.read(o,n),e===n)break}catch(e){}}return e?s[e]:s}},remove:function(e,t){s(e,"",tu({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,tu({},this.attributes,t))},withConverter:function(t){return e(tu({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let tp=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[r]=t.split("=");return e===r}).length>1,t_=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function tm(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,r){let s=t_(t,r);try{return e.getItem(s)}catch{return null}},setItem(t,r,s){let i=t_(t,r);try{s&&e.setItem(i,s)}catch{}},removeItem(t,r){let s=t_(t,r);try{e.removeItem(s)}catch{}}}}let ty=tm(globalThis.localStorage),tg=tm(globalThis.sessionStorage);function tw(e,t){return{getItem:r=>e.getItem(t,r),setItem(r,s){e.setItem(t,r,s)},removeItem(r){e.removeItem(t,r)}}}let tS="seen_domains";class tb{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let r;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=tw(ty,e),this.browserSessionStorage=tw(tg,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const s=this._localStorage.getItem("");if(!s)return;try{r=JSON.parse(s)}catch{this.syncToLocalStorage();return}this.state=r}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:td.get(this.opaqueTokenCookieName),session_jwt:td.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return td.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:r,session_jwt:s}=e,i=tb.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});i.domain&&this.addSeenDomain(i.domain),td.set(this.opaqueTokenCookieName,r,i),td.set(this.jwtCookieName,s,i);let a=tb.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});a.domain&&this.addSeenDomain(a.domain),tp(this.jwtCookieName)&&td.remove(this.jwtCookieName,a),tp(this.opaqueTokenCookieName)&&td.remove(this.opaqueTokenCookieName,a),tp(this.jwtCookieName)&&e_("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),tp(this.opaqueTokenCookieName)&&e_("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),r=tb.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});td.set(this.istCookieName,e,r)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}removeCookies(e){let t=this.getSeenDomains(),r=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(s=>{r.forEach(r=>{let i=tb.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:s,domain:r});e.forEach(e=>{td.remove(e,i)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(tS);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(tS,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:r,expiresAt:s}){let i={expires:new Date(s),sameSite:"lax"};return e&&(i.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?i.secure=!1:(r&&(i.domain=t||window.location.host),i.secure=!0),i}}class tf extends tb{}let tk=Symbol.for("__stytch_DataLayer"),tC=(e,t)=>{Object.values(e).forEach(e=>e(t))},tA=(({KEYS_TO_EXCLUDE:e=[]}={})=>{let t=(r,s)=>typeof r==typeof s&&(null===r||null===s?r===s:"object"==typeof r?!(Object.keys(r).length!==Object.keys(s).length||Object.keys(r).some(e=>!(e in s)))&&Object.entries(r).filter(([t])=>!e.includes(t)).every(([e,r])=>t(r,s[e])):r===s);return t})({KEYS_TO_EXCLUDE:["last_accessed_at"]});class tv{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:r}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!r){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==t_(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let r=this._datalayer.state,s=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=s;let i=this.getFromCache();if(this.setCacheRefreshed(),i||!tA(r,s)){let e;e=null==s||t.fromCache?s:{...s,sessionDurationMinutes:t.sessionDurationMinutes},tC(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let r=this._datalayer.state,s=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=s;let i=this.getFromCache();this.setCacheRefreshed();let a=!tA(r,s);(i||a)&&(tC(this._datalayer.subscriptions,s),a&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:r}=e,s={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:r};"string"==typeof t||"string"==typeof r?(this._datalayer.writeSessionCookie(s),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let r;return t=this._datalayer.subscriptions,t[r=Math.random().toString(36).slice(-10)]=e,()=>delete t[r]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class tP extends tv{updateUser=e=>this.updateState({user:e});getUser=()=>this.getState()?.user??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{let{session:r,user:s,session_jwt:i,session_token:a}=e;a&&i?this.updateStateAndTokens({state:{session:r,user:s},session_jwt:i,session_token:a,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes}):this.updateStateAndTokens({state:{session:r,user:s},session_token:!0,session_jwt:!0,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async(...t)=>{let r=await e(...t);if(null!=r){let e=t.find(e=>null!=e&&"string"!=typeof e);this.updateSession(r,{sessionDurationMinutes:e?.session_duration_minutes})}return r}}let tT=Symbol.for("stytch__internal_b2c");class tE{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;user;magicLinks;session;otps;oauth;cryptoWallets;totps;webauthn;passwords;impersonation;rbac;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchClient()` instead.");(e=>{"string"!=typeof e?e_(`Public token is malformed. Expected a string, got ${typeof e}.${ey}`):""===e?e_(`Public token is malformed. Expected "public-token-...", got an empty string.${ey}`):e.startsWith("public-token-")||e_(`Public token is malformed. Expected "public-token-...", got ${e}.${ey}`)})(e);const r=e??"",s=((e,t={})=>{let{cookieOptions:r,keepSessionAlive:s}=t;return eC(e,t,{keepSessionAlive:"optionalBoolean"}),r&&eC(`${e}.cookieOptions`,r,{opaqueTokenCookieName:"optionalString",jwtCookieName:"optionalString",istCookieName:"optionalString",path:"optionalString",domain:"optionalString"}),{cookieOptions:r,keepSessionAlive:s,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.customBaseUrl?"customBaseUrl":"testApiDomain";e_(`Unable to use custom API domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.customBaseUrl?"customBaseUrl":"apiDomain";e_(`Unable to use custom API domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";e_(`Unable to use custom DFPPA domain \`${t}\`. ${r} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let r=ed(t);if(r)return r;{let r=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";e_(`Unable to use custom DFP CDN domain \`${t}\`. ${r} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),i=((e,t={})=>{let{customBaseUrl:r,endpointOptions:s}=t;return e.includes("public-token-test")?!!(r||s?.testApiDomain):!!(r||s?.apiDomain)})(r,t);this._dataLayer=((e,t)=>{let r,s=((r=window)[tk]||(r[tk]={}),r[tk]);return s[e]||(s[e]=new tf(e,t)),s[e]})(r,s),this._subscriptionService=new tP(r,this._dataLayer,{usingCustomApiEndpoint:i}),this._stateChangeClient=new e9(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const a=()=>({stytch_user_id:this._dataLayer.state?.user?.user_id,stytch_session_id:this._dataLayer.state?.session?.session_id}),o=new th(this._dataLayer,"passwords"),n=new ti(r,this._dataLayer,s.endpoints.liveAPIURL,s.endpoints.testAPIURL,a);this._networkClient=n;const c=new te(r,this._networkClient,this._dataLayer),l=new tt(c.getAsync()),h=new eb(r,s.endpoints.dfpBackendURL,s.endpoints.dfpCdnURL,c.getAsync(),l.executeRecaptcha),u=new tr(s.endpoints.clientsideServicesIframeURL),d=new tc(r,u),p=new e4(this._networkClient,h);this.user=new eK(this._networkClient,this._subscriptionService),this.session=new eF(this._networkClient,this._subscriptionService),this.magicLinks=new eO(this._networkClient,this._subscriptionService,new th(this._dataLayer,"magic_links"),o,c.getAsync(),h),this.otps=new eB(this._networkClient,this._subscriptionService,l.executeRecaptcha,h),this.oauth=new ts(this._networkClient,this._subscriptionService,new th(this._dataLayer,"oauth"),c.getAsync(),{publicToken:r,testAPIURL:s.endpoints.testAPIURL,liveAPIURL:s.endpoints.liveAPIURL},d),this.cryptoWallets=new eP(this._networkClient,this._networkClient,this._subscriptionService,l.executeRecaptcha,h,c.getAsync()),this.totps=new eN(this._networkClient,this._subscriptionService,h),this.webauthn=new e2(this._networkClient,this._subscriptionService,h),this.passwords=new eU(this._networkClient,this._subscriptionService,o,c.getAsync(),h),this.impersonation=new eE(this._networkClient,this._subscriptionService,h),this.rbac=new eL(c.getSync(),c.getAsync(),this._subscriptionService),this.idp=new eT(this._networkClient),this._sessionManager=new e5(this._subscriptionService,this.session,r,{keepSessionAlive:s.keepSessionAlive}),(i||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh(),this._networkClient.logEvent({name:"sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),c.getAsync().then(e=>{"B2B"===e.vertical&&em("This application is using a Stytch client for Consumer projects, but the public token is for a Stytch B2B project. Use a B2B Stytch client instead, or verify that the public token is correct.")});const{authenticateByUrl:_,parseAuthenticateUrl:m}=(e=>{let t=Object.keys(e),r=(e=window.location.href)=>{let r=new URL(e),s=r.searchParams.get("stytch_token_type"),i=r.searchParams.get("token");return i&&s?t.includes(s)?{handled:!0,token:i,tokenType:s}:{handled:!1,token:i,tokenType:s}:null};return{authenticateByUrl:async({clearParams:t,...s},i=window.location.href)=>{let a,o,n,c=t??i===window.location.href,l=r(i);if(null==l)return null;if(!l.handled)return l;let{token:h,tokenType:u}=l,d=e[u];return c&&((o=(a=new URL(window.location.toString())).searchParams).delete("token"),o.delete("stytch_token_type"),n=a,window.history.replaceState(null,document.title,n)),{handled:!0,tokenType:u,data:await d(h,s)}},parseAuthenticateUrl:r}})({magic_links:(e,t)=>this.magicLinks.authenticate(e,t),oauth:(e,t)=>this.oauth.authenticate(e,t),impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=_,this.parseAuthenticateUrl=m,((e,t)=>{Object.assign(e,{[tT]:t})})(this,{bootstrap:c,clientsideServices:u,captcha:l,oneTap:d,searchManager:p,publicToken:r,dataLayer:this._dataLayer,networkClient:this._networkClient})}}let tD=Symbol("__stytch_SSRStubKey"),tO=e=>new Proxy(()=>{},{get:(t,r)=>r===tD||tO(e+"."+String(r)),apply(){throw Error(`[Stytch] Invalid server-side function call to ${e}.
16
16
  The Stytch JavaScript SDK is intended to only be used on the client side.
17
17
  Make sure to wrap your API calls in a hook to ensure they are executed on the client.
18
18