@stytch/vanilla-js 0.0.0-rc.2 → 0.0.0-rc.3

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.
@@ -1,2 +1,5 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e extends Error{constructor(t,s){super(t+"\n"+s),this.message=t+"\n"+s,this.name="SDKError",this.details=s,Object.setPrototypeOf(this,e.prototype)}}class t extends Error{constructor(e,t){super(),this.name="StytchSDKUsageError",this.message=`Invalid call to ${e}\n`+t}}class s extends Error{constructor(e){super(),this.name="StytchSDKSchemaError";const t=e.body?.map((e=>`${e.dataPath}: ${e.message}`)).join("\n");this.message=`[400] Request does not match expected schema\n${t}`}}class i extends Error{constructor(e){super(),this.name="StytchSDKAPIError";const{status_code:t,error_type:s,error_message:i,error_url:r,request_id:o}=e;this.error_type=s,this.error_message=i,this.error_url=r,this.request_id=o,this.status_code=t,this.message=`[${t}] ${s}\n${i}\nSee ${r} for more information.\n`+(o?`request_id: ${o}\n`:"")}}class r{static marshall(e){return{...e,name:e.name,message:e.message,stack:e.stack}}static inflate(e,t){const s=new e(t);return Object.assign(s,t),Object.setPrototypeOf(s,e.prototype),s}static unmarshall(t){if("name"in t)switch(t.name){case"SDKError":return r.inflate(e,t);case"StytchSDKSchemaError":return r.inflate(s,t);case"StytchSDKAPIError":return r.inflate(i,t);case"TypeError":return r.inflate(TypeError,t);case"SyntaxError":return r.inflate(SyntaxError,t);case"ReferenceError":return r.inflate(ReferenceError,t);case"RangeError":return r.inflate(RangeError,t);case"EvalError":return r.inflate(EvalError,t);case"URIError":return r.inflate(URIError,t)}return r.inflate(Error,t)}}class o{constructor(e){this.iframeURL=e,this.createIframe()}createIframe(){const e=document.querySelector(`[src~="${this.iframeURL}"]`);if(e&&e instanceof HTMLIFrameElement)return void(this.frame=Promise.resolve(e));const t=document.createElement("iframe");t.src=this.iframeURL,t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.border="0",document.body.appendChild(t),this.frame=new Promise((e=>t.onload=()=>e(t)))}async call(e,t){const s=await this.frame,i=new MessageChannel;return new Promise(((o,n)=>{i.port1.onmessage=e=>{const t=e.data;i.port1.close(),t.success?o(t.payload):n(r.unmarshall(t.error))};const a={method:e,args:t};s.contentWindow?.postMessage(a,this.iframeURL,[i.port2])}))}}var n,a=new Uint8Array(16);function c(){if(!n&&!(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(a)}var u=/^(?:[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;function l(e){return"string"==typeof e&&u.test(e)}for(var h,d,p,_,m,g,k=[],w=0;w<256;++w)k.push((w+256).toString(16).substr(1));function y(e,t,s){var i=(e=e||{}).random||(e.rng||c)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){s=s||0;for(var r=0;r<16;++r)t[s+r]=i[r];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=(k[e[t+0]]+k[e[t+1]]+k[e[t+2]]+k[e[t+3]]+"-"+k[e[t+4]]+k[e[t+5]]+"-"+k[e[t+6]]+k[e[t+7]]+"-"+k[e[t+8]]+k[e[t+9]]+"-"+k[e[t+10]]+k[e[t+11]]+k[e[t+12]]+k[e[t+13]]+k[e[t+14]]+k[e[t+15]]).toLowerCase();if(!l(s))throw TypeError("Stringified UUID is invalid");return s}(i)}!function(e){e.emailMagicLinks="emailMagicLinks",e.oauth="oauth",e.otp="otp",e.crypto="crypto"}(h||(h={})),function(e){e.Google="google",e.Microsoft="microsoft",e.Apple="apple",e.Github="github",e.GitLab="gitlab",e.Facebook="facebook",e.Discord="discord",e.Slack="slack",e.Amazon="amazon",e.Bitbucket="bitbucket",e.LinkedIn="linkedin"}(d||(d={})),function(e){e.Vessel="Vessel",e.Phantom="Phantom",e.Metamask="Metamask",e.Coinbase="Coinbase",e.Binance="Binance",e.GenericEthereumWallet="Other Ethereum Wallet",e.GenericSolanaWallet="Other Solana Wallet"}(p||(p={})),function(e){e.embedded="embedded",e.floating="floating"}(_||(_={})),function(e){e.SMS="sms",e.WhatsApp="whatsapp",e.Email="email"}(m||(m={})),function(e){e.MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",e.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",e.OTPsAuthenticate="OTP_AUTHENTICATE",e.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",e.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE_"}(g||(g={}));const S={};async function b(e,t){return void 0!==S[e]||(S[e]=function(e,t){return new Promise(((s,i)=>{if(function(e){return f(e).length>0}(e))try{s(t())}catch(t){return i(new Error(`${e} already loaded, but module was not found in global scope: ${t}`))}const r=function(e){const t=f(e);if(t[0])return t[0];const s=document.createElement("script");return s.setAttribute("src",e),s.setAttribute("async","true"),s.setAttribute("defer","true"),document.head.appendChild(s),s}(e);r.addEventListener("load",(()=>{try{s(t())}catch(t){i(new Error(`${e} was loaded, but module was not found in global scope: ${t}`))}})),r.addEventListener("error",(t=>{i(new Error(`${e} could not be loaded: ${t}`))}))}))}(e,t)),S[e]}const f=e=>document.querySelectorAll(`script[src="${e}"]`);const v=["[Stytch]"],C=(...e)=>console.warn(...v,...e),T=(...e)=>console.error(...v,...e),E=({KEYS_TO_EXCLUDE:e=[]}={})=>{const t=(s,i)=>typeof s==typeof i&&(null===s||null===i?s===i:"object"==typeof s?Object.keys(s).length===Object.keys(i).length&&!Object.keys(s).some((e=>!(e in i)))&&Object.entries(s).filter((([t])=>!e.includes(t))).every((([e,s])=>t(s,i[e]))):s===i);return t},O=e=>{const s={isString:(i,r)=>{if("string"!=typeof r)throw new t(e,i+" must be a string.");return s},isOptionalString:(e,t)=>void 0===t?s:s.isString(e,t),isStringArray:(i,r)=>{if(!Array.isArray(r))throw new t(e,i+" must be an array of strings.");for(const s of r)if("string"!=typeof s)throw new t(e,i+" must be an array of strings.");return s},isNumber:(i,r)=>{if("number"!=typeof r)throw new t(e,i+" must be a number.");return s},isOptionalNumber:(e,t)=>void 0===t?s:s.isNumber(e,t)};return s},P=({request_id:e,status_code:t,...s})=>s,R=e=>{const{__user:t,...s}=e;return s};class L{static REFRESH_INTERVAL_MS=18e4;constructor(e,t){this._subscriptionService=e,this._headlessSessionClient=t,this.timeout=null,this._subscriptionService.subscribeToSession(this._onSessionChange)}performBackgroundRefresh(){this._reauthenticateWithBackoff().then((e=>{this.scheduleBackgroundRefresh(),this._subscriptionService.updateState({session:e.session,session_token:e.session_token,session_jwt:e.session_jwt,user:e.user})})).catch((()=>{C("Session background refresh failed. Signalling to app that user is logged out."),this._subscriptionService.destroyState()}))}scheduleBackgroundRefresh(){this.timeout=setTimeout((()=>{this.timeout=null,this.performBackgroundRefresh()}),L.REFRESH_INTERVAL_MS)}cancelBackgroundRefresh(){null!==this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}_onSessionChange=e=>{e&&null===this.timeout&&this.scheduleBackgroundRefresh(),e||this.cancelBackgroundRefresh()};_reauthenticateWithBackoff=()=>{const e=e=>t=>L.isUnrecoverableRecoverableError(t)?Promise.reject(t):new Promise((t=>setTimeout(t,L.timeoutForAttempt(e)))).then((()=>this._headlessSessionClient.authenticate()));return this._headlessSessionClient.authenticate().catch(e(0)).catch(e(1)).catch(e(2)).catch(e(3)).catch(e(4))};static timeoutForAttempt(e){return Math.floor(350*Math.random())-175+2e3*2**e}static isUnrecoverableRecoverableError(e){return"unauthorized_credentials"===e.error_type}}class A{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;const e=this.batch;this.batch=[];try{await fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(e){}}}class M{constructor(e,t){this._networkClient=e,this._subscriptionService=t}get=async()=>{const e=await this._networkClient.fetchSDK({url:"/users/me",errorMessage:"Failed to retrieve user info.",method:"GET"}),t=P(e);return this._subscriptionService.updateUser(t),t};getSync=()=>this._subscriptionService.getUser();update=async e=>{const t=await this._networkClient.fetchSDK({url:"/users/me",body:e,errorMessage:"Failed to update user.",method:"PUT"}),s=P(t.__user);return this._subscriptionService.updateUser(s),R(t)};deleteEmail=async e=>{const t=await this._networkClient.fetchSDK({url:`/users/emails/${e}`,errorMessage:"Failed to delete email.",method:"DELETE"}),s=P(t.__user);return this._subscriptionService.updateUser(s),R(t)};deletePhoneNumber=async e=>{const t=await this._networkClient.fetchSDK({url:`/users/phone_numbers/${e}`,errorMessage:"Failed to delete phone number.",method:"DELETE"}),s=P(t.__user);return this._subscriptionService.updateUser(s),R(t)};deleteTOTP=async e=>{const t=await this._networkClient.fetchSDK({url:`/users/totps/${e}`,errorMessage:"Failed to delete TOTP.",method:"DELETE"}),s=P(t.__user);return this._subscriptionService.updateUser(s),R(t)};onChange=e=>this._subscriptionService.subscribeToUser(e)}class I{constructor(e,t){this._networkClient=e,this._subscriptionService=t}getSync=()=>this._subscriptionService.getSession();onChange=e=>this._subscriptionService.subscribeToSession(e);revoke=async()=>{const e=await this._networkClient.fetchSDK({url:"/sessions/revoke",errorMessage:"Error revoking session",method:"POST"});try{this._subscriptionService.destroyState()}catch{}return e};authenticate=async e=>{try{const t={session_duration_minutes:e?.session_duration_minutes},s=await this._networkClient.fetchSDK({url:"/sessions/authenticate",body:t,errorMessage:"Error authenticating session",method:"POST"});return this._subscriptionService.updateState({session:s.session,user:s.user,session_token:s.session_token,session_jwt:s.session_jwt}),R(s)}catch(e){throw this._subscriptionService.destroyState(),e}};getTokens(){return this._subscriptionService.getTokens()}}const D=Promise.resolve({pkceRequiredForEmailMagicLinks:!1});class x{constructor(e,t,s,i=D,r=(()=>Promise.resolve(void 0))){this._networkClient=e,this._subscriptionService=t,this._pkceManager=s,this._config=i,this.executeRecaptcha=r}async getCodeChallenge(){let e=this._pkceManager.getPKPair();return e||(e=await this._pkceManager.startPKCETransaction()),e.code_challenge}email={loginOrCreate:async(e,t={})=>{const{pkceRequiredForEmailMagicLinks:s}=await this._config;let i;s&&(i=await this.getCodeChallenge());const r={...t,email:e,code_challenge:i,captcha_token:await this.executeRecaptcha()};return this._networkClient.fetchSDK({url:"/magic_links/email/login_or_create",body:r,errorMessage:"Failed to send magic link",method:"POST"})}};authenticate=async(e,t)=>{O("stytch.magicLinks.authenticate").isString("Token",e).isNumber("session_duration_minutes",t.session_duration_minutes);const s={token:e,code_verifier:this._pkceManager.getPKPair()?.code_verifier,...t},i=await this._networkClient.fetchSDK({url:"/magic_links/authenticate",body:s,errorMessage:"Failed to authenticate token.",method:"POST"});return this._pkceManager.clearPKPair(),this._subscriptionService.updateState({session:i.session,user:i.user,session_token:i.session_token,session_jwt:i.session_jwt}),R(i)}}class U{constructor(e,t,s=(()=>Promise.resolve(void 0))){this._networkClient=e,this._subscriptionService=t,this.executeRecaptcha=s}sms={loginOrCreate:async(e,t)=>{const s={...t,phone_number:e,captcha_token:await this.executeRecaptcha()};return this._networkClient.fetchSDK({url:"/otps/sms/login_or_create",body:s,errorMessage:"Failed to send one time passcode",method:"POST"})}};whatsapp={loginOrCreate:async(e,t)=>{const s={...t,phone_number:e,captcha_token:await this.executeRecaptcha()};return this._networkClient.fetchSDK({url:"/otps/whatsapp/login_or_create",body:s,errorMessage:"Failed to send one time passcode",method:"POST"})}};email={loginOrCreate:async(e,t)=>{const s={...t,email:e,captcha_token:await this.executeRecaptcha()};return this._networkClient.fetchSDK({url:"/otps/email/login_or_create",body:s,errorMessage:"Failed to send one time passcode",method:"POST"})}};authenticate=async(e,t,s)=>{O("stytch.otps.authenticate").isString("Code",e).isNumber("session_duration_minutes",s.session_duration_minutes);const i={token:e,method_id:t,...s},r=await this._networkClient.fetchSDK({url:"/otps/authenticate",body:i,errorMessage:"Failed to authenticate token.",method:"POST",includeSessionTokenInBody:!0});return this._subscriptionService.updateState({session:r.session,user:r.user,session_token:r.session_token,session_jwt:r.session_jwt}),R(r)}}class F{constructor(e,t,s,i,r){this._networkClient=e,this._subscriptionService=t,this._pkceManager=s,this._dynamicConfig=i,this._config=r}google={start:this.startOAuthFlow(d.Google)};apple={start:this.startOAuthFlow(d.Apple)};microsoft={start:this.startOAuthFlow(d.Microsoft)};github={start:this.startOAuthFlow(d.Github)};gitlab={start:this.startOAuthFlow(d.GitLab)};facebook={start:this.startOAuthFlow(d.Facebook)};discord={start:this.startOAuthFlow(d.Discord)};slack={start:this.startOAuthFlow(d.Slack)};amazon={start:this.startOAuthFlow(d.Amazon)};bitbucket={start:this.startOAuthFlow(d.Bitbucket)};linkedin={start:this.startOAuthFlow(d.LinkedIn)};async authenticate(e,t){O("stytch.oauth.authenticate").isString("Token",e).isNumber("session_duration_minutes",t.session_duration_minutes);const s=this._pkceManager.getPKPair();s||C("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.");const i=await this._networkClient.fetchSDK({url:"/oauth/authenticate",method:"POST",body:{token:e,code_verifier:s?.code_verifier,...t},errorMessage:"Failed to authenticate token"});return this._pkceManager.clearPKPair(),this._subscriptionService.updateState({session:i.session,user:P(i.__user),session_token:i.session_token,session_jwt:i.session_jwt}),R(i)}async getBaseApiUrl(){const{cnameDomain:e}=await this._dynamicConfig;return 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:s,custom_scopes:i}={})=>{const{cnameDomain:r,pkceRequiredForOAuth:o}=await this._dynamicConfig,n=await this.getBaseApiUrl();this._networkClient.logEvent({name:"start_oauth_flow",details:{provider_type:e,custom_scopes:i,cname_domain:r,pkce:o}});const a=new URL(`${n}/v1/public/oauth/${e}/start`);if(a.searchParams.set("public_token",this._config.publicToken),o){const e=await this._pkceManager.startPKCETransaction();a.searchParams.set("code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();i&&(O("startOAuthFlow").isStringArray("custom_scopes",i),a.searchParams.set("custom_scopes",i.join(" "))),t&&a.searchParams.set("login_redirect_url",t),s&&a.searchParams.set("signup_redirect_url",s),window.location.href=a.toString()}}}class K{constructor(e,t,s=(()=>Promise.resolve(void 0))){this._networkClient=e,this._subscriptionService=t,this.executeRecaptcha=s}async authenticateStart(e){O("stytch.cryptoWallets.authenticateStart").isString("crypto_wallet_address",e.crypto_wallet_address).isString("crypto_wallet_type",e.crypto_wallet_type);const t=!!this._subscriptionService.getSession(),s=await this.executeRecaptcha(),i=t?"/crypto_wallets/authenticate/start/secondary":"/crypto_wallets/authenticate/start/primary";return this._networkClient.fetchSDK({url:i,method:"POST",errorMessage:"Failed to start wallet authentication.",body:{crypto_wallet_address:e.crypto_wallet_address,crypto_wallet_type:e.crypto_wallet_type,captcha_token:s}})}async authenticate(e){O("stytch.cryptoWallets.authenticate").isString("signature",e.signature).isString("crypto_wallet_address",e.crypto_wallet_address).isString("crypto_wallet_type",e.crypto_wallet_type).isNumber("session_duration_minutes",e.session_duration_minutes);const t=await this._networkClient.fetchSDK({url:"/crypto_wallets/authenticate",method:"POST",errorMessage:"Failed to authenticate.",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}});return this._subscriptionService.updateState({session:t.session,user:P(t.__user),session_token:t.session_token,session_jwt:t.session_jwt}),R(t)}}class j{constructor(e,t){this._networkClient=e,this._subscriptionService=t}async create(e){O("stytch.totps.create").isNumber("expiration_minutes",e.expiration_minutes);const t=await this._networkClient.fetchSDK({url:"/totps",method:"POST",errorMessage:"Failed to create TOTP",body:{expiration_minutes:e.expiration_minutes}});return this._subscriptionService.updateUser(t.__user),R(t)}async authenticate(e){O("stytch.totps.authenticate").isNumber("session_duration_minutes",e.session_duration_minutes).isString("totp_code",e.totp_code);const t=await this._networkClient.fetchSDK({url:"/totps/authenticate",method:"POST",errorMessage:"Failed to authenticate TOTP",body:{session_duration_minutes:e.session_duration_minutes,totp_code:e.totp_code}});return this._subscriptionService.updateState({session:t.session,user:t.__user,session_token:t.session_token,session_jwt:t.session_jwt}),R(t)}async recoveryCodes(){return this._networkClient.fetchSDK({url:"/totps/recovery_codes",method:"POST",errorMessage:"Failed to retrieve recovery codes"})}async recover(e){O("stytch.totps.recover").isNumber("session_duration_minutes",e.session_duration_minutes).isString("recovery_code",e.recovery_code);const t=await this._networkClient.fetchSDK({url:"/totps/recover",method:"POST",errorMessage:"Failed to recover TOTP",body:{session_duration_minutes:e.session_duration_minutes,recovery_code:e.recovery_code}});return this._subscriptionService.updateState({session:t.session,user:t.__user,session_token:t.session_token,session_jwt:t.session_jwt}),R(t)}}const N=Promise.resolve({pkceRequiredForPasswordResets:!1});class B{constructor(e,t,s,i=N,r=(()=>Promise.resolve(void 0))){this._networkClient=e,this._subscriptionService=t,this._pkceManager=s,this._config=i,this.executeRecaptcha=r}async getCodeChallenge(){const{pkceRequiredForPasswordResets:e}=await this._config;if(!e)return;let t=this._pkceManager.getPKPair();return t||(t=await this._pkceManager.startPKCETransaction()),t.code_challenge}async create(e){O("stytch.passwords.create").isString("password",e.password).isString("email",e.email).isNumber("session_duration_minutes",e.session_duration_minutes);const t=await this.executeRecaptcha(),s=await this._networkClient.fetchSDK({url:"/passwords",method:"POST",errorMessage:"Failed to create password.",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:t}});return this._subscriptionService.updateState({session:s.session,user:s.user,session_token:s.session_token,session_jwt:s.session_jwt}),R(s)}async authenticate(e){O("stytch.passwords.authenticate").isString("password",e.password).isString("email",e.email).isNumber("session_duration_minutes",e.session_duration_minutes);const t=await this.executeRecaptcha(),s=await this._networkClient.fetchSDK({url:"/passwords/authenticate",method:"POST",errorMessage:"Failed to authenticate password.",body:{email:e.email,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:t}});return this._subscriptionService.updateState({session:s.session,user:s.user,session_token:s.session_token,session_jwt:s.session_jwt}),R(s)}async resetByEmailStart(e){O("stytch.passwords.resetByEmailStart").isString("email",e.email).isOptionalString("login_redirect_url",e.login_redirect_url).isOptionalNumber("login_expiration_minutes",e.login_expiration_minutes).isOptionalString("reset_password_redirect_url",e.reset_password_redirect_url).isOptionalNumber("reset_password_expiration_minutes",e.reset_password_expiration_minutes);const t=await this.getCodeChallenge(),s=await this.executeRecaptcha();return this._networkClient.fetchSDK({url:"/passwords/email/reset/start",method:"POST",errorMessage:"Failed to start password reset flow.",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,code_challenge:t,captcha_token:s}})}async resetByEmail(e){O("stytch.passwords.resetByEmail").isString("token",e.token).isString("password",e.password).isNumber("session_duration_minutes",e.session_duration_minutes);const t=await this.executeRecaptcha(),s=this._pkceManager.getPKPair()?.code_verifier,i=await this._networkClient.fetchSDK({url:"/passwords/email/reset",method:"POST",errorMessage:"Failed to reset password.",body:{token:e.token,password:e.password,session_duration_minutes:e.session_duration_minutes,captcha_token:t,code_verifier:s}});return this._pkceManager.clearPKPair(),this._subscriptionService.updateState({session:i.session,user:i.user,session_token:i.session_token,session_jwt:i.session_jwt}),R(i)}async strengthCheck(e){return O("stytch.passwords.strengthCheck").isOptionalString("email",e.email).isString("password",e.password),this._networkClient.fetchSDK({url:"/passwords/strength_check",method:"POST",errorMessage:"Failed to check password strength.",body:{email:e.email,password:e.password}})}}class q{_publicToken;_subscriptionDataLayer;baseURL;eventLogger;constructor(e,t,s){this._publicToken=e,this._subscriptionDataLayer=t,this.baseURL=s,this.eventLogger=new A({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:s={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:s.error_code,error_description:s.error_description,http_status_code:s.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${y()}`,app_session_id:`app-session-id-${y()}`,persistent_id:`persistent-id-${y()}`,client_sent_at:(new Date).toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,stytch_user_id:this._subscriptionDataLayer.user?.user_id,stytch_session_id:this._subscriptionDataLayer.session?.session_id,app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"v0.0.0"}}}async fetchSDK({url:t,body:s,errorMessage:i,method:r}){const o=this._subscriptionDataLayer.readSessionCookie().session_token,n={method:r,headers:{Authorization:"Basic "+window.btoa(this._publicToken+":"+(o||this._publicToken)),"Content-Type":"application/json","X-SDK-Parent-Host":window.location.origin,"X-SDK-Client":window.btoa(JSON.stringify(this.createTelemetryBlob()))},body:s&&JSON.stringify(s)};let a;try{a=await fetch(this.buildSDKUrl(t),n)}catch(t){if("Failed to fetch"===t.message)throw new e(i,"Unable to contact the Stytch servers. Are you online?");throw t}if(200!==a.status)return $(a,i);try{return(await a.json()).data}catch(t){throw new e(i,"Invalid response from the Stytch servers.")}}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}const $=async(t,r)=>{let o;try{o=await t.json()}catch(t){throw new e(r,"Invalid or no response from server")}if("body"in o||"params"in o||"query"in o)throw new s(o);throw new i(o)};
2
- /*! js-cookie v3.0.1 | MIT */function W(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var G=function e(t,s){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=W({},s,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var n in r)r[n]&&(o+="; "+n,!0!==r[n]&&(o+="="+r[n].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},r=0;r<s.length;r++){var o=s[r].split("="),n=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(n,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",W({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,W({},this.attributes,t))},withConverter:function(t){return e(W({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},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:"/"});const V=(e,t="")=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;class z{publicToken;session;user;_opaqueTokenCookieName;_jwtCookieName;sessionSubscriptions;userSubscriptions;constructor(e,t){this.publicToken=e,this.session=null,this.user=null,this.sessionSubscriptions={},this.userSubscriptions={},t?.cookieOptions?(O("SubscriptionDataLayer").isString("cookieOptions.opaqueTokenCookieName",t.cookieOptions.opaqueTokenCookieName).isString("cookieOptions.jwtCookieName",t.cookieOptions.jwtCookieName),this._jwtCookieName=t.cookieOptions.jwtCookieName,this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName):(this._opaqueTokenCookieName=null,this._jwtCookieName=null);const s=localStorage.getItem(V(this.publicToken));if(!s)return void this.removeSessionCookie();let i;try{i=JSON.parse(s)}catch(e){return this.syncToLocalStorage(),void this.removeSessionCookie()}const{session:r,user:o}=i;this.session=r,this.user=o}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}readSessionCookie(){return{session_token:G.get(this.opaqueTokenCookieName),session_jwt:G.get(this.jwtCookieName)}}writeSessionCookie(e){const{session:t,session_token:s,session_jwt:i}=e,r=z.generateCookieOpts(t.expires_at);G.set(this.opaqueTokenCookieName,s,r),G.set(this.jwtCookieName,i,r)}removeSessionCookie(){const e=z.generateCookieOpts();G.remove(this.opaqueTokenCookieName,e),G.remove(this.jwtCookieName,e)}syncToLocalStorage(){localStorage.setItem(V(this.publicToken),JSON.stringify({session:this.session,user:this.user}))}getItem(e){return localStorage.getItem(V(this.publicToken,e))}setItem(e,t){return localStorage.setItem(V(this.publicToken,e),t)}removeItem(e){return localStorage.removeItem(V(this.publicToken,e))}browserSessionStorage={getItem:e=>sessionStorage.getItem(V(this.publicToken,e)),setItem:(e,t)=>sessionStorage.setItem(V(this.publicToken,e),t),removeItem:e=>sessionStorage.removeItem(V(this.publicToken,e))};static generateCookieOpts(e){const t={sameSite:"lax"};return e&&(t.expires=new Date(e)),X()?t.secure=!1:(t.domain=window.location.host,t.secure=!0),t}}const H={},J=(e,t)=>{const s=Math.random().toString(36).slice(-10);return e[s]=t,()=>delete e[s]},Y=(e,t)=>{Object.values(e).forEach((e=>e(t)))},X=()=>Boolean("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}$/)),Z=E({KEYS_TO_EXCLUDE:["last_accessed_at"]}),Q=E();class ee{_publicToken;_datalayer;constructor(e,t){this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen);const s=this._datalayer.session;if(s&&Date.parse(s.expires_at)<Date.now())return void this.destroyState();const{session_token:i}=this._datalayer.readSessionCookie();i||this.destroyState()}_listen=e=>{e.key===V(this._publicToken)&&(null!==e.newValue?this._updateStateInternal(JSON.parse(e.newValue)):this.destroyState())};getSession(){return this._datalayer.session}getTokens(){const{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return e&&t?{session_token:e,session_jwt:t}:null}destroyState(){this.updateState({session:null,user:null,session_token:null,session_jwt:null})}_updateStateInternal(e){const{session:t,user:s}=e,i=this._datalayer.session,r=this._datalayer.user;this._datalayer.session=t,this._datalayer.user=s,Z(i,t)||Y(this._datalayer.sessionSubscriptions,t),Q(r,s)||Y(this._datalayer.userSubscriptions,s)}updateState(e){e.session?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._updateStateInternal(e),this._datalayer.syncToLocalStorage()}updateUser(e){const t=this._datalayer.user;this._datalayer.user=e,Q(t,e)||(Y(this._datalayer.userSubscriptions,e),this._datalayer.syncToLocalStorage())}subscribeToSession(e){return J(this._datalayer.sessionSubscriptions,e)}getUser(){return this._datalayer.user}subscribeToUser(e){return J(this._datalayer.userSubscriptions,e)}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}}function te(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class se{_dataLayer;constructor(e){this._dataLayer=e}async startPKCETransaction(){const e=await se.createProofkeyPair();return this._dataLayer.setItem("PKCE_VERIFIER",JSON.stringify(e)),e}getPKPair(){const e=this._dataLayer.getItem("PKCE_VERIFIER");if(null!==e)try{return JSON.parse(e)}catch{return void C("Found malformed Proof Key pair in localstorage.")}}clearPKPair(){return this._dataLayer.removeItem("PKCE_VERIFIER")}static async createProofkeyPair(){const e=new Uint32Array(16);window.crypto.getRandomValues(e);const t=Array.from(e).map(te).join(""),s=await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t));return{code_challenge:(i=s,btoa(String.fromCharCode.call(null,...new Uint8Array(i))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:t};var i}}class ie{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,s){this._publicToken=e,this._networkClient=t,this._dataLayer=s,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET",errorMessage:`Error fetching bootstrap data for SDK for ${this._publicToken}`}).then(ie.mapBootstrapData).then((e=>(this._dataLayer.setItem("bootstrap",JSON.stringify(e)),e))).catch((e=>(T(e),{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1})))}static mapBootstrapData(e){return{displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth}}getSync(){const e=this._dataLayer.getItem("bootstrap");if(null===e)return{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1};try{return JSON.parse(e)}catch{return{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1}}}getAsync(){return this._bootstrapDataPromise}}class re{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then((async e=>{return e.captchaSettings.enabled?{configured:!0,captchaClient:await(t=e.captchaSettings.siteKey,b(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,(()=>window.grecaptcha.enterprise))),siteKey:e.captchaSettings.siteKey}:{configured:!1};var t}))}executeRecaptcha=async()=>{const{captchaClient:e,configured:t,siteKey:s}=await this.state;if(t)return await new Promise((t=>e.ready(t))),e.execute(s,{action:"LOGIN"})}}exports.Products=void 0,function(e){e.emailMagicLinks="emailMagicLinks",e.oauth="oauth",e.otp="otp",e.crypto="crypto"}(exports.Products||(exports.Products={})),exports.OAuthProviders=void 0,function(e){e.Google="google",e.Microsoft="microsoft",e.Apple="apple",e.Github="github",e.GitLab="gitlab",e.Facebook="facebook",e.Discord="discord",e.Slack="slack",e.Amazon="amazon",e.Bitbucket="bitbucket",e.LinkedIn="linkedin"}(exports.OAuthProviders||(exports.OAuthProviders={})),exports.Wallets=void 0,function(e){e.Vessel="Vessel",e.Phantom="Phantom",e.Metamask="Metamask",e.Coinbase="Coinbase",e.Binance="Binance",e.GenericEthereumWallet="Other Ethereum Wallet",e.GenericSolanaWallet="Other Solana Wallet"}(exports.Wallets||(exports.Wallets={})),exports.OneTapPositions=void 0,function(e){e.embedded="embedded",e.floating="floating"}(exports.OneTapPositions||(exports.OneTapPositions={})),exports.OTPMethods=void 0,function(e){e.SMS="sms",e.WhatsApp="whatsapp",e.Email="email"}(exports.OTPMethods||(exports.OTPMethods={})),exports.StytchEventType=void 0,function(e){e.MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",e.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",e.OTPsAuthenticate="OTP_AUTHENTICATE",e.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",e.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE_"}(exports.StytchEventType||(exports.StytchEventType={}));class oe{_googleClient;_publicToken;_clientId;constructor(e,t,s){this._googleClient=e,this._publicToken=t,this._clientId=s}async render({callback:e,onOneTapCancelled:t,style:s}){const i={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0};return s.position===exports.OneTapPositions.embedded&&(i.prompt_parent_id="google-parent-prompt",i.cancel_on_tap_outside=!1),this._googleClient.initialize(i),new Promise((e=>{this._googleClient.prompt((i=>i.isSkippedMoment()?("user_cancel"===i.getSkippedReason()&&t(),e(!1)):i.isNotDisplayed()?("unregistered_origin"===i.getNotDisplayedReason()&&t(!0),e(!1)):(this.styleFrame(s),e(!0))))}))}styleFrame(e){e.position===exports.OneTapPositions.embedded&&Array.from(document.getElementsByTagName("iframe")).forEach((e=>{e.src.includes("https://accounts.google.com/gsi")&&(e.style.width="100%")}))}}class ne{_publicToken;frameClient;googleConfig;constructor(e,t){this._publicToken=e,this.frameClient=new o(t)}async createOneTapClient(){const{googleClientId:e}=await this.fetchGoogleStart();return""===e?null:new oe(await b("https://accounts.google.com/gsi/client",(()=>window.google.accounts.id)),this._publicToken,e)}createOnSuccessHandler=({loginRedirectUrl:e,signupRedirectUrl:t,onSuccess:s})=>async i=>{const{credential:r}=i,{redirect_url:o}=await this.submitGoogleOneTapToken({credential:r,loginRedirectUrl:e,signupRedirectUrl:t});s(o)};fetchGoogleStart(){return this.googleConfig||(this.googleConfig=this.frameClient.call("oneTapStart",[this._publicToken])),this.googleConfig}async submitGoogleOneTapToken({credential:e,loginRedirectUrl:t,signupRedirectUrl:s}){const{oauthCallbackId:i}=await this.fetchGoogleStart();return this.frameClient.call("oneTapSubmit",[this._publicToken,e,i,t,s])}RedirectOnSuccess=e=>{window.location.href=e}}const ae=Symbol.for("stytch__internal");exports.StytchHeadlessClient=class{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_pkceManager;user;magicLinks;session;otps;oauth;cryptoWallets;totps;passwords;constructor(e){const t=arguments[1];var s;"string"!=typeof(s=e)?C("Public token is malformed. Expected a string, got "+typeof s):""===s?C('Public token is malformed. Expected "public-token-...", got an empty string'):s.startsWith("public-token-")||C(`Public token is malformed. Expected "public-token-...", got ${s}`);const i={cookieOptions:(r=t)?.cookieOptions,endpoints:{sdkBackendURL:r?.endpoints?.sdkBackendURL??"https://web.stytch.com",testAPIURL:r?.endpoints?.testAPIURL??"https://test.stytch.com",liveAPIURL:r?.endpoints?.liveAPIURL??"https://api.stytch.com",oneTapIFrameURL:r?.endpoints?.oneTapIFrameURL??"https://js.stytch.com/one-tap/index.html"}};var r;this._dataLayer=((e,t)=>(H[e]||(H[e]=new z(e,t)),H[e]))(e,t),this._subscriptionService=new ee(e,this._dataLayer),this._networkClient=new q(e,this._dataLayer,i.endpoints.sdkBackendURL),this._pkceManager=new se(this._dataLayer);const o=new ie(e,this._networkClient,this._dataLayer),n=new re(o.getAsync()),a=new ne(e,i.endpoints.oneTapIFrameURL);var c,u;this.user=new M(this._networkClient,this._subscriptionService),this.session=new I(this._networkClient,this._subscriptionService),this.magicLinks=new x(this._networkClient,this._subscriptionService,this._pkceManager,o.getAsync(),n.executeRecaptcha),this.otps=new U(this._networkClient,this._subscriptionService,n.executeRecaptcha),this.oauth=new F(this._networkClient,this._subscriptionService,this._pkceManager,o.getAsync(),{publicToken:e,testAPIURL:i.endpoints.testAPIURL,liveAPIURL:i.endpoints.liveAPIURL}),this.cryptoWallets=new K(this._networkClient,this._subscriptionService,n.executeRecaptcha),this.totps=new j(this._networkClient,this._subscriptionService),this.passwords=new B(this._networkClient,this._subscriptionService,this._pkceManager,o.getAsync(),n.executeRecaptcha),this._sessionManager=new L(this._subscriptionService,this.session),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=this,u={bootstrap:o,captcha:n,oneTap:a},Object.assign(c,{[ae]:u})}};
1
+ "use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e){return function(e){if(Array.isArray(e))return r(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return r(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function n(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */n=function(){return t};var t={},r=Object.prototype,i=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},s=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function u(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(e){u=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof f?t:f,o=Object.create(i.prototype),s=new O(n||[]);return o._invoke=function(e,t,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return E()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=k(s,r);if(a){if(a===p)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=h(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===p)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}(e,r,s),o}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p={};function f(){}function d(){}function v(){}var _={};u(_,s,(function(){return this}));var y=Object.getPrototypeOf,m=y&&y(y(C([])));m&&m!==r&&i.call(m,s)&&(_=m);var g=v.prototype=f.prototype=Object.create(_);function w(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function b(t,r){function n(o,s,a,c){var u=h(t[o],t,s);if("throw"!==u.type){var l=u.arg,p=l.value;return p&&"object"==e(p)&&i.call(p,"__await")?r.resolve(p.__await).then((function(e){n("next",e,a,c)}),(function(e){n("throw",e,a,c)})):r.resolve(p).then((function(e){l.value=e,a(l)}),(function(e){return n("throw",e,a,c)}))}c(u.arg)}var o;this._invoke=function(e,t){function i(){return new r((function(r,i){n(e,t,r,i)}))}return o=o?o.then(i,i):i()}}function k(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,k(e,t),"throw"===t.method))return p;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var n=h(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,p;var i=n.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,p):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,p)}function S(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function x(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function C(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,n=function t(){for(;++r<e.length;)if(i.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=void 0,t.done=!0,t};return n.next=n}}return{next:E}}function E(){return{value:void 0,done:!0}}return d.prototype=v,u(g,"constructor",v),u(v,"constructor",d),d.displayName=u(v,c,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,u(e,c,"GeneratorFunction")),e.prototype=Object.create(g),e},t.awrap=function(e){return{__await:e}},w(b.prototype),u(b.prototype,a,(function(){return this})),t.AsyncIterator=b,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var s=new b(l(e,r,n,i),o);return t.isGeneratorFunction(r)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},w(g),u(g,c,"Generator"),u(g,s,(function(){return this})),u(g,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function r(){for(;t.length;){var n=t.pop();if(n in e)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(x),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,n){return s.type="throw",s.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var a=i.call(o,"catchLoc"),c=i.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,p):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),p},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),x(r),p}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;x(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),p}},t}function i(e,t,r,n,i,o,s){try{var a=e[o](s),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function o(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var s=e.apply(t,r);function a(e){i(s,n,o,a,c,"next",e)}function c(e){i(s,n,o,a,c,"throw",e)}a(void 0)}))}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function c(e,t,r){return t&&a(e.prototype,t),r&&a(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function u(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(exports,"__esModule",{value:!0});var l=["request_id","status_code"],h=["__user"];function p(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==r)return;var n,i,o=[],s=!0,a=!1;try{for(r=r.call(e);!(s=(n=r.next()).done)&&(o.push(n.value),!t||o.length!==t);s=!0);}catch(e){a=!0,i=e}finally{try{s||null==r.return||r.return()}finally{if(a)throw i}}return o}(e,t)||v(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},d(e)}function v(e,t){if(e){if("string"==typeof e)return _(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_(e,t):void 0}}function _(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function y(){
2
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
3
+ y=function(){return e};var e={},t=Object.prototype,r=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",s=n.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(e){a=function(e,t,r){return e[t]=r}}function c(e,t,r,n){var i=t&&t.prototype instanceof h?t:h,o=Object.create(i.prototype),s=new O(n||[]);return o._invoke=function(e,t,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return E()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=k(s,r);if(a){if(a===l)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=u(e,t,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===l)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}(e,r,s),o}function u(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var l={};function h(){}function p(){}function f(){}var v={};a(v,i,(function(){return this}));var _=Object.getPrototypeOf,m=_&&_(_(C([])));m&&m!==t&&r.call(m,i)&&(v=m);var g=f.prototype=h.prototype=Object.create(v);function w(e){["next","throw","return"].forEach((function(t){a(e,t,(function(e){return this._invoke(t,e)}))}))}function b(e,t){function n(i,o,s,a){var c=u(e[i],e,o);if("throw"!==c.type){var l=c.arg,h=l.value;return h&&"object"==d(h)&&r.call(h,"__await")?t.resolve(h.__await).then((function(e){n("next",e,s,a)}),(function(e){n("throw",e,s,a)})):t.resolve(h).then((function(e){l.value=e,s(l)}),(function(e){return n("throw",e,s,a)}))}a(c.arg)}var i;this._invoke=function(e,r){function o(){return new t((function(t,i){n(e,r,t,i)}))}return i=i?i.then(o,o):o()}}function k(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,k(e,t),"throw"===t.method))return l;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return l}var n=u(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,l;var i=n.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,l):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,l)}function S(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function x(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function C(e){if(e){var t=e[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,o=function t(){for(;++n<e.length;)if(r.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return o.next=o}}return{next:E}}function E(){return{value:void 0,done:!0}}return p.prototype=f,a(g,"constructor",f),a(f,"constructor",p),p.displayName=a(f,s,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===p||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,f):(e.__proto__=f,a(e,s,"GeneratorFunction")),e.prototype=Object.create(g),e},e.awrap=function(e){return{__await:e}},w(b.prototype),a(b.prototype,o,(function(){return this})),e.AsyncIterator=b,e.async=function(t,r,n,i,o){void 0===o&&(o=Promise);var s=new b(c(t,r,n,i),o);return e.isGeneratorFunction(r)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},w(g),a(g,s,"Generator"),a(g,i,(function(){return this})),a(g,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function r(){for(;t.length;){var n=t.pop();if(n in e)return r.value=n,r.done=!1,r}return r.done=!0,r}},e.values=C,O.prototype={constructor:O,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(x),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(r,n){return s.type="throw",s.arg=e,t.next=r,n&&(t.method="next",t.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=r.call(o,"catchLoc"),c=r.call(o,"finallyLoc");if(a&&c){if(this.prev<o.catchLoc)return n(o.catchLoc,!0);if(this.prev<o.finallyLoc)return n(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return n(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return n(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=e,s.arg=t,o?(this.method="next",this.next=o.finallyLoc,l):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),l},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),x(r),l}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;x(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),l}},e}function m(e,t,r,n,i,o,s){try{var a=e[o](s),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function g(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function s(e){m(o,n,i,s,a,"next",e)}function a(e){m(o,n,i,s,a,"throw",e)}s(void 0)}))}}function w(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function b(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?w(Object(r),!0).forEach((function(t){I(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):w(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function k(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function S(e,t,r){return t&&k(e.prototype,t),r&&k(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function x(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function O(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&j(e,t)}function C(e){var t=R();return function(){var r,n=A(e);if(t){var i=A(this).constructor;r=Reflect.construct(n,arguments,i)}else r=n.apply(this,arguments);return E(this,r)}}function E(e,t){if(t&&("object"===d(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return T(e)}function T(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function P(e){var t="function"==typeof Map?new Map:void 0;return P=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return L(e,arguments,A(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),j(n,e)},P(e)}function L(e,t,r){return L=R()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&j(i,r.prototype),i},L.apply(null,arguments)}function R(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function j(e,t){return j=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},j(e,t)}function A(e){return A=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},A(e)}function I(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var M,F="".concat("https://accounts.google.com/gsi","/client"),D=function(e){O(r,P(Error));var t=C(r);function r(e,n){var i;return x(this,r),I(T(i=t.call(this,e+"\n"+n)),"details",void 0),i.message=e+"\n"+n,i.name="SDKError",i.details=n,Object.setPrototypeOf(T(i),r.prototype),i}return S(r)}(),N=function(e){O(r,P(Error));var t=C(r);function r(e,n){var i;return x(this,r),(i=t.call(this)).name="StytchSDKUsageError",i.message="Invalid call to ".concat(e,"\n")+n,i}return S(r)}(),U=function(e){O(r,P(Error));var t=C(r);function r(e){var n,i;x(this,r),(i=t.call(this)).name="StytchSDKSchemaError";var o=null===(n=e.body)||void 0===n?void 0:n.map((function(e){return"".concat(e.dataPath,": ").concat(e.message)})).join("\n");return i.message="[400] Request does not match expected schema\n".concat(o),i}return S(r)}(),K=function(e){O(r,P(Error));var t=C(r);function r(e){var n;x(this,r),I(T(n=t.call(this)),"error_type",void 0),I(T(n),"error_message",void 0),I(T(n),"error_url",void 0),I(T(n),"request_id",void 0),I(T(n),"status_code",void 0),n.name="StytchSDKAPIError";var i=e.status_code,o=e.error_type,s=e.error_message,a=e.error_url,c=e.request_id;return n.error_type=o,n.error_message=s,n.error_url=a,n.request_id=c,n.status_code=i,n.message="[".concat(i,"] ").concat(o,"\n")+"".concat(s,"\n")+"See ".concat(a," for more information.\n")+(c?"request_id: ".concat(c,"\n"):""),n}return S(r)}(),B=function(){function e(){x(this,e)}return S(e,null,[{key:"marshall",value:function(e){return b(b({},e),{},{name:e.name,message:e.message,stack:e.stack})}},{key:"inflate",value:function(e,t){var r=new e(t);return Object.assign(r,t),Object.setPrototypeOf(r,e.prototype),r}},{key:"unmarshall",value:function(t){if("name"in t)switch(t.name){case"SDKError":return e.inflate(D,t);case"StytchSDKSchemaError":return e.inflate(U,t);case"StytchSDKAPIError":return e.inflate(K,t);case"TypeError":return e.inflate(TypeError,t);case"SyntaxError":return e.inflate(SyntaxError,t);case"ReferenceError":return e.inflate(ReferenceError,t);case"RangeError":return e.inflate(RangeError,t);case"EvalError":return e.inflate(EvalError,t);case"URIError":return e.inflate(URIError,t)}return e.inflate(Error,t)}}]),e}(),G=function(){function e(t){x(this,e),I(this,"iframeURL",void 0),I(this,"frame",void 0),this.iframeURL=t,this.createIframe()}var t;return S(e,[{key:"createIframe",value:function(){var e=document.querySelector('[src~="'.concat(this.iframeURL,'"]'));if(e&&e instanceof HTMLIFrameElement)this.frame=Promise.resolve(e);else{var t=document.createElement("iframe");t.src=this.iframeURL,t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.border="0",document.body.appendChild(t),this.frame=new Promise((function(e){return t.onload=function(){return e(t)}}))}}},{key:"call",value:(t=g(y().mark((function e(t,r){var n,i,o=this;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.frame;case 2:return n=e.sent,i=new MessageChannel,e.abrupt("return",new Promise((function(e,s){var a;i.port1.onmessage=function(t){var r=t.data;i.port1.close(),r.success?e(r.payload):s(B.unmarshall(r.error))};var c={method:t,args:r};null===(a=n.contentWindow)||void 0===a||a.postMessage(c,o.iframeURL,[i.port2])})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,r){return t.apply(this,arguments)})}]),e}(),q=new Uint8Array(16);function W(){if(!M&&!(M="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return M(q)}var z=/^(?:[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;function V(e){return"string"==typeof e&&z.test(e)}for(var H,J,Y,$,X,Z,Q=[],ee=0;ee<256;++ee)Q.push((ee+256).toString(16).substr(1));function te(e,t,r){var n=(e=e||{}).random||(e.rng||W)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(Q[e[t+0]]+Q[e[t+1]]+Q[e[t+2]]+Q[e[t+3]]+"-"+Q[e[t+4]]+Q[e[t+5]]+"-"+Q[e[t+6]]+Q[e[t+7]]+"-"+Q[e[t+8]]+Q[e[t+9]]+"-"+Q[e[t+10]]+Q[e[t+11]]+Q[e[t+12]]+Q[e[t+13]]+Q[e[t+14]]+Q[e[t+15]]).toLowerCase();if(!V(r))throw TypeError("Stringified UUID is invalid");return r}(n)}!function(e){e.emailMagicLinks="emailMagicLinks",e.oauth="oauth",e.otp="otp",e.crypto="crypto"}(H||(H={})),function(e){e.Google="google",e.Microsoft="microsoft",e.Apple="apple",e.Github="github",e.GitLab="gitlab",e.Facebook="facebook",e.Discord="discord",e.Slack="slack",e.Amazon="amazon",e.Bitbucket="bitbucket",e.LinkedIn="linkedin"}(J||(J={})),function(e){e.Vessel="Vessel",e.Phantom="Phantom",e.Metamask="Metamask",e.Coinbase="Coinbase",e.Binance="Binance",e.GenericEthereumWallet="Other Ethereum Wallet",e.GenericSolanaWallet="Other Solana Wallet"}(Y||(Y={})),function(e){e.embedded="embedded",e.floating="floating"}($||($={})),function(e){e.SMS="sms",e.WhatsApp="whatsapp",e.Email="email"}(X||(X={})),function(e){e.MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",e.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",e.OTPsAuthenticate="OTP_AUTHENTICATE",e.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",e.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE_"}(Z||(Z={}));var re={};function ne(e,t){return ie.apply(this,arguments)}function ie(){return(ie=g(y().mark((function e(t,r){return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0===re[t]){e.next=2;break}return e.abrupt("return",re[t]);case 2:return re[t]=oe(t,r),e.abrupt("return",re[t]);case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function oe(e,t){return new Promise((function(r,n){if(function(e){return se(e).length>0}(e))try{r(t())}catch(t){return n(new Error("".concat(e," already loaded, but module was not found in global scope: ").concat(t)))}var i=function(e){var t=se(e);if(t[0])return t[0];var r=document.createElement("script");return r.setAttribute("src",e),r.setAttribute("async","true"),r.setAttribute("defer","true"),document.head.appendChild(r),r}(e);i.addEventListener("load",(function(){try{r(t())}catch(t){n(new Error("".concat(e," was loaded, but module was not found in global scope: ").concat(t)))}})),i.addEventListener("error",(function(t){n(new Error("".concat(e," could not be loaded: ").concat(t)))}))}))}var se=function(e){return document.querySelectorAll('script[src="'.concat(e,'"]'))};var ae=["[Stytch]"],ce=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=console).warn.apply(e,ae.concat(r))},ue=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=console).error.apply(e,ae.concat(r))},le=function(e){"string"!=typeof e?ce("Public token is malformed. Expected a string, got ".concat(d(e))):""===e?ce('Public token is malformed. Expected "public-token-...", got an empty string'):e.startsWith("public-token-")||ce('Public token is malformed. Expected "public-token-...", got '.concat(e))},he=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.KEYS_TO_EXCLUDE,r=void 0===t?[]:t,n=function e(t,n){return d(t)===d(n)&&(null===t||null===n?t===n:"object"===d(t)?Object.keys(t).length===Object.keys(n).length&&!Object.keys(t).some((function(e){return!(e in n)}))&&Object.entries(t).filter((function(e){var t=f(e,1)[0];return!r.includes(t)})).every((function(t){var r=f(t,2),i=r[0],o=r[1];return e(o,n[i])})):t===n)};return n},pe=function(e){var t={isString:function(r,n){if("string"!=typeof n)throw new N(e,r+" must be a string.");return t},isOptionalString:function(e,r){return void 0===r?t:t.isString(e,r)},isStringArray:function(r,n){if(!Array.isArray(n))throw new N(e,r+" must be an array of strings.");var i,o=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=v(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,a=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==r.return||r.return()}finally{if(a)throw o}}}}(n);try{for(o.s();!(i=o.n()).done;){if("string"!=typeof i.value)throw new N(e,r+" must be an array of strings.")}}catch(e){o.e(e)}finally{o.f()}return t},isNumber:function(r,n){if("number"!=typeof n)throw new N(e,r+" must be a number.");return t},isOptionalNumber:function(e,r){return void 0===r?t:t.isNumber(e,r)}};return t},fe=function(e){return e.request_id,e.status_code,p(e,l)},de=function(e){return e.__user,p(e,h)},ve=function(){function e(t,r){var n=this;x(this,e),I(this,"_subscriptionService",void 0),I(this,"_headlessSessionClient",void 0),I(this,"timeout",void 0),I(this,"_onSessionChange",(function(e){e&&null===n.timeout&&n.scheduleBackgroundRefresh(),e||n.cancelBackgroundRefresh()})),I(this,"_reauthenticateWithBackoff",(function(){var t=function(t){return function(r){return e.isUnrecoverableRecoverableError(r)?Promise.reject(r):new Promise((function(r){return setTimeout(r,e.timeoutForAttempt(t))})).then((function(){return n._headlessSessionClient.authenticate()}))}};return n._headlessSessionClient.authenticate().catch(t(0)).catch(t(1)).catch(t(2)).catch(t(3)).catch(t(4))})),this._subscriptionService=t,this._headlessSessionClient=r,this.timeout=null,this._subscriptionService.subscribeToSession(this._onSessionChange)}return S(e,[{key:"performBackgroundRefresh",value:function(){var e=this;this._reauthenticateWithBackoff().then((function(t){e.scheduleBackgroundRefresh(),e._subscriptionService.updateState({session:t.session,session_token:t.session_token,session_jwt:t.session_jwt,user:t.user})})).catch((function(){ce("Session background refresh failed. Signalling to app that user is logged out."),e._subscriptionService.destroyState()}))}},{key:"scheduleBackgroundRefresh",value:function(){var t=this;this.timeout=setTimeout((function(){t.timeout=null,t.performBackgroundRefresh()}),e.REFRESH_INTERVAL_MS)}},{key:"cancelBackgroundRefresh",value:function(){null!==this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}}],[{key:"timeoutForAttempt",value:function(e){return Math.floor(350*Math.random())-175+2e3*Math.pow(2,e)}},{key:"isUnrecoverableRecoverableError",value:function(e){return"unauthorized_credentials"===e.error_type}}]),e}();I(ve,"REFRESH_INTERVAL_MS",18e4);var _e=function(){function e(t){x(this,e),I(this,"maxBatchSize",void 0),I(this,"logEventURL",void 0),I(this,"batch",void 0),this.maxBatchSize=t.maxBatchSize,this.logEventURL=t.logEventURL,setInterval(this.flush.bind(this),t.intervalDurationMs),this.batch=[]}var t;return S(e,[{key:"logEvent",value:function(e,t){this.batch.push({telemetry:e,event:t}),this.batch.length>=this.maxBatchSize&&this.flush()}},{key:"flush",value:(t=g(y().mark((function e(){var t;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.batch.length){e.next=2;break}return e.abrupt("return");case 2:return t=this.batch,this.batch=[],e.prev=4,e.next=7,fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});case 7:e.next=11;break;case 9:e.prev=9,e.t0=e.catch(4);case 11:case"end":return e.stop()}}),e,this,[[4,9]])}))),function(){return t.apply(this,arguments)})}]),e}(),ye=S((function e(t,r){var n=this;x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"get",g(y().mark((function e(){var t,r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/users/me",errorMessage:"Failed to retrieve user info.",method:"GET"});case 2:return t=e.sent,r=fe(t),n._subscriptionService.updateUser(r),e.abrupt("return",r);case 6:case"end":return e.stop()}}),e)})))),I(this,"getSync",(function(){return n._subscriptionService.getUser()})),I(this,"update",function(){var e=g(y().mark((function e(t){var r,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/users/me",body:t,errorMessage:"Failed to update user.",method:"PUT"});case 2:return r=e.sent,i=fe(r.__user),n._subscriptionService.updateUser(i),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),I(this,"deleteEmail",function(){var e=g(y().mark((function e(t){var r,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/users/emails/".concat(t),errorMessage:"Failed to delete email.",method:"DELETE"});case 2:return r=e.sent,i=fe(r.__user),n._subscriptionService.updateUser(i),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),I(this,"deletePhoneNumber",function(){var e=g(y().mark((function e(t){var r,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/users/phone_numbers/".concat(t),errorMessage:"Failed to delete phone number.",method:"DELETE"});case 2:return r=e.sent,i=fe(r.__user),n._subscriptionService.updateUser(i),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),I(this,"deleteTOTP",function(){var e=g(y().mark((function e(t){var r,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/users/totps/".concat(t),errorMessage:"Failed to delete TOTP.",method:"DELETE"});case 2:return r=e.sent,i=fe(r.__user),n._subscriptionService.updateUser(i),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()),I(this,"onChange",(function(e){return n._subscriptionService.subscribeToUser(e)})),this._networkClient=t,this._subscriptionService=r})),me=function(){function e(t,r){var n=this;x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"getSync",(function(){return n._subscriptionService.getSession()})),I(this,"onChange",(function(e){return n._subscriptionService.subscribeToSession(e)})),I(this,"revoke",g(y().mark((function e(){var t;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._networkClient.fetchSDK({url:"/sessions/revoke",errorMessage:"Error revoking session",method:"POST"});case 2:t=e.sent;try{n._subscriptionService.destroyState()}catch(e){}return e.abrupt("return",t);case 5:case"end":return e.stop()}}),e)})))),I(this,"authenticate",function(){var e=g(y().mark((function e(t){var r,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,r={session_duration_minutes:null==t?void 0:t.session_duration_minutes},e.next=4,n._networkClient.fetchSDK({url:"/sessions/authenticate",body:r,errorMessage:"Error authenticating session",method:"POST"});case 4:return i=e.sent,n._subscriptionService.updateState({session:i.session,user:i.user,session_token:i.session_token,session_jwt:i.session_jwt}),e.abrupt("return",de(i));case 9:throw e.prev=9,e.t0=e.catch(0),n._subscriptionService.destroyState(),e.t0;case 13:case"end":return e.stop()}}),e,null,[[0,9]])})));return function(t){return e.apply(this,arguments)}}()),this._networkClient=t,this._subscriptionService=r}return S(e,[{key:"getTokens",value:function(){return this._subscriptionService.getTokens()}}]),e}(),ge=Promise.resolve({pkceRequiredForEmailMagicLinks:!1}),we=function(){function e(t,r,n){var i,o=this,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:ge,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:function(){return Promise.resolve(void 0)};x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"_pkceManager",void 0),I(this,"_config",void 0),I(this,"executeRecaptcha",void 0),I(this,"email",{loginOrCreate:(i=g(y().mark((function e(t){var r,n,i,s,a,c=arguments;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=c.length>1&&void 0!==c[1]?c[1]:{},e.next=3,o._config;case 3:if(n=e.sent,i=n.pkceRequiredForEmailMagicLinks,s=void 0,!i){e.next=10;break}return e.next=9,o.getCodeChallenge();case 9:s=e.sent;case 10:return e.t0=b,e.t1=b({},r),e.t2={},e.t3=t,e.t4=s,e.next=17,o.executeRecaptcha();case 17:return e.t5=e.sent,e.t6={email:e.t3,code_challenge:e.t4,captcha_token:e.t5},a=(0,e.t0)(e.t1,e.t2,e.t6),e.abrupt("return",o._networkClient.fetchSDK({url:"/magic_links/email/login_or_create",body:a,errorMessage:"Failed to send magic link",method:"POST"}));case 21:case"end":return e.stop()}}),e)}))),function(e){return i.apply(this,arguments)})}),I(this,"authenticate",function(){var e=g(y().mark((function e(t,r){var n,i,s;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.magicLinks.authenticate").isString("Token",t).isNumber("session_duration_minutes",r.session_duration_minutes),i=b({token:t,code_verifier:null===(n=o._pkceManager.getPKPair())||void 0===n?void 0:n.code_verifier},r),e.next=4,o._networkClient.fetchSDK({url:"/magic_links/authenticate",body:i,errorMessage:"Failed to authenticate token.",method:"POST"});case 4:return s=e.sent,o._pkceManager.clearPKPair(),o._subscriptionService.updateState({session:s.session,user:s.user,session_token:s.session_token,session_jwt:s.session_jwt}),e.abrupt("return",de(s));case 8:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}()),this._networkClient=t,this._subscriptionService=r,this._pkceManager=n,this._config=s,this.executeRecaptcha=a}var t;return S(e,[{key:"getCodeChallenge",value:(t=g(y().mark((function e(){var t;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t=this._pkceManager.getPKPair())){e.next=3;break}return e.abrupt("return",t.code_challenge);case 3:return e.next=5,this._pkceManager.startPKCETransaction();case 5:return t=e.sent,e.abrupt("return",t.code_challenge);case 7:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),e}(),be=S((function e(t,r){var n,i,o,s=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return Promise.resolve(void 0)};x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"executeRecaptcha",void 0),I(this,"sms",{loginOrCreate:(n=g(y().mark((function e(t,r){var n,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s.executeRecaptcha();case 2:return n=e.sent,i=b(b({},r),{},{phone_number:t,captcha_token:n}),e.abrupt("return",s._networkClient.fetchSDK({url:"/otps/sms/login_or_create",body:i,errorMessage:"Failed to send one time passcode",method:"POST"}));case 5:case"end":return e.stop()}}),e)}))),function(e,t){return n.apply(this,arguments)})}),I(this,"whatsapp",{loginOrCreate:(i=g(y().mark((function e(t,r){var n,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s.executeRecaptcha();case 2:return n=e.sent,i=b(b({},r),{},{phone_number:t,captcha_token:n}),e.abrupt("return",s._networkClient.fetchSDK({url:"/otps/whatsapp/login_or_create",body:i,errorMessage:"Failed to send one time passcode",method:"POST"}));case 5:case"end":return e.stop()}}),e)}))),function(e,t){return i.apply(this,arguments)})}),I(this,"email",{loginOrCreate:(o=g(y().mark((function e(t,r){var n,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s.executeRecaptcha();case 2:return n=e.sent,i=b(b({},r),{},{email:t,captcha_token:n}),e.abrupt("return",s._networkClient.fetchSDK({url:"/otps/email/login_or_create",body:i,errorMessage:"Failed to send one time passcode",method:"POST"}));case 5:case"end":return e.stop()}}),e)}))),function(e,t){return o.apply(this,arguments)})}),I(this,"authenticate",function(){var e=g(y().mark((function e(t,r,n){var i,o;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.otps.authenticate").isString("Code",t).isNumber("session_duration_minutes",n.session_duration_minutes),i=b({token:t,method_id:r},n),e.next=4,s._networkClient.fetchSDK({url:"/otps/authenticate",body:i,errorMessage:"Failed to authenticate token.",method:"POST",includeSessionTokenInBody:!0});case 4:return o=e.sent,s._subscriptionService.updateState({session:o.session,user:o.user,session_token:o.session_token,session_jwt:o.session_jwt}),e.abrupt("return",de(o));case 7:case"end":return e.stop()}}),e)})));return function(t,r,n){return e.apply(this,arguments)}}()),this._networkClient=t,this._subscriptionService=r,this.executeRecaptcha=a})),ke=function(){function e(t,r,n,i,o){x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"_pkceManager",void 0),I(this,"_dynamicConfig",void 0),I(this,"_config",void 0),I(this,"google",{start:this.startOAuthFlow(J.Google)}),I(this,"apple",{start:this.startOAuthFlow(J.Apple)}),I(this,"microsoft",{start:this.startOAuthFlow(J.Microsoft)}),I(this,"github",{start:this.startOAuthFlow(J.Github)}),I(this,"gitlab",{start:this.startOAuthFlow(J.GitLab)}),I(this,"facebook",{start:this.startOAuthFlow(J.Facebook)}),I(this,"discord",{start:this.startOAuthFlow(J.Discord)}),I(this,"slack",{start:this.startOAuthFlow(J.Slack)}),I(this,"amazon",{start:this.startOAuthFlow(J.Amazon)}),I(this,"bitbucket",{start:this.startOAuthFlow(J.Bitbucket)}),I(this,"linkedin",{start:this.startOAuthFlow(J.LinkedIn)}),this._networkClient=t,this._subscriptionService=r,this._pkceManager=n,this._dynamicConfig=i,this._config=o}var t,r;return S(e,[{key:"authenticate",value:(r=g(y().mark((function e(t,r){var n,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.oauth.authenticate").isString("Token",t).isNumber("session_duration_minutes",r.session_duration_minutes),(n=this._pkceManager.getPKPair())||ce("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."),e.next=5,this._networkClient.fetchSDK({url:"/oauth/authenticate",method:"POST",body:b({token:t,code_verifier:null==n?void 0:n.code_verifier},r),errorMessage:"Failed to authenticate token"});case 5:return i=e.sent,this._pkceManager.clearPKPair(),this._subscriptionService.updateState({session:i.session,user:fe(i.__user),session_token:i.session_token,session_jwt:i.session_jwt}),e.abrupt("return",de(i));case 9:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"getBaseApiUrl",value:(t=g(y().mark((function e(){var t,r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._dynamicConfig;case 2:if(t=e.sent,!(r=t.cnameDomain)){e.next=6;break}return e.abrupt("return",r);case 6:if(!this._config.publicToken.includes("public-token-test")){e.next=8;break}return e.abrupt("return",this._config.testAPIURL);case 8:return e.abrupt("return",this._config.liveAPIURL);case 9:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"startOAuthFlow",value:function(e){var t=this;return g(y().mark((function r(){var n,i,o,s,a,c,u,l,h,p,f=arguments;return y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return n=f.length>0&&void 0!==f[0]?f[0]:{},i=n.login_redirect_url,o=n.signup_redirect_url,s=n.custom_scopes,r.next=3,t._dynamicConfig;case 3:return a=r.sent,c=a.cnameDomain,u=a.pkceRequiredForOAuth,r.next=8,t.getBaseApiUrl();case 8:if(l=r.sent,t._networkClient.logEvent({name:"start_oauth_flow",details:{provider_type:e,custom_scopes:s,cname_domain:c,pkce:u}}),(h=new URL("".concat(l,"/v1/public/oauth/").concat(e,"/start"))).searchParams.set("public_token",t._config.publicToken),!u){r.next=20;break}return r.next=16,t._pkceManager.startPKCETransaction();case 16:p=r.sent,h.searchParams.set("code_challenge",p.code_challenge),r.next=21;break;case 20:t._pkceManager.clearPKPair();case 21:s&&(pe("startOAuthFlow").isStringArray("custom_scopes",s),h.searchParams.set("custom_scopes",s.join(" "))),i&&h.searchParams.set("login_redirect_url",i),o&&h.searchParams.set("signup_redirect_url",o),window.location.href=h.toString();case 25:case"end":return r.stop()}}),r)})))}}]),e}(),Se=function(){function e(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return Promise.resolve(void 0)};x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"executeRecaptcha",void 0),this._networkClient=t,this._subscriptionService=r,this.executeRecaptcha=n}var t,r;return S(e,[{key:"authenticateStart",value:(r=g(y().mark((function e(t){var r,n,i;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.cryptoWallets.authenticateStart").isString("crypto_wallet_address",t.crypto_wallet_address).isString("crypto_wallet_type",t.crypto_wallet_type),r=!!this._subscriptionService.getSession(),e.next=4,this.executeRecaptcha();case 4:return n=e.sent,i=r?"/crypto_wallets/authenticate/start/secondary":"/crypto_wallets/authenticate/start/primary",e.abrupt("return",this._networkClient.fetchSDK({url:i,method:"POST",errorMessage:"Failed to start wallet authentication.",body:{crypto_wallet_address:t.crypto_wallet_address,crypto_wallet_type:t.crypto_wallet_type,captcha_token:n}}));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"authenticate",value:(t=g(y().mark((function e(t){var r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.cryptoWallets.authenticate").isString("signature",t.signature).isString("crypto_wallet_address",t.crypto_wallet_address).isString("crypto_wallet_type",t.crypto_wallet_type).isNumber("session_duration_minutes",t.session_duration_minutes),e.next=3,this._networkClient.fetchSDK({url:"/crypto_wallets/authenticate",method:"POST",errorMessage:"Failed to authenticate.",body:{session_duration_minutes:t.session_duration_minutes,crypto_wallet_address:t.crypto_wallet_address,crypto_wallet_type:t.crypto_wallet_type,signature:t.signature}});case 3:return r=e.sent,this._subscriptionService.updateState({session:r.session,user:fe(r.__user),session_token:r.session_token,session_jwt:r.session_jwt}),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}(),xe=function(){function e(t,r){x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),this._networkClient=t,this._subscriptionService=r}var t,r,n,i;return S(e,[{key:"create",value:(i=g(y().mark((function e(t){var r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.totps.create").isNumber("expiration_minutes",t.expiration_minutes),e.next=3,this._networkClient.fetchSDK({url:"/totps",method:"POST",errorMessage:"Failed to create TOTP",body:{expiration_minutes:t.expiration_minutes}});case 3:return r=e.sent,this._subscriptionService.updateUser(r.__user),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"authenticate",value:(n=g(y().mark((function e(t){var r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.totps.authenticate").isNumber("session_duration_minutes",t.session_duration_minutes).isString("totp_code",t.totp_code),e.next=3,this._networkClient.fetchSDK({url:"/totps/authenticate",method:"POST",errorMessage:"Failed to authenticate TOTP",body:{session_duration_minutes:t.session_duration_minutes,totp_code:t.totp_code}});case 3:return r=e.sent,this._subscriptionService.updateState({session:r.session,user:r.__user,session_token:r.session_token,session_jwt:r.session_jwt}),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"recoveryCodes",value:(r=g(y().mark((function e(){return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._networkClient.fetchSDK({url:"/totps/recovery_codes",method:"POST",errorMessage:"Failed to retrieve recovery codes"}));case 1:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"recover",value:(t=g(y().mark((function e(t){var r;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.totps.recover").isNumber("session_duration_minutes",t.session_duration_minutes).isString("recovery_code",t.recovery_code),e.next=3,this._networkClient.fetchSDK({url:"/totps/recover",method:"POST",errorMessage:"Failed to recover TOTP",body:{session_duration_minutes:t.session_duration_minutes,recovery_code:t.recovery_code}});case 3:return r=e.sent,this._subscriptionService.updateState({session:r.session,user:r.__user,session_token:r.session_token,session_jwt:r.session_jwt}),e.abrupt("return",de(r));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}(),Oe=Promise.resolve({pkceRequiredForPasswordResets:!1}),Ce=function(){function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Oe,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:function(){return Promise.resolve(void 0)};x(this,e),I(this,"_networkClient",void 0),I(this,"_subscriptionService",void 0),I(this,"_pkceManager",void 0),I(this,"_config",void 0),I(this,"executeRecaptcha",void 0),this._networkClient=t,this._subscriptionService=r,this._pkceManager=n,this._config=i,this.executeRecaptcha=o}var t,r,n,i,o,s;return S(e,[{key:"getCodeChallenge",value:(s=g(y().mark((function e(){var t;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._config;case 2:if(e.sent.pkceRequiredForPasswordResets){e.next=6;break}return e.abrupt("return",void 0);case 6:if(!(t=this._pkceManager.getPKPair())){e.next=9;break}return e.abrupt("return",t.code_challenge);case 9:return e.next=11,this._pkceManager.startPKCETransaction();case 11:return t=e.sent,e.abrupt("return",t.code_challenge);case 13:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"create",value:(o=g(y().mark((function e(t){var r,n;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.passwords.create").isString("password",t.password).isString("email",t.email).isNumber("session_duration_minutes",t.session_duration_minutes),e.next=3,this.executeRecaptcha();case 3:return r=e.sent,e.next=6,this._networkClient.fetchSDK({url:"/passwords",method:"POST",errorMessage:"Failed to create password.",body:{email:t.email,password:t.password,session_duration_minutes:t.session_duration_minutes,captcha_token:r}});case 6:return n=e.sent,this._subscriptionService.updateState({session:n.session,user:n.user,session_token:n.session_token,session_jwt:n.session_jwt}),e.abrupt("return",de(n));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"authenticate",value:(i=g(y().mark((function e(t){var r,n;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.passwords.authenticate").isString("password",t.password).isString("email",t.email).isNumber("session_duration_minutes",t.session_duration_minutes),e.next=3,this.executeRecaptcha();case 3:return r=e.sent,e.next=6,this._networkClient.fetchSDK({url:"/passwords/authenticate",method:"POST",errorMessage:"Failed to authenticate password.",body:{email:t.email,password:t.password,session_duration_minutes:t.session_duration_minutes,captcha_token:r}});case 6:return n=e.sent,this._subscriptionService.updateState({session:n.session,user:n.user,session_token:n.session_token,session_jwt:n.session_jwt}),e.abrupt("return",de(n));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"resetByEmailStart",value:(n=g(y().mark((function e(t){var r,n;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.passwords.resetByEmailStart").isString("email",t.email).isOptionalString("login_redirect_url",t.login_redirect_url).isOptionalNumber("login_expiration_minutes",t.login_expiration_minutes).isOptionalString("reset_password_redirect_url",t.reset_password_redirect_url).isOptionalNumber("reset_password_expiration_minutes",t.reset_password_expiration_minutes),e.next=3,this.getCodeChallenge();case 3:return r=e.sent,e.next=6,this.executeRecaptcha();case 6:return n=e.sent,e.abrupt("return",this._networkClient.fetchSDK({url:"/passwords/email/reset/start",method:"POST",errorMessage:"Failed to start password reset flow.",body:{email:t.email,login_redirect_url:t.login_redirect_url,reset_password_redirect_url:t.reset_password_redirect_url,reset_password_expiration_minutes:t.reset_password_expiration_minutes,code_challenge:r,captcha_token:n}}));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"resetByEmail",value:(r=g(y().mark((function e(t){var r,n,i,o;return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.passwords.resetByEmail").isString("token",t.token).isString("password",t.password).isNumber("session_duration_minutes",t.session_duration_minutes),e.next=3,this.executeRecaptcha();case 3:return n=e.sent,i=null===(r=this._pkceManager.getPKPair())||void 0===r?void 0:r.code_verifier,e.next=7,this._networkClient.fetchSDK({url:"/passwords/email/reset",method:"POST",errorMessage:"Failed to reset password.",body:{token:t.token,password:t.password,session_duration_minutes:t.session_duration_minutes,captcha_token:n,code_verifier:i}});case 7:return o=e.sent,this._pkceManager.clearPKPair(),this._subscriptionService.updateState({session:o.session,user:o.user,session_token:o.session_token,session_jwt:o.session_jwt}),e.abrupt("return",de(o));case 11:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"strengthCheck",value:(t=g(y().mark((function e(t){return y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return pe("stytch.passwords.strengthCheck").isOptionalString("email",t.email).isString("password",t.password),e.abrupt("return",this._networkClient.fetchSDK({url:"/passwords/strength_check",method:"POST",errorMessage:"Failed to check password strength.",body:{email:t.email,password:t.password}}));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}(),Ee=function(){function e(t,r,n){s(this,e),u(this,"_publicToken",void 0),u(this,"_subscriptionDataLayer",void 0),u(this,"baseURL",void 0),u(this,"eventLogger",void 0),u(this,"updateSessionToken",(function(){return null})),this._publicToken=t,this._subscriptionDataLayer=r,this.baseURL=n,this.eventLogger=new _e({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}var t;return c(e,[{key:"logEvent",value:function(e){var t=e.name,r=e.details,n=e.error,i=void 0===n?{}:n;this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:t,details:r,error_code:i.error_code,error_description:i.error_description,http_status_code:i.http_status_code})}},{key:"createTelemetryBlob",value:function(){var e,t;return{event_id:"event-id-".concat(te()),app_session_id:"app-session-id-".concat(te()),persistent_id:"persistent-id-".concat(te()),client_sent_at:(new Date).toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,stytch_user_id:null===(e=this._subscriptionDataLayer.user)||void 0===e?void 0:e.user_id,stytch_session_id:null===(t=this._subscriptionDataLayer.session)||void 0===t?void 0:t.session_id,app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"v0.0.0"}}}},{key:"fetchSDK",value:(t=o(n().mark((function e(t){var r,i,o,s,a,c,u,l,h;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.url,i=t.body,o=t.errorMessage,s=t.method,a=this._subscriptionDataLayer.readSessionCookie().session_token,c="Basic "+window.btoa(this._publicToken+":"+(a||this._publicToken)),u={method:s,headers:{Authorization:c,"Content-Type":"application/json","X-SDK-Parent-Host":window.location.origin,"X-SDK-Client":window.btoa(JSON.stringify(this.createTelemetryBlob()))},body:i&&JSON.stringify(i)},e.prev=4,e.next=7,fetch(this.buildSDKUrl(r),u);case 7:l=e.sent,e.next=15;break;case 10:if(e.prev=10,e.t0=e.catch(4),"Failed to fetch"!==e.t0.message){e.next=14;break}throw new D(o,"Unable to contact the Stytch servers. Are you online?");case 14:throw e.t0;case 15:if(200===l.status){e.next=17;break}return e.abrupt("return",Te(l,o));case 17:return e.prev=17,e.next=20,l.json();case 20:return h=e.sent,e.abrupt("return",h.data);case 24:throw e.prev=24,e.t1=e.catch(17),new D(o,"Invalid response from the Stytch servers.");case 27:case"end":return e.stop()}}),e,this,[[4,10],[17,24]])}))),function(e){return t.apply(this,arguments)})},{key:"buildSDKUrl",value:function(e){return"".concat(this.baseURL,"/sdk/v1").concat(e)}}]),e}(),Te=function(){var e=o(n().mark((function e(t,r){var i;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,t.json();case 3:i=e.sent,e.next=9;break;case 6:throw e.prev=6,e.t0=e.catch(0),new D(r,"Invalid or no response from server");case 9:if(!("body"in i||"params"in i||"query"in i)){e.next=11;break}throw new U(i);case 11:throw new K(i);case 12:case"end":return e.stop()}}),e,null,[[0,6]])})));return function(t,r){return e.apply(this,arguments)}}();
4
+ /*! js-cookie v3.0.1 | MIT */
5
+ function Pe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)e[n]=r[n]}return e}var Le=function e(t,r){function n(e,n,i){if("undefined"!=typeof document){"number"==typeof(i=Pe({},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 o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(n,e)+o}}return Object.create({set:n,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],n={},i=0;i<r.length;i++){var o=r[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(n[a]=t.read(s,a),e===a)break}catch(e){}}return e?n[e]:n}},remove:function(e,t){n(e,"",Pe({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Pe({},this.attributes,t))},withConverter:function(t){return e(Pe({},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:"/"}),Re=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return"".concat("stytch_sdk_state_").concat(e).concat(t?"::".concat(t):"")},je=function(){function e(t,r){var n=this;s(this,e),u(this,"publicToken",void 0),u(this,"session",void 0),u(this,"user",void 0),u(this,"_opaqueTokenCookieName",void 0),u(this,"_jwtCookieName",void 0),u(this,"sessionSubscriptions",void 0),u(this,"userSubscriptions",void 0),u(this,"browserSessionStorage",{getItem:function(e){return sessionStorage.getItem(Re(n.publicToken,e))},setItem:function(e,t){return sessionStorage.setItem(Re(n.publicToken,e),t)},removeItem:function(e){return sessionStorage.removeItem(Re(n.publicToken,e))}}),this.publicToken=t,this.session=null,this.user=null,this.sessionSubscriptions={},this.userSubscriptions={},null!=r&&r.cookieOptions?(pe("SubscriptionDataLayer").isString("cookieOptions.opaqueTokenCookieName",r.cookieOptions.opaqueTokenCookieName).isString("cookieOptions.jwtCookieName",r.cookieOptions.jwtCookieName),this._jwtCookieName=r.cookieOptions.jwtCookieName,this._opaqueTokenCookieName=r.cookieOptions.opaqueTokenCookieName):(this._opaqueTokenCookieName=null,this._jwtCookieName=null);var i=localStorage.getItem(Re(this.publicToken));if(i){var o;try{o=JSON.parse(i)}catch(e){return this.syncToLocalStorage(),void this.removeSessionCookie()}var a=o,c=a.session,l=a.user;this.session=c,this.user=l}else this.removeSessionCookie()}return c(e,[{key:"opaqueTokenCookieName",get:function(){var e;return null!==(e=this._opaqueTokenCookieName)&&void 0!==e?e:"stytch_session"}},{key:"jwtCookieName",get:function(){var e;return null!==(e=this._jwtCookieName)&&void 0!==e?e:"stytch_session_jwt"}},{key:"readSessionCookie",value:function(){return{session_token:Le.get(this.opaqueTokenCookieName),session_jwt:Le.get(this.jwtCookieName)}}},{key:"writeSessionCookie",value:function(t){var r=t.session,n=t.session_token,i=t.session_jwt,o=e.generateCookieOpts(r.expires_at);Le.set(this.opaqueTokenCookieName,n,o),Le.set(this.jwtCookieName,i,o)}},{key:"removeSessionCookie",value:function(){var t=e.generateCookieOpts();Le.remove(this.opaqueTokenCookieName,t),Le.remove(this.jwtCookieName,t)}},{key:"syncToLocalStorage",value:function(){localStorage.setItem(Re(this.publicToken),JSON.stringify({session:this.session,user:this.user}))}},{key:"getItem",value:function(e){return localStorage.getItem(Re(this.publicToken,e))}},{key:"setItem",value:function(e,t){return localStorage.setItem(Re(this.publicToken,e),t)}},{key:"removeItem",value:function(e){return localStorage.removeItem(Re(this.publicToken,e))}}],[{key:"generateCookieOpts",value:function(e){var t={sameSite:"lax"};return e&&(t.expires=new Date(e)),De()?t.secure=!1:(t.domain=window.location.host,t.secure=!0),t}}]),e}(),Ae={},Ie=function(e,t){return Ae[e]||(Ae[e]=new je(e,t)),Ae[e]},Me=function(e,t){var r=Math.random().toString(36).slice(-10);return e[r]=t,function(){return delete e[r]}},Fe=function(e,t){Object.values(e).forEach((function(e){return e(t)}))},De=function(){return Boolean("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}$/))},Ne=he({KEYS_TO_EXCLUDE:["last_accessed_at"]}),Ue=he(),Ke=function(){function e(t,r){var n=this;s(this,e),u(this,"_publicToken",void 0),u(this,"_datalayer",void 0),u(this,"_listen",(function(e){e.key===Re(n._publicToken)&&(null!==e.newValue?n._updateStateInternal(JSON.parse(e.newValue)):n.destroyState())})),this._publicToken=t,this._datalayer=r,window.addEventListener("storage",this._listen);var i=this._datalayer.session;i&&Date.parse(i.expires_at)<Date.now()?this.destroyState():this._datalayer.readSessionCookie().session_token||this.destroyState()}return c(e,[{key:"getSession",value:function(){return this._datalayer.session}},{key:"getTokens",value:function(){var e=this._datalayer.readSessionCookie(),t=e.session_token,r=e.session_jwt;return t&&r?{session_token:t,session_jwt:r}:null}},{key:"destroyState",value:function(){this.updateState({session:null,user:null,session_token:null,session_jwt:null})}},{key:"_updateStateInternal",value:function(e){var t=e.session,r=e.user,n=this._datalayer.session,i=this._datalayer.user;this._datalayer.session=t,this._datalayer.user=r,Ne(n,t)||Fe(this._datalayer.sessionSubscriptions,t),Ue(i,r)||Fe(this._datalayer.userSubscriptions,r)}},{key:"updateState",value:function(e){e.session?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._updateStateInternal(e),this._datalayer.syncToLocalStorage()}},{key:"updateUser",value:function(e){var t=this._datalayer.user;this._datalayer.user=e,Ue(t,e)||(Fe(this._datalayer.userSubscriptions,e),this._datalayer.syncToLocalStorage())}},{key:"subscribeToSession",value:function(e){return Me(this._datalayer.sessionSubscriptions,e)}},{key:"getUser",value:function(){return this._datalayer.user}},{key:"subscribeToUser",value:function(e){return Me(this._datalayer.userSubscriptions,e)}},{key:"destroy",value:function(){window.removeEventListener("storage",this._listen)}},{key:"syncFromDeviceStorage",value:function(){return null}}]),e}();function Be(e){var t=e.toString(16);return 1===t.length&&(t="0"+t),t}var Ge=function(){function e(t){s(this,e),u(this,"_dataLayer",void 0),this._dataLayer=t}var r,i;return c(e,[{key:"startPKCETransaction",value:(i=o(n().mark((function t(){var r;return n().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.createProofkeyPair();case 2:return r=t.sent,this._dataLayer.setItem("PKCE_VERIFIER",JSON.stringify(r)),t.abrupt("return",r);case 5:case"end":return t.stop()}}),t,this)}))),function(){return i.apply(this,arguments)})},{key:"getPKPair",value:function(){var e=this._dataLayer.getItem("PKCE_VERIFIER");if(null!==e)try{return JSON.parse(e)}catch(e){return void ce("Found malformed Proof Key pair in localstorage.")}}},{key:"clearPKPair",value:function(){return this._dataLayer.removeItem("PKCE_VERIFIER")}}],[{key:"createProofkeyPair",value:(r=o(n().mark((function e(){var r,i,o;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Uint32Array(16),window.crypto.getRandomValues(r),i=Array.from(r).map(Be).join(""),e.next=5,window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(i));case 5:return o=e.sent,e.abrupt("return",{code_challenge:(n=o,s=void 0,btoa((s=String.fromCharCode).call.apply(s,[null].concat(t(new Uint8Array(n))))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:i});case 7:case"end":return e.stop()}var n,s}),e)}))),function(){return r.apply(this,arguments)})}]),e}(),qe=function(){function e(t,r,n){var i=this;s(this,e),u(this,"_publicToken",void 0),u(this,"_networkClient",void 0),u(this,"_dataLayer",void 0),u(this,"_bootstrapDataPromise",void 0),this._publicToken=t,this._networkClient=r,this._dataLayer=n,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:"/projects/bootstrap/".concat(this._publicToken),method:"GET",errorMessage:"Error fetching bootstrap data for SDK for ".concat(this._publicToken)}).then(e.mapBootstrapData).then((function(e){return i._dataLayer.setItem("bootstrap",JSON.stringify(e)),e})).catch((function(e){return ue(e),{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1}}))}return c(e,[{key:"getSync",value:function(){var e=this._dataLayer.getItem("bootstrap");if(null===e)return{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1};try{return JSON.parse(e)}catch(e){return{displayWatermark:!1,cnameDomain:null,captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1}}}},{key:"getAsync",value:function(){return this._bootstrapDataPromise}}],[{key:"mapBootstrapData",value:function(e){return{displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth}}}]),e}(),We=c((function e(t){var r=this;s(this,e),u(this,"bootstrapPromise",void 0),u(this,"state",void 0),u(this,"executeRecaptcha",o(n().mark((function e(){var t,i,o,s;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,r.state;case 2:if(t=e.sent,i=t.captchaClient,o=t.configured,s=t.siteKey,o){e.next=8;break}return e.abrupt("return",void 0);case 8:return e.next=10,new Promise((function(e){return i.ready(e)}));case 10:return e.abrupt("return",i.execute(s,{action:"LOGIN"}));case 11:case"end":return e.stop()}}),e)})))),this.bootstrapPromise=t,this.state=t.then(function(){var e=o(n().mark((function e(t){return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.captchaSettings.enabled){e.next=2;break}return e.abrupt("return",{configured:!1});case 2:return e.next=4,r=t.captchaSettings.siteKey,ne("https://www.google.com/recaptcha/enterprise.js?render=".concat(r),(function(){return window.grecaptcha.enterprise}));case 4:return e.t0=e.sent,e.t1=t.captchaSettings.siteKey,e.abrupt("return",{configured:!0,captchaClient:e.t0,siteKey:e.t1});case 7:case"end":return e.stop()}var r}),e)})));return function(t){return e.apply(this,arguments)}}())}));exports.Products=void 0,function(e){e.emailMagicLinks="emailMagicLinks",e.oauth="oauth",e.otp="otp",e.crypto="crypto"}(exports.Products||(exports.Products={})),exports.OAuthProviders=void 0,function(e){e.Google="google",e.Microsoft="microsoft",e.Apple="apple",e.Github="github",e.GitLab="gitlab",e.Facebook="facebook",e.Discord="discord",e.Slack="slack",e.Amazon="amazon",e.Bitbucket="bitbucket",e.LinkedIn="linkedin"}(exports.OAuthProviders||(exports.OAuthProviders={})),exports.Wallets=void 0,function(e){e.Vessel="Vessel",e.Phantom="Phantom",e.Metamask="Metamask",e.Coinbase="Coinbase",e.Binance="Binance",e.GenericEthereumWallet="Other Ethereum Wallet",e.GenericSolanaWallet="Other Solana Wallet"}(exports.Wallets||(exports.Wallets={})),exports.OneTapPositions=void 0,function(e){e.embedded="embedded",e.floating="floating"}(exports.OneTapPositions||(exports.OneTapPositions={})),exports.OTPMethods=void 0,function(e){e.SMS="sms",e.WhatsApp="whatsapp",e.Email="email"}(exports.OTPMethods||(exports.OTPMethods={})),exports.StytchEventType=void 0,function(e){e.MagicLinkLoginOrCreateEvent="MAGIC_LINK_LOGIN_OR_CREATE",e.OTPsLoginOrCreateEvent="OTP_LOGIN_OR_CREATE",e.OTPsAuthenticate="OTP_AUTHENTICATE",e.CryptoWalletAuthenticateStart="CRYPTO_WALLET_AUTHENTICATE_START",e.CryptoWalletAuthenticate="CRYPTO_WALLET_AUTHENTICATE_"}(exports.StytchEventType||(exports.StytchEventType={}));var ze=function(){function e(t,r,n){s(this,e),u(this,"_googleClient",void 0),u(this,"_publicToken",void 0),u(this,"_clientId",void 0),this._googleClient=t,this._publicToken=r,this._clientId=n}var t;return c(e,[{key:"render",value:(t=o(n().mark((function e(t){var r,i,o,s,a=this;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.callback,i=t.onOneTapCancelled,o=t.style,s={client_id:this._clientId,callback:r,auto_select:!1,context:"use",itp_support:!0},o.position===exports.OneTapPositions.embedded&&(s.prompt_parent_id="google-parent-prompt",s.cancel_on_tap_outside=!1),this._googleClient.initialize(s),e.abrupt("return",new Promise((function(e){a._googleClient.prompt((function(t){return t.isSkippedMoment()?("user_cancel"===t.getSkippedReason()&&i(),e(!1)):t.isNotDisplayed()?("unregistered_origin"===t.getNotDisplayedReason()&&i(!0),e(!1)):(a.styleFrame(o),e(!0))}))})));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"styleFrame",value:function(e){e.position===exports.OneTapPositions.embedded&&Array.from(document.getElementsByTagName("iframe")).forEach((function(e){e.src.includes("https://accounts.google.com/gsi")&&(e.style.width="100%")}))}}]),e}(),Ve=function(){function e(t,r){var i=this;s(this,e),u(this,"_publicToken",void 0),u(this,"frameClient",void 0),u(this,"googleConfig",void 0),u(this,"createOnSuccessHandler",(function(e){var t=e.loginRedirectUrl,r=e.signupRedirectUrl,s=e.onSuccess;return function(){var e=o(n().mark((function e(o){var a,c,u;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=o.credential,e.next=3,i.submitGoogleOneTapToken({credential:a,loginRedirectUrl:t,signupRedirectUrl:r});case 3:c=e.sent,u=c.redirect_url,s(u);case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()})),u(this,"RedirectOnSuccess",(function(e){window.location.href=e})),this._publicToken=t,this.frameClient=new G(r)}var t,r;return c(e,[{key:"createOneTapClient",value:(r=o(n().mark((function e(){var t,r;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.fetchGoogleStart();case 2:if(t=e.sent,""!==(r=t.googleClientId)){e.next=6;break}return e.abrupt("return",null);case 6:return e.t0=ze,e.next=9,ne(F,(function(){return window.google.accounts.id}));case 9:return e.t1=e.sent,e.t2=this._publicToken,e.t3=r,e.abrupt("return",new e.t0(e.t1,e.t2,e.t3));case 13:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"fetchGoogleStart",value:function(){return this.googleConfig||(this.googleConfig=this.frameClient.call("oneTapStart",[this._publicToken])),this.googleConfig}},{key:"submitGoogleOneTapToken",value:(t=o(n().mark((function e(t){var r,i,o,s,a;return n().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.credential,i=t.loginRedirectUrl,o=t.signupRedirectUrl,e.next=3,this.fetchGoogleStart();case 3:return s=e.sent,a=s.oauthCallbackId,e.abrupt("return",this.frameClient.call("oneTapSubmit",[this._publicToken,r,a,i,o]));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}(),He=Symbol.for("stytch__internal"),Je=function(e,t){Object.assign(e,u({},He,t))},Ye=c((function e(t){s(this,e),u(this,"_subscriptionService",void 0),u(this,"_sessionManager",void 0),u(this,"_networkClient",void 0),u(this,"_dataLayer",void 0),u(this,"_pkceManager",void 0),u(this,"user",void 0),u(this,"magicLinks",void 0),u(this,"session",void 0),u(this,"otps",void 0),u(this,"oauth",void 0),u(this,"cryptoWallets",void 0),u(this,"totps",void 0),u(this,"passwords",void 0);var r=arguments[1];le(t);var n=$e(r);this._dataLayer=Ie(t,r),this._subscriptionService=new Ke(t,this._dataLayer),this._networkClient=new Ee(t,this._dataLayer,n.endpoints.sdkBackendURL),this._pkceManager=new Ge(this._dataLayer);var i=new qe(t,this._networkClient,this._dataLayer),o=new We(i.getAsync()),a=new Ve(t,n.endpoints.oneTapIFrameURL);this.user=new ye(this._networkClient,this._subscriptionService),this.session=new me(this._networkClient,this._subscriptionService),this.magicLinks=new we(this._networkClient,this._subscriptionService,this._pkceManager,i.getAsync(),o.executeRecaptcha),this.otps=new be(this._networkClient,this._subscriptionService,o.executeRecaptcha),this.oauth=new ke(this._networkClient,this._subscriptionService,this._pkceManager,i.getAsync(),{publicToken:t,testAPIURL:n.endpoints.testAPIURL,liveAPIURL:n.endpoints.liveAPIURL}),this.cryptoWallets=new Se(this._networkClient,this._subscriptionService,o.executeRecaptcha),this.totps=new xe(this._networkClient,this._subscriptionService),this.passwords=new Ce(this._networkClient,this._subscriptionService,this._pkceManager,i.getAsync(),o.executeRecaptcha),this._sessionManager=new ve(this._subscriptionService,this.session),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}}),Je(this,{bootstrap:i,captcha:o,oneTap:a})}));function $e(e){var t,r,n,i,o,s,a,c;return{cookieOptions:null==e?void 0:e.cookieOptions,endpoints:{sdkBackendURL:null!==(t=null==e||null===(r=e.endpoints)||void 0===r?void 0:r.sdkBackendURL)&&void 0!==t?t:"https://web.stytch.com",testAPIURL:null!==(n=null==e||null===(i=e.endpoints)||void 0===i?void 0:i.testAPIURL)&&void 0!==n?n:"https://test.stytch.com",liveAPIURL:null!==(o=null==e||null===(s=e.endpoints)||void 0===s?void 0:s.liveAPIURL)&&void 0!==o?o:"https://api.stytch.com",oneTapIFrameURL:null!==(a=null==e||null===(c=e.endpoints)||void 0===c?void 0:c.oneTapIFrameURL)&&void 0!==a?a:"https://js.stytch.com/one-tap/index.html"}}}exports.StytchHeadlessClient=Ye;