@edgespark/web 0.0.0-beta.4ec283e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +310 -0
  2. package/auth/styles/styles.css +402 -0
  3. package/dist/api/fetch.d.ts +8 -0
  4. package/dist/api/types.d.ts +13 -0
  5. package/dist/auth/create-auth.d.ts +18 -0
  6. package/dist/auth/local-dev.d.ts +41 -0
  7. package/dist/auth/placeholder-email.d.ts +7 -0
  8. package/dist/auth/types.d.ts +84 -0
  9. package/dist/auth-ui/ManagedAuthUI.d.ts +114 -0
  10. package/dist/auth-ui/appearance.d.ts +64 -0
  11. package/dist/auth-ui/config.d.ts +60 -0
  12. package/dist/auth-ui/default-labels.d.ts +2 -0
  13. package/dist/auth-ui/google-one-tap.d.ts +47 -0
  14. package/dist/auth-ui/index.d.ts +4 -0
  15. package/dist/auth-ui/mount.d.ts +22 -0
  16. package/dist/auth-ui/prompt-google-one-tap.d.ts +43 -0
  17. package/dist/auth-ui/runtime.d.ts +7 -0
  18. package/dist/auth-ui/types.d.ts +202 -0
  19. package/dist/browser.d.ts +2 -0
  20. package/dist/client.d.ts +43 -0
  21. package/dist/errors.d.ts +32 -0
  22. package/dist/index.cjs +197 -0
  23. package/dist/index.d.ts +29 -0
  24. package/dist/index.es.js +2994 -0
  25. package/dist/locales/ar.d.ts +2 -0
  26. package/dist/locales/de.d.ts +2 -0
  27. package/dist/locales/en-US.d.ts +2 -0
  28. package/dist/locales/es.d.ts +2 -0
  29. package/dist/locales/fr.d.ts +2 -0
  30. package/dist/locales/hi.d.ts +2 -0
  31. package/dist/locales/index.d.ts +21 -0
  32. package/dist/locales/it.d.ts +2 -0
  33. package/dist/locales/ja.d.ts +2 -0
  34. package/dist/locales/ko.d.ts +2 -0
  35. package/dist/locales/pt-BR.d.ts +2 -0
  36. package/dist/locales/ru.d.ts +2 -0
  37. package/dist/locales/zh-CN.d.ts +2 -0
  38. package/dist/redirect.d.ts +5 -0
  39. package/dist/shared/types.d.ts +6 -0
  40. package/package.json +53 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,197 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("better-auth/client");class Y extends Error{constructor(e,i){super(i),this.name="EdgeSparkError",this.code=e}}class f extends Y{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class ve extends Y{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class E extends Y{constructor(e,i){super((i==null?void 0:i.code)??"AUTH_ERROR",e),this.name="EdgeSparkAuthError",this.cause=i==null?void 0:i.cause,this.status=i==null?void 0:i.status}}function ye(t,e="Authentication failed.",i){if(t instanceof E)return t;if(typeof t=="object"&&t!==null){const s=t;return new E(s.message||e,{code:s.code??i,status:s.status,cause:t})}return typeof t=="string"?new E(t,{code:i}):new E(e,{code:i,cause:t})}function Be(){if(typeof window>"u"||typeof document>"u")throw new ve("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function le(){return Be(),window.location.origin}function Je(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function Xe(t){if(t.origin!==le())throw new f(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${le()}.`)}function Ze(){return{async fetch(t,e){const i=Je(t);return Xe(i),fetch(t,{...e,credentials:"include"})}}}const De="/api/_es/auth",Qe="edgespark-auth-session",Ne="__edgespark_auth_sync__",J="__edgespark_auth_pending_sign_in__",Ve=Symbol("edgespark.notifyAuthTabs"),et=10*60*1e3,tt=new Set(["signOut","revokeSession","revokeSessions","revokeOtherSessions"]),it=new Map([["changeEmail","changeEmail() is not currently supported by EdgeSpark platform auth. Use authUI.mount() or other supported client.auth flows instead of wiring raw /api/_es/auth/* routes manually."],["deleteUser","deleteUser() is not currently supported by EdgeSpark platform auth. Handle account removal through your own app flow until the platform enables this capability."],["deleteUserCallback","deleteUserCallback() is not currently supported by EdgeSpark platform auth. Handle account removal through your own app flow until the platform enables this capability."]]);class st{constructor(e){this.value=e}deref(){return this.value}}const Ie=globalThis.WeakRef,_e=globalThis.FinalizationRegistry;let Z,Le=!1;const D=new Map,Q=_e?new _e(t=>{D.delete(t)}):null;function Fe(t){return Ye.createAuthClient({baseURL:le(),basePath:De,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function B(t){var e,i;return(i=(e=t.$store)==null?void 0:e.atoms)==null?void 0:i.session}function nt(t){return JSON.stringify({source:t,timestamp:Date.now()})}function ot(t){if(typeof t!="string")return null;try{const e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function rt(t){return t.join(".")}function at(t){const e=rt(t),i=it.get(e);return i?new E(i,{code:"UNSUPPORTED_AUTH_METHOD"}):null}async function de(t){var e;try{return await((e=B(t))==null?void 0:e.get().refetch()),!0}catch{return!1}}function He(){return Z===void 0&&(Z=typeof BroadcastChannel<"u"?new BroadcastChannel(Qe):null),Z}function Ae(t){const e=ot(t);if(e)for(const[i,s]of D){if(i===e.source)continue;const n=s.deref();if(!n){D.delete(i);continue}de(n)}}function lt(){var t;Le||(Le=!0,(t=He())==null||t.addEventListener("message",e=>{Ae(e.data)}),typeof window<"u"&&window.addEventListener("storage",e=>{e.key!==Ne||e.newValue===null||Ae(e.newValue)}))}function dt(t,e){Ie?D.set(t,new Ie(e)):(D.clear(),D.set(t,new st(e))),Q==null||Q.register(e,t),lt()}function O(t){const e=nt(t),i=He();let s=!1;if(i)try{i.postMessage(e),s=!0}catch{}if(!s)try{window.localStorage.setItem(Ne,e)}catch{}}function ee(t){if(!(typeof window>"u"))try{window.sessionStorage.setItem(J,JSON.stringify({path:t,createdAt:Date.now()}))}catch{}}function M(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(J)}catch{}}function ct(t){return!!(t!=null&&t.session&&(t!=null&&t.user))}function v(t){return t instanceof Date?t.toISOString():t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:t==null?null:String(t)}function ut(t){return t?JSON.stringify({session:{createdAt:v(t.session.createdAt),expiresAt:v(t.session.expiresAt),id:v(t.session.id),impersonatedBy:v(t.session.impersonatedBy),ipAddress:v(t.session.ipAddress),token:v(t.session.token),updatedAt:v(t.session.updatedAt),userAgent:v(t.session.userAgent),userId:v(t.session.userId)},user:{banExpires:v(t.user.banExpires),banReason:v(t.user.banReason),banned:v(t.user.banned),createdAt:v(t.user.createdAt),email:v(t.user.email),emailVerified:v(t.user.emailVerified),id:v(t.user.id),image:v(t.user.image),lastLoginAt:v(t.user.lastLoginAt),name:v(t.user.name),role:v(t.user.role),updatedAt:v(t.user.updatedAt)}}):"__null__"}function ze(){if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(J);if(!t)return null;const e=JSON.parse(t);return!e||typeof e!="object"||typeof e.createdAt!="number"||Date.now()-e.createdAt>et?null:{createdAt:e.createdAt}}catch{return null}}function Ce(){if(!ze())return!1;try{window.sessionStorage.removeItem(J)}catch{}return!0}function ht(){return ze()!==null}function mt(t){if(!(t&&typeof t=="object")||"error"in t&&t.error)return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"token"in e&&typeof e.token=="string"&&e.token.length>0?!0:"session"in e&&"user"in e&&!!e.session&&!!e.user:!1}function pt(t){if(!(t&&typeof t=="object")||"error"in t&&t.error)return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"url"in e&&typeof e.url=="string":!1}function gt(t){if(k(t)||!(t&&typeof t=="object"))return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"user"in e&&!!e.user&&"token"in e&&e.token===null&&!("url"in e):!1}function ft(t,e){if(t.length!==1||t[0]!=="changePassword")return!1;const[i]=e;return!!(i&&typeof i=="object"&&"revokeOtherSessions"in i&&i.revokeOtherSessions===!0)}function k(t){return!!(t&&typeof t=="object"&&"error"in t&&t.error)}function bt(t){if(k(t)||!(t&&typeof t=="object"))return!1;const e="data"in t?t.data:t;return e&&typeof e=="object"?"message"in e&&e.message==="User deleted":!1}function wt(t){return!!(t&&(typeof t=="object"||typeof t=="function")&&"then"in t&&typeof t.then=="function")}function te(t){return ye(t,"Failed to load the current session.","SESSION_LOOKUP_FAILED")}async function vt(t){var i,s;let e=null;try{await((i=B(t))==null?void 0:i.get().refetch())}catch(n){e=n}finally{(s=t[Ve])==null||s.call(t)}if(e)throw e}function yt(){const t=Fe(),e=`${Date.now()}-${Math.random().toString(36).slice(2)}`;dt(e,t);const i=2,s=500;let n=null,r=!1,l;const h=a=>(l=a,a),p=()=>{var m;const a=(m=B(t))==null?void 0:m.get();return a!=null&&a.error&&!a.data&&l!==void 0?l:(a==null?void 0:a.data)??l??null},I=()=>r?Promise.resolve(p()):(n||(n=(async()=>{var d,g,C;let a=!1,m=null;try{for(let _=0;_<=i;_++){let u=null;try{u=await t.getSession()}catch(R){m=R}const y=((d=B(t))==null?void 0:d.get().data)??null;if((g=u==null?void 0:u.data)!=null&&g.session&&((C=u.data)!=null&&C.user))return r=!0,Ce()&&O(e),h(u.data);if(y!=null&&y.session&&(y!=null&&y.user))return r=!0,Ce()&&O(e),h(y);if(u!=null&&u.error?m=u.error:u&&(a=!0),u&&!u.error&&ht()&&_<i){await new Promise(R=>setTimeout(R,s));continue}if(u&&!u.error){const R=p();return r=!0,h(R)}_<i&&await new Promise(R=>setTimeout(R,s))}if(!a)throw n=null,new E("Failed to load the current session.",{code:"SESSION_LOOKUP_FAILED",cause:m});const S=p();return r=!0,h(S)}catch(S){throw n=null,te(S)}})()),n);I().catch(()=>{});const w=async()=>{var a,m;try{const d=await t.getSession();if((a=d.data)!=null&&a.session&&((m=d.data)!=null&&m.user))return d.data;throw d.error?te(d.error):new E("No authenticated session is available.",{code:"UNAUTHENTICATED"})}catch(d){throw te(d)}},b=async()=>{await de(t),O(e)},P=async()=>{var d;const a=await de(t),m=((d=B(t))==null?void 0:d.get().data)??null;ct(m)?(M(),O(e)):a||O(e)},c=a=>{let m=!1,d=!1,g;const C=u=>{const y=ut(u);y!==g&&(g=y,a(u))};I().then(u=>{m||(d=!0,C(h(u)))}).catch(()=>{m||(d=!0)});const S=B(t);if(!S)return()=>{m=!0};const _=S.subscribe(u=>{if(m||!d||u.error&&!u.data)return;const y=u.data??null;C(h(y))});return()=>{m=!0,_()}},L=async(a,m,d)=>{const g=a[0],C=a.length>=2&&g==="emailOtp"&&a[1]==="verifyEmail",S=a.length>=2&&g==="emailOtp"&&a[1]==="resetPassword",_=a.length>=2&&g==="resetPassword"&&a[1]==="emailOtp",u=a.length>=2&&g==="oneTap"&&a[1]==="callback",y=a.length>=2&&g==="phoneNumber"&&a[1]==="verify";return a.length===1&&(g==="deleteUser"||g==="deleteUserCallback")?(M(),bt(d)&&await b(),d):a.length===1&&g&&tt.has(g)?(M(),k(d)||await b(),d):ft(a,m)&&!k(d)?(M(),await b(),d):(S||_)&&!k(d)?(M(),await b(),d):a.length===1&&g==="changeEmail"&&!k(d)?(await b(),d):((g==="signIn"||g==="signUp"||C||u||y)&&mt(d)?(M(),await b()):(g==="signIn"||g==="signUp")&&pt(d)||g==="signUp"&&gt(d)?ee(a):g==="verifyEmail"&&!k(d)&&(ee(a),await P()),d)},A=new WeakMap,T=(a,m)=>{if(!a||typeof a!="object"&&typeof a!="function")return a;const d=A.get(a);if(d)return d;const g=new Proxy(a,{get(C,S,_){if(m.length===0){if(S==="requireSession")return w;if(S==="onSessionChange")return c;if(S===Ve)return()=>{O(e)}}const u=Reflect.get(C,S,_);return typeof S!="string"?u:T(u,[...m,S])},apply(C,S,_){const u=at(m);if(u)throw u;const y=Reflect.apply(C,S,_);return wt(y)?Promise.resolve(y).then(R=>L(m,_,R)):y}});return A.set(a,g),g};return T(t,[])}function St(){return Fe({disableDefaultRedirectPlugin:!0})}const X="/api/_es/dev";function Pt(){if(typeof document>"u")return!1;const t=document.querySelector('meta[name="edgespark-local-dev"]');return(t==null?void 0:t.getAttribute("content"))==="true"}async function Et(t){const e=typeof window<"u"?window.location.origin:"";if(!e)return!1;const i=await fetch(`${e}${X}/auto-verify?email=${encodeURIComponent(t)}`,{credentials:"include"});return i.ok?(await i.json()).verified===!0:!1}async function It(t){const e=typeof window<"u"?window.location.origin:"";if(!e)return null;try{const i=await fetch(`${e}${X}/pending-otp?email=${encodeURIComponent(t)}`,{credentials:"include"});return i.ok?(await i.json()).otp??null:null}catch{return null}}async function _t(t){const e=typeof window<"u"?window.location.origin:"";if(!e)return null;try{const i=await fetch(`${e}${X}/pending-sign-in-otp?email=${encodeURIComponent(t)}`,{credentials:"include"});return i.ok?(await i.json()).otp??null:null}catch{return null}}async function Lt(t){const e=typeof window<"u"?window.location.origin:"";if(!e)return null;try{const i=await fetch(`${e}${X}/pending-phone-otp?phoneNumber=${encodeURIComponent(t)}`,{credentials:"include"});return i.ok?(await i.json()).otp??null:null}catch{return null}}function At(t){const e=(()=>{if(t instanceof URL)return t;const i=t.trim();if(!i)throw new f("redirectTo must not be an empty string.");try{return new URL(i,window.location.href)}catch{throw new f(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new f(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function Ct(t,e){return e?{common:{...t.common,...e.common},signIn:{...t.signIn,...e.signIn},signUp:{...t.signUp,...e.signUp},verifyEmail:{...t.verifyEmail,...e.verifyEmail},forgotPassword:{...t.forgotPassword,...e.forgotPassword},resetPassword:{...t.resetPassword,...e.resetPassword},oauth:{...t.oauth,...e.oauth},errors:{...t.errors,...e.errors}}:t}const F={common:{loading:"Loading sign-in…",redirecting:"Redirecting…",backToSignIn:"Back to sign in"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Sign-in code sent to your email",sendingCode:"Sending sign-in code…",signingIn:"Signing in…",title:"Welcome back",subtitle:"Sign in to continue",emailLabel:"Email",passwordLabel:"Password",submitButton:"Sign in",resendCodeButton:"Resend code",resendCountdown:"Resend in {seconds}s",forgotPassword:"Forgot password?",switchToSignUp:"Create an account",signUpPrompt:"Don’t have an account?",phoneTab:"Phone",phoneLabel:"Phone number",phonePlaceholder:"11-digit mobile number",phoneCodePlaceholder:"Code sent by SMS. Use the most recent one."},signUp:{title:"Create your account",subtitle:"Start with your name, email, and password",nameLabel:"Name",emailLabel:"Email",passwordLabel:"Password",confirmPasswordLabel:"Confirm password",submitButton:"Create account",switchToSignIn:"Sign in",signInPrompt:"Already have an account?"},verifyEmail:{title:"Verify your email",subtitle:"Finish account setup from the verification email we sent.",sentToLabel:"Sent to",resendButton:"Resend verification email",resendCountdown:"Resend in {seconds}s",changeEmailButton:"Use a different email"},forgotPassword:{title:"Reset your password",subtitle:"Enter your email and we will send a reset code.",emailLabel:"Email",submitButton:"Send reset code"},resetPassword:{title:"Set a new password",subtitle:"Use the code from your email to finish resetting your password.",codeLabel:"Verification code",newPasswordLabel:"New password",confirmPasswordLabel:"Confirm password",submitButton:"Update password",resendCodeButton:"Resend code",resendCountdown:"Resend in {seconds}s"},oauth:{redirecting:"Redirecting to {provider}…",dividerText:"or",continueWith:"Continue with"},errors:{invalidEmail:"Enter a valid email address.",requiredField:"This field is required.",passwordTooShort:"Password must be at least {min} characters.",passwordMismatch:"Passwords do not match.",invalidCode:"Enter the 6-digit verification code.",generic:"Something went wrong. Please try again.",invalidPhone:"Enter a valid mainland China mobile number",smsRateLimited:"Too many code requests. Please try again later.",smsSendFailed:"Couldn’t send the SMS. Please try again later."}},K={common:{loading:"加载中…",redirecting:"跳转中…",backToSignIn:"返回登录"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"登录验证码已发送至你的邮箱",sendingCode:"正在发送登录验证码…",signingIn:"正在登录…",title:"欢迎回来",subtitle:"登录以继续",emailLabel:"邮箱",passwordLabel:"密码",submitButton:"登录",forgotPassword:"忘记密码?",switchToSignUp:"立即注册",signUpPrompt:"没有账号?",phoneTab:"手机号",phoneLabel:"手机号",phonePlaceholder:"11 位手机号",phoneCodePlaceholder:"验证码已通过短信发送,请以最新一条为准"},signUp:{title:"创建账号",subtitle:"填写姓名、邮箱和密码开始使用",nameLabel:"姓名",emailLabel:"邮箱",passwordLabel:"密码",confirmPasswordLabel:"确认密码",submitButton:"注册",switchToSignIn:"去登录",signInPrompt:"已有账号?"},verifyEmail:{title:"验证邮箱",subtitle:"请查收邮件并点击验证链接",sentToLabel:"已发送至",resendButton:"重新发送验证邮件",resendCountdown:"{seconds}秒后可重发",changeEmailButton:"更换邮箱"},forgotPassword:{title:"重置密码",subtitle:"输入邮箱以接收重置验证码",emailLabel:"邮箱",submitButton:"发送重置码"},resetPassword:{title:"设置新密码",subtitle:"使用邮件中的验证码完成密码重置",codeLabel:"验证码",newPasswordLabel:"新密码",confirmPasswordLabel:"确认密码",submitButton:"更新密码",resendCodeButton:"重新发送",resendCountdown:"{seconds}秒后可重发"},oauth:{redirecting:"正在跳转至 {provider}…",dividerText:"或",continueWith:"使用"},errors:{invalidEmail:"请输入有效的邮箱地址",requiredField:"此项为必填",passwordTooShort:"密码至少需要 {min} 个字符",passwordMismatch:"两次密码输入不一致",invalidCode:"请输入 6 位验证码",generic:"出现错误,请稍后重试",invalidPhone:"请输入有效的中国大陆手机号",smsRateLimited:"验证码发送过于频繁,请稍后再试",smsSendFailed:"短信发送失败,请稍后重试"}},ce={common:{loading:"サインインを読み込み中…",redirecting:"リダイレクト中…",backToSignIn:"サインインに戻る"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"ログインコードをメールに送信しました",sendingCode:"ログインコードを送信中…",signingIn:"ログイン中…",title:"おかえりなさい",subtitle:"サインインして続行",emailLabel:"メールアドレス",passwordLabel:"パスワード",submitButton:"サインイン",forgotPassword:"パスワードをお忘れですか?",switchToSignUp:"アカウントを作成",signUpPrompt:"アカウントをお持ちでない方",phoneTab:"電話番号",phoneLabel:"電話番号",phonePlaceholder:"11桁の携帯電話番号",phoneCodePlaceholder:"SMSで認証コードを送信しました。最新のコードを使用してください"},signUp:{title:"アカウントを作成",subtitle:"名前、メールアドレス、パスワードを入力してください",nameLabel:"名前",emailLabel:"メールアドレス",passwordLabel:"パスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"アカウント作成",switchToSignIn:"サインイン",signInPrompt:"既にアカウントをお持ちですか?"},verifyEmail:{title:"メールアドレスを確認",subtitle:"送信した確認メールからアカウント設定を完了してください",sentToLabel:"送信先",resendButton:"確認メールを再送信",resendCountdown:"{seconds}秒後に再送信可能",changeEmailButton:"別のメールアドレスを使用"},forgotPassword:{title:"パスワードをリセット",subtitle:"メールアドレスを入力するとリセットコードをお送りします",emailLabel:"メールアドレス",submitButton:"リセットコードを送信"},resetPassword:{title:"新しいパスワードを設定",subtitle:"メールで届いた認証コードを使ってパスワードをリセットしてください",codeLabel:"認証コード",newPasswordLabel:"新しいパスワード",confirmPasswordLabel:"パスワード(確認)",submitButton:"パスワードを更新",resendCodeButton:"コードを再送信",resendCountdown:"{seconds}秒後に再送信可能"},oauth:{redirecting:"{provider} に移動中…",dividerText:"または",continueWith:"で続行"},errors:{invalidEmail:"有効なメールアドレスを入力してください",requiredField:"この項目は必須です",passwordTooShort:"パスワードは {min} 文字以上で入力してください",passwordMismatch:"パスワードが一致しません",invalidCode:"6桁の認証コードを入力してください",generic:"エラーが発生しました。もう一度お試しください",invalidPhone:"有効な中国本土の携帯電話番号を入力してください",smsRateLimited:"コードの送信回数が多すぎます。しばらくしてから再度お試しください",smsSendFailed:"SMSを送信できませんでした。しばらくしてから再度お試しください"}},ue={common:{loading:"로그인 로딩 중…",redirecting:"리디렉션 중…",backToSignIn:"로그인으로 돌아가기"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"로그인 코드를 이메일로 보냈습니다",sendingCode:"로그인 코드 전송 중…",signingIn:"로그인 중…",title:"다시 오신 것을 환영합니다",subtitle:"로그인하여 계속하기",emailLabel:"이메일",passwordLabel:"비밀번호",submitButton:"로그인",forgotPassword:"비밀번호를 잊으셨나요?",switchToSignUp:"계정 만들기",signUpPrompt:"계정이 없으신가요?",phoneTab:"휴대폰",phoneLabel:"휴대폰 번호",phonePlaceholder:"11자리 휴대폰 번호",phoneCodePlaceholder:"SMS로 인증 코드를 보냈습니다. 가장 최근 코드를 사용하세요"},signUp:{title:"계정 만들기",subtitle:"이름, 이메일, 비밀번호를 입력해 주세요",nameLabel:"이름",emailLabel:"이메일",passwordLabel:"비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"계정 생성",switchToSignIn:"로그인",signInPrompt:"이미 계정이 있으신가요?"},verifyEmail:{title:"이메일 인증",subtitle:"발송된 인증 이메일에서 계정 설정을 완료해 주세요",sentToLabel:"발송 대상",resendButton:"인증 이메일 재발송",resendCountdown:"{seconds}초 후 재발송 가능",changeEmailButton:"다른 이메일 사용"},forgotPassword:{title:"비밀번호 재설정",subtitle:"이메일을 입력하시면 재설정 코드를 보내드립니다",emailLabel:"이메일",submitButton:"재설정 코드 발송"},resetPassword:{title:"새 비밀번호 설정",subtitle:"이메일로 받은 인증 코드를 사용하여 비밀번호를 재설정하세요",codeLabel:"인증 코드",newPasswordLabel:"새 비밀번호",confirmPasswordLabel:"비밀번호 확인",submitButton:"비밀번호 변경",resendCodeButton:"코드 재발송",resendCountdown:"{seconds}초 후 재발송 가능"},oauth:{redirecting:"{provider}(으)로 이동 중…",dividerText:"또는",continueWith:"으로 계속"},errors:{invalidEmail:"올바른 이메일 주소를 입력해 주세요",requiredField:"필수 입력 항목입니다",passwordTooShort:"비밀번호는 최소 {min}자 이상이어야 합니다",passwordMismatch:"비밀번호가 일치하지 않습니다",invalidCode:"6자리 인증 코드를 입력해 주세요",generic:"문제가 발생했습니다. 다시 시도해 주세요",invalidPhone:"유효한 중국 본토 휴대폰 번호를 입력하세요",smsRateLimited:"코드 요청이 너무 많습니다. 잠시 후 다시 시도하세요",smsSendFailed:"SMS를 보내지 못했습니다. 잠시 후 다시 시도하세요"}},W={common:{loading:"Cargando inicio de sesión…",redirecting:"Redirigiendo…",backToSignIn:"Volver a iniciar sesión"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Código de acceso enviado a tu correo",sendingCode:"Enviando código de acceso…",signingIn:"Iniciando sesión…",title:"Bienvenido de nuevo",subtitle:"Inicia sesión para continuar",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",submitButton:"Iniciar sesión",forgotPassword:"¿Olvidaste tu contraseña?",switchToSignUp:"Crear una cuenta",signUpPrompt:"¿No tienes cuenta?",phoneTab:"Teléfono",phoneLabel:"Número de teléfono",phonePlaceholder:"Móvil de 11 dígitos",phoneCodePlaceholder:"Código enviado por SMS. Usa el más reciente."},signUp:{title:"Crea tu cuenta",subtitle:"Empieza con tu nombre, correo y contraseña",nameLabel:"Nombre",emailLabel:"Correo electrónico",passwordLabel:"Contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Crear cuenta",switchToSignIn:"Iniciar sesión",signInPrompt:"¿Ya tienes una cuenta?"},verifyEmail:{title:"Verifica tu correo",subtitle:"Completa la configuración desde el correo de verificación que te enviamos.",sentToLabel:"Enviado a",resendButton:"Reenviar correo de verificación",resendCountdown:"Reenviar en {seconds}s",changeEmailButton:"Usar otro correo"},forgotPassword:{title:"Restablecer contraseña",subtitle:"Ingresa tu correo y te enviaremos un código de restablecimiento.",emailLabel:"Correo electrónico",submitButton:"Enviar código"},resetPassword:{title:"Establece una nueva contraseña",subtitle:"Usa el código de tu correo para completar el restablecimiento.",codeLabel:"Código de verificación",newPasswordLabel:"Nueva contraseña",confirmPasswordLabel:"Confirmar contraseña",submitButton:"Actualizar contraseña",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar en {seconds}s"},oauth:{redirecting:"Redirigiendo a {provider}…",dividerText:"o",continueWith:"Continuar con"},errors:{invalidEmail:"Ingresa una dirección de correo válida.",requiredField:"Este campo es obligatorio.",passwordTooShort:"La contraseña debe tener al menos {min} caracteres.",passwordMismatch:"Las contraseñas no coinciden.",invalidCode:"Ingresa el código de verificación de 6 dígitos.",generic:"Algo salió mal. Por favor, inténtalo de nuevo.",invalidPhone:"Introduce un número móvil válido de China continental",smsRateLimited:"Demasiadas solicitudes de código. Inténtalo más tarde.",smsSendFailed:"No se pudo enviar el SMS. Inténtalo más tarde."}},he={common:{loading:"Carregando login…",redirecting:"Redirecionando…",backToSignIn:"Voltar para o login"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Código de acesso enviado por e-mail",sendingCode:"Enviando código de acesso…",signingIn:"Entrando…",title:"Bem-vindo de volta",subtitle:"Faça login para continuar",emailLabel:"E-mail",passwordLabel:"Senha",submitButton:"Entrar",forgotPassword:"Esqueceu a senha?",switchToSignUp:"Criar uma conta",signUpPrompt:"Não tem uma conta?",phoneTab:"Telefone",phoneLabel:"Número de telefone",phonePlaceholder:"Celular de 11 dígitos",phoneCodePlaceholder:"Código enviado por SMS. Use o mais recente."},signUp:{title:"Crie sua conta",subtitle:"Comece com seu nome, e-mail e senha",nameLabel:"Nome",emailLabel:"E-mail",passwordLabel:"Senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Criar conta",switchToSignIn:"Entrar",signInPrompt:"Já tem uma conta?"},verifyEmail:{title:"Verifique seu e-mail",subtitle:"Conclua a configuração a partir do e-mail de verificação que enviamos.",sentToLabel:"Enviado para",resendButton:"Reenviar e-mail de verificação",resendCountdown:"Reenviar em {seconds}s",changeEmailButton:"Usar outro e-mail"},forgotPassword:{title:"Redefinir senha",subtitle:"Informe seu e-mail e enviaremos um código de redefinição.",emailLabel:"E-mail",submitButton:"Enviar código"},resetPassword:{title:"Defina uma nova senha",subtitle:"Use o código recebido por e-mail para concluir a redefinição.",codeLabel:"Código de verificação",newPasswordLabel:"Nova senha",confirmPasswordLabel:"Confirmar senha",submitButton:"Atualizar senha",resendCodeButton:"Reenviar código",resendCountdown:"Reenviar em {seconds}s"},oauth:{redirecting:"Redirecionando para {provider}…",dividerText:"ou",continueWith:"Continuar com"},errors:{invalidEmail:"Insira um endereço de e-mail válido.",requiredField:"Este campo é obrigatório.",passwordTooShort:"A senha deve ter pelo menos {min} caracteres.",passwordMismatch:"As senhas não coincidem.",invalidCode:"Insira o código de verificação de 6 dígitos.",generic:"Algo deu errado. Por favor, tente novamente.",invalidPhone:"Digite um número de celular válido da China continental",smsRateLimited:"Muitas solicitações de código. Tente novamente mais tarde.",smsSendFailed:"Não foi possível enviar o SMS. Tente novamente mais tarde."}},me={common:{loading:"Chargement de la connexion…",redirecting:"Redirection…",backToSignIn:"Retour à la connexion"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Code de connexion envoyé par e-mail",sendingCode:"Envoi du code de connexion…",signingIn:"Connexion en cours…",title:"Bon retour",subtitle:"Connectez-vous pour continuer",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",submitButton:"Se connecter",forgotPassword:"Mot de passe oublié ?",switchToSignUp:"Créer un compte",signUpPrompt:"Vous n’avez pas de compte ?",phoneTab:"Téléphone",phoneLabel:"Numéro de téléphone",phonePlaceholder:"Numéro mobile à 11 chiffres",phoneCodePlaceholder:"Code envoyé par SMS. Utilisez le plus récent."},signUp:{title:"Créez votre compte",subtitle:"Commencez par votre nom, e-mail et mot de passe",nameLabel:"Nom",emailLabel:"Adresse e-mail",passwordLabel:"Mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Créer le compte",switchToSignIn:"Se connecter",signInPrompt:"Vous avez déjà un compte ?"},verifyEmail:{title:"Vérifiez votre e-mail",subtitle:"Finalisez la création de votre compte depuis l’e-mail de vérification envoyé.",sentToLabel:"Envoyé à",resendButton:"Renvoyer l’e-mail de vérification",resendCountdown:"Renvoyer dans {seconds}s",changeEmailButton:"Utiliser un autre e-mail"},forgotPassword:{title:"Réinitialiser le mot de passe",subtitle:"Saisissez votre e-mail pour recevoir un code de réinitialisation.",emailLabel:"Adresse e-mail",submitButton:"Envoyer le code"},resetPassword:{title:"Définir un nouveau mot de passe",subtitle:"Utilisez le code reçu par e-mail pour réinitialiser votre mot de passe.",codeLabel:"Code de vérification",newPasswordLabel:"Nouveau mot de passe",confirmPasswordLabel:"Confirmer le mot de passe",submitButton:"Mettre à jour le mot de passe",resendCodeButton:"Renvoyer le code",resendCountdown:"Renvoyer dans {seconds}s"},oauth:{redirecting:"Redirection vers {provider}…",dividerText:"ou",continueWith:"Continuer avec"},errors:{invalidEmail:"Veuillez saisir une adresse e-mail valide.",requiredField:"Ce champ est requis.",passwordTooShort:"Le mot de passe doit contenir au moins {min} caractères.",passwordMismatch:"Les mots de passe ne correspondent pas.",invalidCode:"Saisissez le code de vérification à 6 chiffres.",generic:"Une erreur est survenue. Veuillez réessayer.",invalidPhone:"Saisissez un numéro de mobile valide de Chine continentale",smsRateLimited:"Trop de demandes de code. Réessayez plus tard.",smsSendFailed:"Impossible d’envoyer le SMS. Réessayez plus tard."}},pe={common:{loading:"Anmeldung wird geladen…",redirecting:"Weiterleitung…",backToSignIn:"Zurück zur Anmeldung"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Anmeldecode wurde per E-Mail gesendet",sendingCode:"Anmeldecode wird gesendet…",signingIn:"Anmeldung läuft…",title:"Willkommen zurück",subtitle:"Melden Sie sich an, um fortzufahren",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",submitButton:"Anmelden",forgotPassword:"Passwort vergessen?",switchToSignUp:"Konto erstellen",signUpPrompt:"Noch kein Konto?",phoneTab:"Telefon",phoneLabel:"Telefonnummer",phonePlaceholder:"11-stellige Mobilnummer",phoneCodePlaceholder:"Code per SMS gesendet. Verwende den neuesten."},signUp:{title:"Konto erstellen",subtitle:"Geben Sie Ihren Namen, Ihre E-Mail und ein Passwort ein",nameLabel:"Name",emailLabel:"E-Mail-Adresse",passwordLabel:"Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Konto erstellen",switchToSignIn:"Anmelden",signInPrompt:"Bereits ein Konto?"},verifyEmail:{title:"E-Mail bestätigen",subtitle:"Schließen Sie die Einrichtung über die Bestätigungs-E-Mail ab, die wir Ihnen gesendet haben.",sentToLabel:"Gesendet an",resendButton:"Bestätigungs-E-Mail erneut senden",resendCountdown:"Erneut senden in {seconds}s",changeEmailButton:"Andere E-Mail verwenden"},forgotPassword:{title:"Passwort zurücksetzen",subtitle:"Geben Sie Ihre E-Mail ein und wir senden Ihnen einen Zurücksetzungscode.",emailLabel:"E-Mail-Adresse",submitButton:"Code senden"},resetPassword:{title:"Neues Passwort festlegen",subtitle:"Verwenden Sie den Code aus der E-Mail, um Ihr Passwort zurückzusetzen.",codeLabel:"Bestätigungscode",newPasswordLabel:"Neues Passwort",confirmPasswordLabel:"Passwort bestätigen",submitButton:"Passwort aktualisieren",resendCodeButton:"Code erneut senden",resendCountdown:"Erneut senden in {seconds}s"},oauth:{redirecting:"Weiterleitung zu {provider}…",dividerText:"oder",continueWith:"Weiter mit"},errors:{invalidEmail:"Bitte geben Sie eine gültige E-Mail-Adresse ein.",requiredField:"Dieses Feld ist erforderlich.",passwordTooShort:"Das Passwort muss mindestens {min} Zeichen lang sein.",passwordMismatch:"Die Passwörter stimmen nicht überein.",invalidCode:"Geben Sie den 6-stelligen Bestätigungscode ein.",generic:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",invalidPhone:"Gib eine gültige Mobilnummer aus Festlandchina ein",smsRateLimited:"Zu viele Code-Anfragen. Bitte versuche es später erneut.",smsSendFailed:"SMS konnte nicht gesendet werden. Bitte versuche es später erneut."}},ge={common:{loading:"Caricamento accesso…",redirecting:"Reindirizzamento…",backToSignIn:"Torna all’accesso"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Codice di accesso inviato alla tua e-mail",sendingCode:"Invio del codice di accesso…",signingIn:"Accesso in corso…",title:"Bentornato",subtitle:"Accedi per continuare",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",submitButton:"Accedi",forgotPassword:"Password dimenticata?",switchToSignUp:"Crea un account",signUpPrompt:"Non hai un account?",phoneTab:"Telefono",phoneLabel:"Numero di telefono",phonePlaceholder:"Cellulare di 11 cifre",phoneCodePlaceholder:"Codice inviato via SMS. Usa il più recente."},signUp:{title:"Crea il tuo account",subtitle:"Inserisci nome, e-mail e password per iniziare",nameLabel:"Nome",emailLabel:"Indirizzo e-mail",passwordLabel:"Password",confirmPasswordLabel:"Conferma password",submitButton:"Crea account",switchToSignIn:"Accedi",signInPrompt:"Hai già un account?"},verifyEmail:{title:"Verifica la tua e-mail",subtitle:"Completa la configurazione dall’e-mail di verifica che ti abbiamo inviato.",sentToLabel:"Inviata a",resendButton:"Reinvia e-mail di verifica",resendCountdown:"Reinvia tra {seconds}s",changeEmailButton:"Usa un’altra e-mail"},forgotPassword:{title:"Reimposta la password",subtitle:"Inserisci la tua e-mail e ti invieremo un codice di reimpostazione.",emailLabel:"Indirizzo e-mail",submitButton:"Invia codice"},resetPassword:{title:"Imposta una nuova password",subtitle:"Usa il codice ricevuto via e-mail per reimpostare la password.",codeLabel:"Codice di verifica",newPasswordLabel:"Nuova password",confirmPasswordLabel:"Conferma password",submitButton:"Aggiorna password",resendCodeButton:"Reinvia codice",resendCountdown:"Reinvia tra {seconds}s"},oauth:{redirecting:"Reindirizzamento a {provider}…",dividerText:"oppure",continueWith:"Continua con"},errors:{invalidEmail:"Inserisci un indirizzo e-mail valido.",requiredField:"Questo campo è obbligatorio.",passwordTooShort:"La password deve contenere almeno {min} caratteri.",passwordMismatch:"Le password non corrispondono.",invalidCode:"Inserisci il codice di verifica a 6 cifre.",generic:"Qualcosa è andato storto. Riprova.",invalidPhone:"Inserisci un numero di cellulare valido della Cina continentale",smsRateLimited:"Troppe richieste di codice. Riprova più tardi.",smsSendFailed:"Impossibile inviare l’SMS. Riprova più tardi."}},fe={common:{loading:"Загрузка входа…",redirecting:"Перенаправление…",backToSignIn:"Вернуться ко входу"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"Код входа отправлен на вашу почту",sendingCode:"Отправка кода входа…",signingIn:"Вход…",title:"С возвращением",subtitle:"Войдите, чтобы продолжить",emailLabel:"Электронная почта",passwordLabel:"Пароль",submitButton:"Войти",forgotPassword:"Забыли пароль?",switchToSignUp:"Создать аккаунт",signUpPrompt:"Нет аккаунта?",phoneTab:"Телефон",phoneLabel:"Номер телефона",phonePlaceholder:"11-значный номер мобильного",phoneCodePlaceholder:"Код отправлен по SMS. Используйте последний."},signUp:{title:"Создание аккаунта",subtitle:"Укажите имя, электронную почту и пароль",nameLabel:"Имя",emailLabel:"Электронная почта",passwordLabel:"Пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Создать аккаунт",switchToSignIn:"Войти",signInPrompt:"Уже есть аккаунт?"},verifyEmail:{title:"Подтвердите почту",subtitle:"Завершите настройку через письмо с подтверждением, которое мы отправили.",sentToLabel:"Отправлено на",resendButton:"Отправить повторно",resendCountdown:"Повторная отправка через {seconds}с",changeEmailButton:"Использовать другую почту"},forgotPassword:{title:"Сброс пароля",subtitle:"Введите электронную почту, и мы отправим код для сброса.",emailLabel:"Электронная почта",submitButton:"Отправить код"},resetPassword:{title:"Установите новый пароль",subtitle:"Используйте код из письма для завершения сброса пароля.",codeLabel:"Код подтверждения",newPasswordLabel:"Новый пароль",confirmPasswordLabel:"Подтвердите пароль",submitButton:"Обновить пароль",resendCodeButton:"Отправить код повторно",resendCountdown:"Повторная отправка через {seconds}с"},oauth:{redirecting:"Переход в {provider}…",dividerText:"или",continueWith:"Продолжить через"},errors:{invalidEmail:"Введите корректный адрес электронной почты.",requiredField:"Это поле обязательно.",passwordTooShort:"Пароль должен содержать не менее {min} символов.",passwordMismatch:"Пароли не совпадают.",invalidCode:"Введите 6-значный код подтверждения.",generic:"Произошла ошибка. Пожалуйста, попробуйте снова.",invalidPhone:"Введите действительный номер мобильного телефона материкового Китая",smsRateLimited:"Слишком много запросов кода. Повторите попытку позже.",smsSendFailed:"Не удалось отправить SMS. Повторите попытку позже."}},be={common:{loading:"جارٍ تحميل تسجيل الدخول…",redirecting:"جارٍ إعادة التوجيه…",backToSignIn:"العودة إلى تسجيل الدخول"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"تم إرسال رمز تسجيل الدخول إلى بريدك الإلكتروني",sendingCode:"جارٍ إرسال رمز تسجيل الدخول…",signingIn:"جارٍ تسجيل الدخول…",title:"مرحبًا بعودتك",subtitle:"سجّل الدخول للمتابعة",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",submitButton:"تسجيل الدخول",forgotPassword:"هل نسيت كلمة المرور؟",switchToSignUp:"إنشاء حساب",signUpPrompt:"ليس لديك حساب؟",phoneTab:"الهاتف",phoneLabel:"رقم الهاتف",phonePlaceholder:"رقم جوال من 11 رقمًا",phoneCodePlaceholder:"تم إرسال الرمز عبر رسالة نصية. استخدم أحدث رمز."},signUp:{title:"أنشئ حسابك",subtitle:"ابدأ بإدخال اسمك وبريدك الإلكتروني وكلمة المرور",nameLabel:"الاسم",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"إنشاء الحساب",switchToSignIn:"تسجيل الدخول",signInPrompt:"لديك حساب بالفعل؟"},verifyEmail:{title:"تحقّق من بريدك الإلكتروني",subtitle:"أكمل إعداد حسابك من رسالة التحقّق التي أرسلناها.",sentToLabel:"أُرسل إلى",resendButton:"إعادة إرسال رسالة التحقّق",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية",changeEmailButton:"استخدام بريد إلكتروني آخر"},forgotPassword:{title:"إعادة تعيين كلمة المرور",subtitle:"أدخل بريدك الإلكتروني وسنرسل لك رمز إعادة التعيين.",emailLabel:"البريد الإلكتروني",submitButton:"إرسال رمز إعادة التعيين"},resetPassword:{title:"تعيين كلمة مرور جديدة",subtitle:"استخدم الرمز المرسل إلى بريدك لإكمال إعادة تعيين كلمة المرور.",codeLabel:"رمز التحقّق",newPasswordLabel:"كلمة المرور الجديدة",confirmPasswordLabel:"تأكيد كلمة المرور",submitButton:"تحديث كلمة المرور",resendCodeButton:"إعادة إرسال الرمز",resendCountdown:"إعادة الإرسال خلال {seconds} ثانية"},oauth:{redirecting:"جارٍ الانتقال إلى {provider}…",dividerText:"أو",continueWith:"المتابعة باستخدام"},errors:{invalidEmail:"يرجى إدخال عنوان بريد إلكتروني صالح.",requiredField:"هذا الحقل مطلوب.",passwordTooShort:"يجب أن تتكوّن كلمة المرور من {min} حرفًا على الأقل.",passwordMismatch:"كلمتا المرور غير متطابقتين.",invalidCode:"يرجى إدخال رمز التحقّق المكوّن من 6 أرقام.",generic:"حدث خطأ. يرجى المحاولة مرة أخرى.",invalidPhone:"أدخل رقم جوال صالحًا في البر الرئيسي للصين",smsRateLimited:"طلبات رموز كثيرة جدًا. حاول مرة أخرى لاحقًا.",smsSendFailed:"تعذّر إرسال الرسالة النصية. حاول مرة أخرى لاحقًا."}},we={common:{loading:"सधाइन की जुलातीअ लोड हो रही है…",redirecting:"रीडायरेक्ट हो रहا है…",backToSignIn:"साइन इन पर वापस जाएँ"},signIn:{emailPlaceholder:"you@mail.com",codePlaceholder:"साइन-इन कोड आपके ईमेल पर भेज दिया गया है",sendingCode:"साइन-इन कोड भेजा जा रहा है…",signingIn:"साइन इन हो रहा है…",title:"वापसी आपका स्वागत है",subtitle:"जारी रखने के लिए साइन इन करें",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",submitButton:"साइन इन",forgotPassword:"पासवर्ड भूल गए?",switchToSignUp:"खाता बनाएँ",signUpPrompt:"खाता नहीं है?",phoneTab:"फ़ोन",phoneLabel:"फ़ोन नंबर",phonePlaceholder:"11 अंकों का मोबाइल नंबर",phoneCodePlaceholder:"कोड SMS से भेजा गया। सबसे नया कोड इस्तेमाल करें।"},signUp:{title:"अपना खाता बनाएँ",subtitle:"अपना नाम, ईमेल और पासवर्ड दर्ज करें",nameLabel:"नाम",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"खाता बनाएँ",switchToSignIn:"साइन इन",signInPrompt:"पहले से खाता है?"},verifyEmail:{title:"अपना ईमेल सत्यापित करें",subtitle:"हमने जो सत्यापन ईमेल भेजा है उससे सेटअप पूरा करें।",sentToLabel:"भेजा गया",resendButton:"सत्यापन ईमेल फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें",changeEmailButton:"दूसरा ईमेल इस्तेमाल करें"},forgotPassword:{title:"पासवर्ड रीसेट करें",subtitle:"अपना ईमेल दर्ज करें और हम रीसेट कोड भेजेंगे।",emailLabel:"ईमेल",submitButton:"रीसेट कोड भेजें"},resetPassword:{title:"नया पासवर्ड सेट करें",subtitle:"पासवर्ड रीसेट पूरा करने के लिए ईमेल में प्राप्त कोड का उपयोग करें।",codeLabel:"सत्यापन कोड",newPasswordLabel:"नया पासवर्ड",confirmPasswordLabel:"पासवर्ड की पुष्टि",submitButton:"पासवर्ड अपडेट करें",resendCodeButton:"कोड फिर से भेजें",resendCountdown:"{seconds} सेकंड में फिर से भेजें"},oauth:{redirecting:"{provider} पर भेजा जा रहा है…",dividerText:"या",continueWith:"से जारी रखें"},errors:{invalidEmail:"कृपया एक वैध ईमेल पता दर्ज करें।",requiredField:"यह फ़ील्ड आवश्यक है।",passwordTooShort:"पासवर्ड कम से कम {min} अक्षरों का होना चाहिए।",passwordMismatch:"पासवर्ड मेल नहीं खाते।",invalidCode:"कृपया 6 अंकों का सत्यापन कोड दर्ज करें।",generic:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।",invalidPhone:"मुख्य भूमि चीन का मान्य मोबाइल नंबर दर्ज करें",smsRateLimited:"बहुत अधिक कोड अनुरोध। कृपया बाद में पुनः प्रयास करें।",smsSendFailed:"SMS नहीं भेजा जा सका। कृपया बाद में पुनः प्रयास करें।"}},Te={en:F,"en-US":F,zh:K,"zh-CN":K,"zh-TW":K,ja:ce,"ja-JP":ce,ko:ue,"ko-KR":ue,es:W,"es-ES":W,"es-MX":W,pt:he,"pt-BR":he,fr:me,"fr-FR":me,de:pe,"de-DE":pe,it:ge,"it-IT":ge,ru:fe,"ru-RU":fe,ar:be,"ar-SA":be,hi:we,"hi-IN":we};function xe(){if(typeof navigator>"u")return F;const t=navigator.languages??[navigator.language];for(const e of t){const i=Te[e]??Te[e.split("-")[0]];if(i)return i}return F}const Se={LIGHT:"light",DARK:"dark"},Pe=Se.LIGHT,Ge=Se.DARK,Ee=[Pe,Ge],je=Pe,qe={BACKGROUND:"--edgespark-auth-bg",BACKGROUND_MUTED:"--edgespark-auth-bg-muted",CARD_BACKGROUND:"--edgespark-auth-card-bg",BORDER:"--edgespark-auth-border",TEXT:"--edgespark-auth-text",TEXT_MUTED:"--edgespark-auth-text-muted",DIVIDER_BACKGROUND:"--edgespark-auth-divider-bg",PRIMARY:"--edgespark-auth-primary",PRIMARY_HOVER:"--edgespark-auth-primary-hover",PRIMARY_CONTRAST:"--edgespark-auth-primary-contrast",ERROR:"--edgespark-auth-error",INFO:"--edgespark-auth-info",CARD_RADIUS:"--edgespark-auth-radius-card",CONTROL_RADIUS:"--edgespark-auth-radius-control",SHADOW:"--edgespark-auth-shadow",FONT:"--edgespark-auth-font",MODAL_BACKDROP:"--edgespark-auth-modal-backdrop",MODAL_CARD_BACKGROUND:"--edgespark-auth-modal-card-bg",MODAL_SHADOW:"--edgespark-auth-modal-shadow"},Ke=Object.values(qe);function Tt(t){return typeof t=="string"&&Ee.includes(t)}function Rt(t){return Ke.includes(t)}function $t(t){var e;return{theme:(t==null?void 0:t.theme)??je,className:((e=t==null?void 0:t.className)==null?void 0:e.trim())??"",variables:{...(t==null?void 0:t.variables)??{}}}}function H(t,e="Authentication failed."){return ye(t,e)}async function V(t){var i,s;const e=await t.getSession();if(e.error)throw new E(e.error.message||"Failed to load the current session.",{code:e.error.code??"SESSION_LOOKUP_FAILED",status:e.error.status,cause:e.error});return(i=e.data)!=null&&i.user&&((s=e.data)!=null&&s.session)?{user:e.data.user,session:e.data}:{user:null,session:null}}let Ut=0;const kt="data-edgespark-auth",Ot="data-edgespark-auth-theme",o="edgespark-auth",ie="es_auth_completion",z="es_auth_email",se="oauth",N="verify-sign-in",$="verify-sign-up",Re=200,ne=2,$e="+86",Mt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ue={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function U(t){return"redirectTo"in t}function oe(t){return"onSuccess"in t&&!("redirectTo"in t)}function x(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function re(t){return/^\d{6}$/.test(t.trim())}function We(t){return t.replace(/[\s-]/g,"")}function Bt(t){return/^1[3-9]\d{9}$/.test(We(t))}function Dt(t){return t==="email"||t==="phone"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}function Nt(t){return!!(t.error||t.errorDescription)}class Vt{constructor(e,i,s,n,r){this.container=e,this.auth=i,this.options=s,this.loadConfig=n,this.runtimeOptions=r,this.fieldIdPrefix=`edgespark-auth-${++Ut}`,this.state={view:"loading",busy:!0,busyLabel:void 0,error:null,notice:null,email:"",phone:"",name:"",password:"",confirmPassword:"",code:"",newPassword:"",signInMethod:"password",signInOtpSent:!1},this.destroyed=!1,this.terminalActionInProgress=!1,this.config=null,this.countdownUntil=null,this.countdownTimer=null,this.pendingFocusSnapshot=null,this.focusRestoreTimer=null,this.verificationCompletionAction=null;const l=$t(s.appearance);this.labels=Ct(xe(),s.labels),this.root=document.createElement("div"),this.root.className=l.className?`${o} ${l.className}`:o,this.root.setAttribute(kt,""),this.root.setAttribute(Ot,l.theme);for(const[h,p]of Object.entries(l.variables))p!==void 0&&this.root.style.setProperty(h,p);e.appendChild(this.root),this.render(),this.initialize()}destroy(){this.destroyed||(this.destroyed=!0,this.clearCountdown(),this.clearFocusRestoreTimer(),this.root.remove())}async initialize(){const e=this.consumeManagedReturnContext();try{const[i,s]=await Promise.allSettled([this.loadConfig(),this.readMountSession(e)]);if(this.destroyed)return;if(s.status==="rejected"){if(e.marker&&!Nt(e)&&U(this.options)){this.redirectAfterManagedReturnLookupFailure();return}}else{const r=s.value;if(r.user&&r.session){switch(e.marker){case se:case N:await this.completeAuth("sign-in",r);return;case $:await this.completeAuth("sign-up",r);return;default:break}this.handleExistingSessionOnMount();return}}if(i.status==="rejected")throw s.status==="rejected"?s.reason:i.reason;if(this.config=i.value,this.state.signInMethod=this.resolveInitialSignInMethod(),this.handleSessionlessManagedReturn(e))return;if(s.status==="rejected")throw s.reason;const n=s.value;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(i){this.handleError(i,"Failed to load the authentication UI.")}}redirectAfterManagedReturnLookupFailure(){U(this.options)&&this.navigateToRedirect()}navigateToRedirect(){U(this.options)&&(this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(At(this.options.redirectTo).toString()))}async readMountSession(e){if(!e.marker)return V(this.auth);let i=null;for(let s=0;s<=ne;s++){try{const n=await V(this.auth);if(n.user&&n.session)return n}catch(n){i=n}s<ne&&await new Promise(n=>setTimeout(n,Re))}if(i)throw i;return{user:null,session:null}}render(){if(this.destroyed)return;const e=this.captureFocusSnapshot();if(e&&(this.pendingFocusSnapshot=e),this.root.dataset.authAction=this.state.busy?this.state.busyAction??"loading":"idle",!this.config){this.root.innerHTML=this.renderLoading();return}this.root.innerHTML=`
2
+ <div class="${o}__shell">
3
+ ${this.renderDevModeBanner()}
4
+ <div class="${o}__card">
5
+ ${this.renderStatus()}
6
+ ${this.renderCurrentView()}
7
+ </div>
8
+ </div>
9
+ `,this.bindDOM(),this.scheduleFocusRestore()}renderLoading(){return`
10
+ <div class="${o}__shell">
11
+ <div class="${o}__card" aria-busy="${!this.state.error}">
12
+ ${this.renderStatus()}
13
+ ${this.state.error?"":`
14
+ <p class="${o}__sr-only" role="status">${this.escape(this.labels.common.loading)}</p>
15
+ <div class="${o}__section ${o}__skeleton" aria-hidden="true">
16
+ <div class="${o}__skeleton-label"></div>
17
+ <div class="${o}__skeleton-input"></div>
18
+ <div class="${o}__skeleton-button"></div>
19
+ <div class="${o}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>
20
+ <div class="${o}__skeleton-button ${o}__skeleton-button--secondary"></div>
21
+ </div>
22
+ `}
23
+ </div>
24
+ </div>
25
+ `}renderDevModeBanner(){var e;return(e=this.config)!=null&&e.isLocalDev?`<div class="${o}__dev-banner">Local dev mode — emails are mocked, OAuth uses test identities</div>`:""}renderStatus(){var i;const e=[];return this.state.error&&e.push(`<div role="alert" class="${o}__status ${o}__status--error">${this.escape(this.state.error)}</div>`),this.state.notice&&e.push(`<div role="status" class="${this.state.view==="sign-in"&&this.state.signInOtpSent&&!((i=this.config)!=null&&i.isLocalDev)?`${o}__sr-only`:`${o}__status ${o}__status--info`}">${this.escape(this.state.notice)}</div>`),this.state.busy&&this.state.busyLabel&&!this.state.busyAction&&e.push(`<div class="${o}__status ${o}__status--muted">${this.escape(this.state.busyLabel)}</div>`),e.join("")}renderCurrentView(){switch(this.state.view){case"sign-in":return this.renderSignInView();case"sign-up":return this.renderSignUpView();case"verify-email":return this.renderVerifyEmailView();case"forgot-password":return this.renderForgotPasswordView();case"reset-password":return this.renderResetPasswordView();case"loading":default:return`<p class="${o}__copy">${this.escape(this.labels.common.loading)}</p>`}}renderSignInView(){var w,b;const e=this.renderOAuthProviders(),i=this.availableSignInMethods(),s=i.length>0,n=this.activeSignInMethod(),r=n==="password",l=n==="phone",h=r?this.labels.signIn.submitButton:this.state.signInOtpSent?this.labels.signIn.verifyCodeButton??"Verify code":this.labels.signIn.sendCodeButton??"Send code",p=this.countdownText(this.labels.signIn.resendCodeButton??"Resend code",this.labels.signIn.resendCountdown??"Resend in {seconds}s"),I=l?this.labels.signIn.phoneCodePlaceholder??"Code sent by SMS. Use the most recent one.":this.labels.signIn.codePlaceholder;return`
26
+ <section class="${o}__section">
27
+ <header class="${o}__header">
28
+ <h1 class="${o}__title">${this.escape(this.labels.signIn.title)}</h1>
29
+ <p class="${o}__copy">${this.escape(this.labels.signIn.subtitle)}</p>
30
+ </header>
31
+ ${e}
32
+ ${e&&s?`<div class="${o}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
33
+ ${s?`
34
+ ${i.length>1?`
35
+ <div class="${o}__tabs" role="tablist" aria-label="Sign-in method">
36
+ ${i.map(P=>this.renderSignInMethodTab(P,n)).join("")}
37
+ </div>
38
+ `:""}
39
+ <form class="${o}__form" data-view="sign-in" novalidate>
40
+ ${l?this.renderPhoneInput():this.renderInput("email",this.labels.signIn.emailLabel,"email",this.state.email,"email",this.labels.signIn.emailPlaceholder)}
41
+ ${r?this.renderInput("password",this.labels.signIn.passwordLabel,"password",this.state.password,"current-password"):this.state.signInOtpSent?this.renderInput("code",this.labels.signIn.codeLabel??"Code","text",this.state.code,"one-time-code",I,`
42
+ <button class="${o}__text-action" type="button" data-action="resend-sign-in-code" aria-busy="${this.state.busy&&this.state.busyAction==="resend-code"}" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
43
+ ${this.escape(this.state.busy&&this.state.busyAction==="resend-code"?this.state.busyLabel??p:p)}
44
+ </button>
45
+ `):""}
46
+ <button class="${o}__button ${o}__button--primary" type="submit" aria-busy="${this.state.busy&&(this.state.busyAction==="sign-in"||this.state.busyAction==="send-code")}" ${this.state.busy?"disabled":""}>
47
+ ${this.escape(this.state.busy&&(this.state.busyAction==="sign-in"||this.state.busyAction==="send-code")?this.state.busyLabel??h:h)}
48
+ </button>
49
+ </form>
50
+ <div class="${o}__actions">
51
+ ${r&&this.canUsePasswordResetEmailOtp()?`
52
+ <button class="${o}__link" type="button" data-action="forgot-password" ${this.state.busy?"disabled":""}>
53
+ ${this.escape(this.labels.signIn.forgotPassword)}
54
+ </button>
55
+ `:""}
56
+ ${!((w=this.config)!=null&&w.disableSignUp)&&((b=this.config)!=null&&b.emailPasswordEnabled)?`
57
+ <p class="${o}__meta">
58
+ ${this.escape(this.labels.signIn.signUpPrompt)}
59
+ <button class="${o}__link" type="button" data-action="switch-sign-up" ${this.state.busy?"disabled":""}>
60
+ ${this.escape(this.labels.signIn.switchToSignUp)}
61
+ </button>
62
+ </p>
63
+ `:""}
64
+ </div>
65
+ `:""}
66
+ </section>
67
+ `}renderSignInMethodTab(e,i){let s;return e==="password"?s=this.labels.signIn.passwordTab??"Password":e==="phone"?s=this.labels.signIn.phoneTab??"Phone":s=this.availableSignInMethods().includes("phone")?this.labels.signIn.emailLabel:this.labels.signIn.codeTab??"Code",`
68
+ <button class="${o}__tab ${e===i?`${o}__tab--active`:""}" type="button" data-action="sign-in-method" data-method="${e}" ${this.state.busy?"disabled":""}>
69
+ ${this.escape(s)}
70
+ </button>
71
+ `}renderPhoneInput(){const e=`${this.fieldIdPrefix}-phone`;return`
72
+ <div class="${o}__field">
73
+ <div class="${o}__field-heading">
74
+ <label class="${o}__label" for="${e}">${this.escape(this.labels.signIn.phoneLabel??"Phone number")}</label>
75
+ </div>
76
+ <div class="${o}__input-group">
77
+ <span class="${o}__input-prefix" aria-hidden="true">${$e}</span>
78
+ <input
79
+ id="${e}"
80
+ placeholder="${this.escape(this.labels.signIn.phonePlaceholder??"11-digit mobile number")}"
81
+ class="${o}__input"
82
+ name="phone"
83
+ type="tel"
84
+ inputmode="numeric"
85
+ maxlength="13"
86
+ value="${this.escape(this.state.phone)}"
87
+ autocomplete="tel-national"
88
+ ${this.state.busy?"disabled":""}
89
+ />
90
+ </div>
91
+ </div>
92
+ `}renderSignUpView(){const e=this.renderOAuthProviders();return`
93
+ <section class="${o}__section">
94
+ <header class="${o}__header">
95
+ <h1 class="${o}__title">${this.escape(this.labels.signUp.title)}</h1>
96
+ <p class="${o}__copy">${this.escape(this.labels.signUp.subtitle)}</p>
97
+ </header>
98
+ ${e}
99
+ ${e?`<div class="${o}__divider"><span>${this.escape(this.labels.oauth.dividerText)}</span></div>`:""}
100
+ <form class="${o}__form" data-view="sign-up" novalidate>
101
+ ${this.renderInput("name",this.labels.signUp.nameLabel,"text",this.state.name,"name")}
102
+ ${this.renderInput("email",this.labels.signUp.emailLabel,"email",this.state.email,"email")}
103
+ ${this.renderInput("password",this.labels.signUp.passwordLabel,"password",this.state.password,"new-password")}
104
+ ${this.renderInput("confirmPassword",this.labels.signUp.confirmPasswordLabel,"password",this.state.confirmPassword,"new-password")}
105
+ <button class="${o}__button ${o}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
106
+ ${this.escape(this.labels.signUp.submitButton)}
107
+ </button>
108
+ </form>
109
+ <p class="${o}__meta">
110
+ ${this.escape(this.labels.signUp.signInPrompt)}
111
+ <button class="${o}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
112
+ ${this.escape(this.labels.signUp.switchToSignIn)}
113
+ </button>
114
+ </p>
115
+ </section>
116
+ `}renderVerifyEmailView(){const e=this.countdownText(this.labels.verifyEmail.resendButton,this.labels.verifyEmail.resendCountdown);return`
117
+ <section class="${o}__section">
118
+ <header class="${o}__header">
119
+ <h1 class="${o}__title">${this.escape(this.labels.verifyEmail.title)}</h1>
120
+ <p class="${o}__copy">${this.escape(this.labels.verifyEmail.subtitle)}</p>
121
+ </header>
122
+ <p class="${o}__copy">
123
+ <strong>${this.escape(this.labels.verifyEmail.sentToLabel)}:</strong>
124
+ ${this.escape(this.state.email)}
125
+ </p>
126
+ <div class="${o}__stack">
127
+ <button class="${o}__button ${o}__button--secondary" type="button" data-action="resend-verification" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
128
+ ${this.escape(e)}
129
+ </button>
130
+ <button class="${o}__link" type="button" data-action="use-different-email" ${this.state.busy?"disabled":""}>
131
+ ${this.escape(this.labels.verifyEmail.changeEmailButton)}
132
+ </button>
133
+ </div>
134
+ </section>
135
+ `}renderForgotPasswordView(){return`
136
+ <section class="${o}__section">
137
+ <header class="${o}__header">
138
+ <h1 class="${o}__title">${this.escape(this.labels.forgotPassword.title)}</h1>
139
+ <p class="${o}__copy">${this.escape(this.labels.forgotPassword.subtitle)}</p>
140
+ </header>
141
+ <form class="${o}__form" data-view="forgot-password" novalidate>
142
+ ${this.renderInput("email",this.labels.forgotPassword.emailLabel,"email",this.state.email,"email")}
143
+ <button class="${o}__button ${o}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
144
+ ${this.escape(this.labels.forgotPassword.submitButton)}
145
+ </button>
146
+ </form>
147
+ <button class="${o}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
148
+ ${this.escape(this.labels.common.backToSignIn)}
149
+ </button>
150
+ </section>
151
+ `}renderResetPasswordView(){const e=this.countdownText(this.labels.resetPassword.resendCodeButton,this.labels.resetPassword.resendCountdown);return`
152
+ <section class="${o}__section">
153
+ <header class="${o}__header">
154
+ <h1 class="${o}__title">${this.escape(this.labels.resetPassword.title)}</h1>
155
+ <p class="${o}__copy">${this.escape(this.labels.resetPassword.subtitle)}</p>
156
+ </header>
157
+ <form class="${o}__form" data-view="reset-password" novalidate>
158
+ ${this.renderInput("code",this.labels.resetPassword.codeLabel,"text",this.state.code,"one-time-code")}
159
+ ${this.renderInput("newPassword",this.labels.resetPassword.newPasswordLabel,"password",this.state.newPassword,"new-password")}
160
+ ${this.renderInput("confirmPassword",this.labels.resetPassword.confirmPasswordLabel,"password",this.state.confirmPassword,"new-password")}
161
+ <button class="${o}__button ${o}__button--primary" type="submit" ${this.state.busy?"disabled":""}>
162
+ ${this.escape(this.labels.resetPassword.submitButton)}
163
+ </button>
164
+ </form>
165
+ <button class="${o}__button ${o}__button--secondary" type="button" data-action="resend-reset-code" ${this.state.busy||this.isCountdownActive()?"disabled":""}>
166
+ ${this.escape(e)}
167
+ </button>
168
+ <button class="${o}__link" type="button" data-action="switch-sign-in" ${this.state.busy?"disabled":""}>
169
+ ${this.escape(this.labels.common.backToSignIn)}
170
+ </button>
171
+ </section>
172
+ `}renderOAuthProviders(){var i;const e=((i=this.config)==null?void 0:i.oauthProviders)??[];return e.length===0?"":`
173
+ <div class="${o}__stack">
174
+ ${e.map(s=>`
175
+ <button class="${o}__button ${o}__button--secondary" type="button" data-action="oauth" data-provider="${s}" aria-busy="${this.state.busy&&this.state.busyAction===`oauth:${s}`}" ${this.state.busy?"disabled":""}>
176
+ ${this.escape(this.state.busy&&this.state.busyAction===`oauth:${s}`?this.state.busyLabel??this.labels.common.redirecting:`${this.labels.oauth.continueWith} ${Ue[s]}`)}
177
+ </button>
178
+ `).join("")}
179
+ </div>
180
+ `}renderInput(e,i,s,n,r,l="",h=""){const p=`${this.fieldIdPrefix}-${e}`;return`
181
+ <div class="${o}__field">
182
+ <div class="${o}__field-heading">
183
+ <label class="${o}__label" for="${p}">${this.escape(i)}</label>
184
+ ${h}
185
+ </div>
186
+ <input
187
+ id="${p}"
188
+ placeholder="${this.escape(l)}"
189
+ class="${o}__input"
190
+ name="${this.escape(e)}"
191
+ type="${this.escape(s)}"
192
+ value="${this.escape(n)}"
193
+ autocomplete="${this.escape(r)}"
194
+ ${this.state.busy?"disabled":""}
195
+ />
196
+ </div>
197
+ `}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(n=>{n.addEventListener("submit",r=>{r.preventDefault();const l=n.dataset.view;l==="sign-in"&&this.handleSignIn(),l==="sign-up"&&this.handleSignUp(),l==="forgot-password"&&this.handleForgotPassword(),l==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(n=>{n.addEventListener("input",()=>{Dt(n.name)&&(this.state[n.name]=n.value,(n.name==="email"||n.name==="phone")&&this.state.signInOtpSent&&(this.state.signInOtpSent=!1,this.state.code="",this.clearCountdown(),this.state.notice=null,this.state.error=null,this.render()))})}),this.root.querySelectorAll("[data-action]").forEach(n=>{n.addEventListener("click",()=>{const r=n.dataset.action;if(r==="switch-sign-up"&&this.switchView("sign-up"),r==="switch-sign-in"&&this.switchView("sign-in"),r==="forgot-password"&&this.switchView("forgot-password"),r==="resend-verification"&&this.resendVerificationEmail(),r==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),r==="sign-in-method"){const l=n.dataset.method;this.setSignInMethod(l==="otp"||l==="phone"?l:"password")}r==="resend-sign-in-code"&&this.resendSignInCode(),r==="resend-reset-code"&&this.resendResetCode(),r==="oauth"&&this.handleOAuthSignIn(n.dataset.provider)})})}switchView(e){this.clearCountdown(),e!=="verify-email"&&(this.verificationCompletionAction=null),this.state.view=e,this.state.error=null,this.state.notice=null,this.state.busy=!1,this.state.busyLabel=void 0,this.terminalActionInProgress=!1,this.render()}async handleSignIn(){const e=this.activeSignInMethod();if(e==="otp"){await this.handleEmailOtpSignIn();return}if(e==="phone"){await this.handlePhoneOtpSignIn();return}if(!x(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}await this.runAction(this.labels.signIn.signingIn??this.labels.common.loading,async()=>{const i=await this.auth.signIn.email({email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(N,this.state.email.trim())});if(i.error)throw i.error;await this.completeAuth("sign-in")},"sign-in")}async handleEmailOtpSignIn(){if(!this.canUseEmailOtpSignIn()){this.handleError(new f("Email OTP sign-in is not enabled for this project."));return}if(!x(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.signInOtpSent){await this.sendSignInOtp();return}if(!re(this.state.code)){this.failValidation(this.labels.errors.invalidCode);return}await this.runAction(this.labels.signIn.signingIn??this.labels.common.loading,async()=>{const e=await this.emailOtpSignInEndpoints().signIn.emailOtp({email:this.state.email.trim(),otp:this.state.code.trim()});if(e.error)throw e.error;await this.completeAuth("sign-in",await this.resolveAuthCompletionData(e.data))},"sign-in")}async sendSignInOtp(e=!1){await this.runAction(this.labels.signIn.sendingCode??this.labels.common.loading,async()=>{var s;const i=await this.emailOtpSignInEndpoints().emailOtp.sendVerificationOtp({email:this.state.email.trim(),type:"sign-in"});if(i.error)throw i.error;if(this.state.signInOtpSent=!0,this.state.code="",(s=this.config)!=null&&s.isLocalDev){this.state.busyLabel="Dev mode: fetching sign-in code...",this.render();const n=await _t(this.state.email.trim());n?(this.state.code=n,this.state.notice=`Dev mode: sign-in code auto-filled (${n})`):this.state.notice="Dev mode: could not retrieve sign-in code — check server logs"}else this.state.notice=this.labels.signIn.codePlaceholder??this.labels.signIn.codeLabel??"Code";this.startCountdown()},e?"resend-code":"send-code")}async resendSignInCode(){if(!this.isCountdownActive()){if(this.activeSignInMethod()==="phone"){await this.sendPhoneOtp(!0);return}await this.sendSignInOtp(!0)}}async handlePhoneOtpSignIn(){if(!this.availableSignInMethods().includes("phone")){this.handleError(new f("SMS sign-in is not enabled for this project."));return}if(!Bt(this.state.phone)){this.failValidation(this.labels.errors.invalidPhone??"Enter a valid mainland China mobile number.");return}if(!this.state.signInOtpSent){await this.sendPhoneOtp();return}if(!re(this.state.code)){this.failValidation(this.labels.errors.invalidCode);return}await this.runAction(this.labels.signIn.signingIn??this.labels.common.loading,async()=>{const e=await this.phoneOtpSignInEndpoints().phoneNumber.verify({phoneNumber:this.fullPhoneNumber(),code:this.state.code.trim()});if(e.error)throw this.toPhoneAuthError(e.error);await this.completeAuth("sign-in",await this.resolveAuthCompletionData(e.data))},"sign-in")}async sendPhoneOtp(e=!1){await this.runAction(this.labels.signIn.sendingCode??this.labels.common.loading,async()=>{var n;const i=this.fullPhoneNumber(),s=await this.phoneOtpSignInEndpoints().phoneNumber.sendOtp({phoneNumber:i});if(s.error)throw this.toPhoneAuthError(s.error);if(this.state.signInOtpSent=!0,this.state.code="",(n=this.config)!=null&&n.isLocalDev){this.state.busyLabel="Dev mode: fetching sign-in code...",this.render();const r=await Lt(i);r?(this.state.code=r,this.state.notice=`Dev mode: sign-in code auto-filled (${r})`):this.state.notice="Dev mode: could not retrieve sign-in code — check server logs"}else this.state.notice=this.labels.signIn.phoneCodePlaceholder??"Code sent by SMS. Use the most recent one.";this.startCountdown()},e?"resend-code":"send-code")}fullPhoneNumber(){return`${$e}${We(this.state.phone)}`}toPhoneAuthError(e){const i=H(e),s=i.code==="SMS_RATE_LIMITED"||i.status===429?this.labels.errors.smsRateLimited:i.code==="SMS_SEND_FAILED"?this.labels.errors.smsSendFailed:i.code==="INVALID_PHONE_NUMBER"?this.labels.errors.invalidPhone:void 0;return s?new E(s,{code:i.code,status:i.status,cause:e}):i}async handleSignUp(){var e,i;if(!this.state.name.trim()){this.failValidation(this.labels.errors.requiredField);return}if(!x(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}if(this.state.password.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((i=this.config)==null?void 0:i.minPasswordLength)??8)));return}if(this.state.password!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Creating account…",async()=>{var n;const s=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL($,this.state.email.trim())});if(s.error)throw s.error;if((n=this.config)!=null&&n.requireEmailVerification){if(this.config.isLocalDev&&await this.tryDevAutoVerify("sign-up",s.data))return;this.verificationCompletionAction="sign-up",this.state.view="verify-email",this.state.notice=this.config.isLocalDev?"Dev mode: auto-verify didn’t complete. Click resend to retry.":"Check your inbox to verify your email address.",this.startCountdown();return}await this.completeAuth("sign-up",await this.resolveAuthCompletionData(s.data))})}async handleOAuthSignIn(e){const i=(this.labels.oauth.redirecting??this.labels.common.redirecting).replace("{provider}",Ue[e]);await this.runAction(i,async()=>{const s=await this.auth.signIn.social({provider:e,callbackURL:this.getManagedReturnURL("oauth"),errorCallbackURL:this.getManagedReturnURL("oauth")});if(s.error)throw s.error;const n=this.extractRedirectURL(s.data);if(!n)throw new f(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=i,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(n)},`oauth:${e}`)}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new f("Password reset via email OTP is not enabled for this project."));return}if(!x(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}await this.runAction("Sending reset code…",async()=>{var i;const e=await this.passwordResetEndpoints().forgetPassword.emailOtp({email:this.state.email.trim()});if(e.error)throw e.error;if(this.state.view="reset-password",(i=this.config)!=null&&i.isLocalDev){this.state.busyLabel="Dev mode: fetching reset code…",this.render();const s=await It(this.state.email.trim());s?(this.state.code=s,this.state.notice=`Dev mode: reset code auto-filled (${s})`):this.state.notice="Dev mode: could not retrieve reset code — check server logs"}else this.state.notice=`We sent a reset code to ${this.state.email.trim()}.`;this.startCountdown()})}async resendResetCode(){this.isCountdownActive()||await this.handleForgotPassword()}async handleResetPassword(){var e,i;if(!this.canUsePasswordResetEmailOtp()){this.handleError(new f("Password reset via email OTP is not enabled for this project."));return}if(!re(this.state.code)){this.failValidation(this.labels.errors.invalidCode);return}if(!this.state.newPassword){this.failValidation(this.labels.errors.requiredField);return}if(this.state.newPassword.length<(((e=this.config)==null?void 0:e.minPasswordLength)??8)){this.failValidation(this.labels.errors.passwordTooShort.replace("{min}",String(((i=this.config)==null?void 0:i.minPasswordLength)??8)));return}if(this.state.newPassword!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const s=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(s.error)throw s.error;await this.completePasswordReset()})}async resendVerificationEmail(){var e;if((e=this.config)!=null&&e.isLocalDev){if(this.isCountdownActive())return;await this.runAction("Dev mode: retrying auto-verify…",async()=>{const i=this.verificationCompletionAction??"sign-in";if(!await this.tryDevAutoVerify(i))throw new Error("Dev auto-verify did not complete. Check the edgespark dev logs and try again.")});return}await this.sendVerificationEmail(!1)}async tryDevAutoVerify(e,i){const s=this.state.email.trim();try{return this.state.busyLabel="Dev mode: auto-verifying email…",this.render(),await Et(s)?(this.state.notice="Dev mode: email verification auto-completed",await this.completeAuth(e,await this.resolveAuthCompletionData(i)),!0):(console.warn("[edgespark] Dev auto-verify returned false — falling through"),!1)}catch(n){return console.warn("[edgespark] Dev auto-verify failed:",n),!1}}async sendVerificationEmail(e){!e&&this.isCountdownActive()||await this.runAction("Sending verification email…",async()=>{const i=await this.auth.sendVerificationEmail({email:this.state.email.trim(),callbackURL:this.getManagedReturnURL(this.verificationCompletionAction==="sign-up"?$:N,this.state.email.trim())});if(i.error)throw i.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,i){const s=await this.retryAuthCompletionDataIfNeeded(i??await this.resolveAuthCompletionData());if(this.destroyed)return;if(!s.user||!s.session){if(this.destroyed)return;if(s.lookupError&&U(this.options)){this.navigateToRedirect();return}if(e==="sign-in")throw s.lookupError??new ve("Managed sign-in completed without an authenticated session.");this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render();return}const n={action:e,user:s.user,session:s.session};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(U(this.options)){this.invokeRedirectModeSuccessHook(n),this.navigateToRedirect();return}if(oe(this.options)){this.options.onSuccess(n),this.terminalActionInProgress=!0;return}}}async retryAuthCompletionDataIfNeeded(e){if(e.session)return e;let i=e.lookupError;for(let s=0;s<ne;s++){await new Promise(n=>setTimeout(n,Re));try{const n=await V(this.auth);if(n.user&&n.session)return{user:n.user,session:n.session}}catch(n){i=n}}return{...e,lookupError:i??e.lookupError}}async syncPublicSessionBestEffort(){var e,i;try{await((i=(e=this.runtimeOptions)==null?void 0:e.syncPublicSession)==null?void 0:i.call(e))}catch{}}async resolveAuthCompletionData(e){try{const i=await V(this.auth),s=this.extractUser(e);return{user:i.user??s,session:i.session}}catch(i){return{user:this.extractUser(e),session:null,lookupError:i}}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(oe(this.options)){this.clearCountdown(),this.options.onSuccess(e),this.terminalActionInProgress=!0;return}this.invokeRedirectModeSuccessHook(e),this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.newPassword="",this.state.code="",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice="Password updated. Sign in with your new password.",this.render()}}handleExistingSessionOnMount(){if(U(this.options)){this.navigateToRedirect();return}if(oe(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new f("authUI.mount(container, { onSuccess }) cannot run while a session already exists. Check es.auth.getSession() before mounting controlled auth UI.")}async runAction(e,i,s){this.state.busyAction=s,this.state.busy=!0,this.state.busyLabel=e,this.state.error=null,this.state.notice=null,this.render();try{await i()}catch(n){if(this.maybeHandleVerificationRequired(n))return;this.handleError(n);return}!this.destroyed&&!this.terminalActionInProgress&&(this.state.busy=!1,this.state.busyLabel=void 0,this.render())}maybeHandleVerificationRequired(e){return H(e).code!=="EMAIL_NOT_VERIFIED"?!1:(this.verificationCompletionAction="sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=null,this.state.notice=`Verify your email to finish signing in as ${this.state.email.trim()}.`,this.render(),this.sendVerificationEmail(!0),!0)}handleVerificationEmailSent(e,i){this.state.notice=i?`We sent another verification email to ${e}.`:`We sent a verification email to ${e}.`,this.startCountdown()}invokeRedirectModeSuccessHook(e){var i,s;if(!(!U(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(n){const r=H(n,"Post-auth callback failed.");try{(s=(i=this.options).onError)==null||s.call(i,r)}catch{}}}handleError(e,i){var n,r;const s=H(e,i);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=s.message,this.render(),(r=(n=this.options).onError)==null||r.call(n,s)}failValidation(e){this.state.error=e,this.state.notice=null,this.render()}getManagedReturnURL(e,i){if(!e)return window.location.href;const s=new URL(window.location.href);return s.searchParams.set(ie,e),i?s.searchParams.set(z,i):s.searchParams.delete(z),s.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),i=e.searchParams.get(ie),s=i===se||i===N||i===$?i:null,n=e.searchParams.get(z),r=s?e.searchParams.get("error"):null,l=s?e.searchParams.get("error_description"):null;return(s||n)&&(e.searchParams.delete(ie),e.searchParams.delete(z),s&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:s,email:n,error:r,errorDescription:l}}startCountdown(e=60){this.countdownUntil=Date.now()+e*1e3,this.countdownTimer&&window.clearInterval(this.countdownTimer),this.countdownTimer=window.setInterval(()=>{if(!this.isCountdownActive()){this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null),this.updateCountdownControls();return}this.updateCountdownControls()},1e3)}updateCountdownControls(){const e=[{action:"resend-sign-in-code",base:this.labels.signIn.resendCodeButton??"Resend code",template:this.labels.signIn.resendCountdown??"Resend in {seconds}s"},{action:"resend-verification",base:this.labels.verifyEmail.resendButton,template:this.labels.verifyEmail.resendCountdown},{action:"resend-reset-code",base:this.labels.resetPassword.resendCodeButton,template:this.labels.resetPassword.resendCountdown}];for(const i of e){const s=this.root.querySelector(`[data-action="${i.action}"]`);s&&(i.action==="resend-sign-in-code"&&this.state.busy&&this.state.busyAction==="resend-code"||(s.textContent=this.countdownText(i.base,i.template),s.disabled=this.state.busy||this.isCountdownActive()))}}clearCountdown(){this.countdownUntil=null,this.countdownTimer&&(window.clearInterval(this.countdownTimer),this.countdownTimer=null)}captureFocusSnapshot(){const e=document.activeElement;return!(e instanceof HTMLInputElement)||!this.root.contains(e)||!e.name?null:{name:e.name,type:e.type,selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}scheduleFocusRestore(){this.pendingFocusSnapshot&&(this.clearFocusRestoreTimer(),this.focusRestoreTimer=window.setTimeout(()=>{if(this.focusRestoreTimer=null,this.destroyed||!this.pendingFocusSnapshot)return;const e=this.pendingFocusSnapshot,i=`input[name="${this.escape(e.name)}"][type="${this.escape(e.type)}"]`,s=this.root.querySelector(i);if(!(!s||s.disabled)){if(s.focus(),e.selectionStart!==null&&e.selectionEnd!==null)try{s.setSelectionRange(e.selectionStart,e.selectionEnd)}catch{const n=s.value.length;s.setSelectionRange(n,n)}this.pendingFocusSnapshot=null}},0))}clearFocusRestoreTimer(){this.focusRestoreTimer!==null&&(window.clearTimeout(this.focusRestoreTimer),this.focusRestoreTimer=null)}passwordResetEndpoints(){return this.auth}emailOtpSignInEndpoints(){return this.auth}phoneOtpSignInEndpoints(){return this.auth}availableSignInMethods(){var s,n,r;const e=[];(s=this.config)!=null&&s.emailPasswordEnabled&&e.push("password"),(n=this.config)!=null&&n.emailOtpSignInEnabled&&e.push("otp"),(r=this.config)!=null&&r.phoneOtpSignInEnabled&&e.push("phone");const i=this.options.signInMethods;return i?e.filter(l=>i.includes(l)):e}activeSignInMethod(){const e=this.availableSignInMethods();return e.includes(this.state.signInMethod)?this.state.signInMethod:e[0]??"password"}resolveInitialSignInMethod(){return this.availableSignInMethods()[0]??"password"}setSignInMethod(e){this.state.signInMethod!==e&&(this.state.signInMethod=e,this.state.signInOtpSent=!1,this.state.code="",this.state.error=null,this.state.notice=null,this.render())}canUseEmailOtpSignIn(){var e;return!!((e=this.config)!=null&&e.emailOtpSignInEnabled)}extractRedirectURL(e){if(!e||typeof e!="object")return null;const i=e;return i.redirect&&typeof i.url=="string"&&i.url.length>0?i.url:null}extractUser(e){if(!e||typeof e!="object")return null;const i=e;return i.user&&typeof i.user=="object"?i.user:null}canUsePasswordResetEmailOtp(){var e;return!!((e=this.config)!=null&&e.passwordResetEmailOtpEnabled)}handleSessionlessManagedReturn(e){return e.email&&(this.state.email=e.email),e.marker===$&&!e.error?(this.verificationCompletionAction=null,this.clearCountdown(),this.state.view="sign-in",this.state.password="",this.state.confirmPassword="",this.state.error=null,this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice="Account created. Sign in to continue.",this.render(),!0):e.marker===N||e.marker===$?(this.verificationCompletionAction=e.marker===$?"sign-up":"sign-in",this.state.view="verify-email",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,e.error||e.errorDescription?this.handleError(new E(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===se&&(e.error||e.errorDescription)?(this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,this.handleError(new E(e.errorDescription??"OAuth sign-in failed.",{code:e.error??"OAUTH_ERROR"})),!0):!1}isCountdownActive(){return this.getCountdownSecondsRemaining()>0}getCountdownSecondsRemaining(){return this.countdownUntil?Math.max(0,Math.ceil((this.countdownUntil-Date.now())/1e3)):0}countdownText(e,i){const s=this.getCountdownSecondsRemaining();return s<=0?e:i.replace("{seconds}",String(s))}escape(e){return e.replace(/[&<>"']/g,i=>Mt[i])}}function Ft(t){return"data"in t&&t.data?t.data:t}const Ht=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],ke=2,zt=500;async function xt(){const t=`${window.location.origin}${De}/config`;let e;for(let i=0;i<=ke;i++)try{const s=await fetch(t,{method:"GET",credentials:"include"});if(!s.ok)throw new f(`Failed to load auth config: HTTP ${s.status}`);const n=await s.json(),r=Ft(n);return Gt(r,Pt())}catch(s){e=s,i<ke&&await new Promise(n=>setTimeout(n,zt))}throw e}let G=null;async function Oe(){return G||(G=xt().catch(t=>{throw G=null,t})),G}function Gt(t,e=!1){var r,l,h,p,I,w,b,P,c,L;const i=Ht.filter(({key:A})=>{const T=t[A];return typeof T=="object"&&T!==null&&"enabled"in T&&!!T.enabled}).map(({id:A})=>A),s=t.providerGoogle,n=s!=null&&s.enabled&&typeof((r=s.config)==null?void 0:r.clientId)=="string"?s.config.clientId:null;return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((l=t.providerEmailPassword)!=null&&l.enabled),emailOtpSignInEnabled:!!((h=t.providerEmailOtp)!=null&&h.enabled),phoneOtpSignInEnabled:!!((p=t.providerPhoneOtp)!=null&&p.enabled),minPasswordLength:((w=(I=t.providerEmailPassword)==null?void 0:I.config)==null?void 0:w.minPasswordLength)??8,requireEmailVerification:!!((P=(b=t.providerEmailPassword)==null?void 0:b.config)!=null&&P.requireEmailVerification),passwordResetEmailOtpEnabled:!!((L=(c=t.providerEmailPassword)==null?void 0:c.config)!=null&&L.requirePasswordResetEmailVerification),oauthProviders:i,googleClientId:n,isLocalDev:e}}const jt="https://accounts.google.com/gsi/client",Me="data-edgespark-gsi";let j=null;function ae(){var t,e;return(e=(t=window.google)==null?void 0:t.accounts)==null?void 0:e.id}function qt(){if(typeof window>"u")return Promise.reject(new Error("Google Identity Services is unavailable outside the browser."));const t=ae();return t?Promise.resolve(t):(j||(j=new Promise((e,i)=>{const s=document.querySelector(`script[${Me}]`);if(s){const r=ae();if(r){e(r);return}s.remove()}const n=document.createElement("script");n.src=jt,n.async=!0,n.defer=!0,n.setAttribute(Me,""),n.addEventListener("load",()=>{const r=ae();r?e(r):(n.remove(),i(new Error("Google Identity Services loaded but did not expose google.accounts.id.")))},{once:!0}),n.addEventListener("error",()=>{n.remove(),i(new Error("Failed to load Google Identity Services."))},{once:!0}),document.head.appendChild(n)}).catch(e=>{throw j=null,e})),j)}function Kt(){return{cancel:()=>{}}}function Wt(t){let e=null;return function(s){if(typeof window>"u")return console.error("[edgespark] promptGoogleOneTap() requires a browser environment."),Kt();if(e)return console.warn("[edgespark] promptGoogleOneTap() is already in flight; returning the existing handle. Call cancel() on the original before re-prompting."),e;let n=!1,r=null;const l=()=>{n||(n=!0,e===h&&(e=null))},h={cancel(){if(!n&&(l(),r))try{r.cancel()}catch{}}},p=()=>{var b;if(!n){l();try{(b=s==null?void 0:s.onUnavailable)==null||b.call(s)}catch(P){console.error("[edgespark] onUnavailable threw:",P)}}},I=(b,P)=>{var L;if(n)return;l();const c=ye(b,P);try{(L=s==null?void 0:s.onError)==null||L.call(s,c)}catch(A){console.error("[edgespark] onError threw:",A)}},w=(b,P)=>{var c;if(!n){l();try{(c=s==null?void 0:s.onSuccess)==null||c.call(s,{action:"sign-in",user:b,session:P})}catch(L){console.error("[edgespark] onSuccess threw:",L)}}};return e=h,(async()=>{let b;try{b=await t.loadConfig()}catch(c){I(c,"Failed to load auth config for Google One Tap.");return}if(n)return;if(b.isLocalDev){console.error("[edgespark] promptGoogleOneTap() is disabled in local dev mode — Google Identity Services cannot run against mock OAuth."),l();return}const P=b.googleClientId;if(!P){console.error("[edgespark] promptGoogleOneTap() called but Google is not configured. Set `providerGoogle` in `auth-config.yaml` with resolvable credentials."),l();return}try{r=await qt()}catch(c){console.warn("[edgespark] Google Identity Services failed to load; treating as unavailable.",c),p();return}if(!n){r.initialize({client_id:P,callback:c=>{n||typeof(c==null?void 0:c.credential)!="string"||c.credential.length===0||Yt(c.credential,t,{emitSuccess:w,emitError:I,isDone:()=>n})},cancel_on_tap_outside:!1,use_fedcm_for_prompt:!0,context:"signin"});try{r.prompt(c=>{var L,A,T,a;if(!n){if((L=c.isDismissedMoment)!=null&&L.call(c)){const m=(A=c.getDismissedReason)==null?void 0:A.call(c);if(m==="credential_returned"||m==="cancel_called")return;p();return}((T=c.isNotDisplayed)!=null&&T.call(c)||(a=c.isSkippedMoment)!=null&&a.call(c))&&p()}})}catch(c){I(c,"Failed to prompt Google One Tap.")}}})(),h}}async function Yt(t,e,i){var I;const{emitSuccess:s,emitError:n,isDone:r}=i,l=e.authClient;if(!((I=l.oneTap)!=null&&I.callback)){n(new E("Google One Tap endpoint not registered. Update the EdgeSpark sidecar.",{code:"ONE_TAP_UNAVAILABLE"}),"Google One Tap endpoint not registered.");return}try{const w=await l.oneTap.callback({idToken:t});if(r())return;if(w.error){n(new E(w.error.message??"Google One Tap sign-in failed.",{code:w.error.code??"ONE_TAP_FAILED",status:w.error.status,cause:w.error}),"Google One Tap sign-in failed.");return}}catch(w){if(r())return;n(w,"Google One Tap sign-in failed.");return}let h=null,p=null;try{const w=await V(e.authClient);if(r())return;h=w.user,p=w.session}catch(w){if(r())return;n(w,"Sign-in succeeded but session lookup failed.");return}if(!h||!p){n(new E("Google One Tap completed without an authenticated session.",{code:"ONE_TAP_NO_SESSION"}),"Google One Tap completed without an authenticated session.");return}s(h,p)}const q=new WeakMap;function Jt(t){if(!t)throw new f("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");const e="redirectTo"in t,i="onSuccess"in t&&typeof t.onSuccess=="function";if(!e&&!i)throw new f("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");if("redirectTo"in t){const s=t.redirectTo;if(!(typeof s=="string"||s instanceof URL))throw new f("authUI.mount(container, options) expected redirectTo to be a string or URL.")}if("onSuccess"in t&&t.onSuccess!==void 0&&typeof t.onSuccess!="function")throw new f("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new f("authUI.mount(container, options) expected onError to be a function.");if("appearance"in t&&t.appearance!==void 0){const s=t.appearance;if(!s||typeof s!="object"||Array.isArray(s))throw new f("authUI.mount(container, options) expected appearance to be an object.");if("theme"in s&&s.theme!==void 0&&!Tt(s.theme))throw new f(`authUI.mount(container, options) expected appearance.theme to be one of: ${Ee.join(", ")}.`);if("className"in s&&s.className!==void 0&&typeof s.className!="string")throw new f("authUI.mount(container, options) expected appearance.className to be a string.");if("variables"in s&&s.variables!==void 0){if(!s.variables||typeof s.variables!="object"||Array.isArray(s.variables))throw new f("authUI.mount(container, options) expected appearance.variables to be an object.");for(const[n,r]of Object.entries(s.variables)){if(!Rt(n))throw new f(`authUI.mount(container, options) received unsupported appearance.variables key "${n}".`);if(r!==void 0&&typeof r!="string")throw new f(`authUI.mount(container, options) expected appearance.variables["${n}"] to be a string.`)}}}}function Xt(t){if(!(t instanceof HTMLElement))throw new f("authUI.mount(container, options) requires a real HTMLElement container.")}function Zt(t,e){const i=Wt({authClient:e.publicAuthClient,loadConfig:Oe});return{mount(s,n){var p;Jt(n),Xt(s),(p=q.get(s))==null||p.destroy();const r=new Vt(s,t,n,Oe,e),l=r.destroy.bind(r),h={destroy(){l(),q.get(s)===h&&q.delete(s)}};return q.set(s,h),h},promptGoogleOneTap:i}}function Qt(){Be();const t=yt(),e=St(),i=Ze(),s=Zt(e,{syncPublicSession:async()=>{await vt(t)},publicAuthClient:t});return{auth:t,api:i,authUI:s}}const ei="phone.invalid";function ti(t){return t?t.trim().toLowerCase().endsWith(`@${ei}`):!1}exports.AUTH_UI_APPEARANCE_VARIABLE=qe;exports.AUTH_UI_APPEARANCE_VARIABLE_NAMES=Ke;exports.AUTH_UI_DEFAULT_THEME=je;exports.AUTH_UI_THEME=Se;exports.AUTH_UI_THEMES=Ee;exports.AUTH_UI_THEME_DARK=Ge;exports.AUTH_UI_THEME_LIGHT=Pe;exports.EdgeSparkAuthError=E;exports.EdgeSparkConfigError=f;exports.EdgeSparkError=Y;exports.EdgeSparkRuntimeError=ve;exports.ar=be;exports.createEdgeSpark=Qt;exports.de=pe;exports.detectLocale=xe;exports.enUS=F;exports.es=W;exports.fr=me;exports.hi=we;exports.isPlaceholderEmail=ti;exports.it=ge;exports.ja=ce;exports.ko=ue;exports.ptBR=he;exports.ru=fe;exports.zhCN=K;
@@ -0,0 +1,29 @@
1
+ export { createEdgeSpark } from './client';
2
+ export type { EdgeSparkClient } from './client';
3
+ export type { AuthSession, AuthUser, BetterAuthClientInstance, EdgeSparkAuth, SessionChangeCallback, SessionResult, } from './auth/types';
4
+ export type { EdgeSparkApi, EdgeSparkRequestInit } from './api/types';
5
+ export { isPlaceholderEmail } from './auth/placeholder-email';
6
+ export type { DeepPartial } from './shared/types';
7
+ export type { RedirectTarget } from './redirect';
8
+ export { AUTH_UI_APPEARANCE_VARIABLE, AUTH_UI_APPEARANCE_VARIABLE_NAMES, AUTH_UI_THEME, AUTH_UI_DEFAULT_THEME, AUTH_UI_THEME_DARK, AUTH_UI_THEME_LIGHT, AUTH_UI_THEMES, } from './auth-ui/appearance';
9
+ export type { AuthUIAppearance, AuthUIAppearanceVariableName, AuthUIAppearanceVariables, AuthUITheme, } from './auth-ui/appearance';
10
+ export type { AuthenticatedAuthSuccessEvent, AuthSuccessEvent, AuthUILabelOverrides, AuthUILabels, AuthUISignInMethod, ControlledAuthUIOptions, EdgeSparkAuthUI, MountAuthUIOptions, MountedAuthUI, OneTapPromptHandle, PromptGoogleOneTapOptions, RedirectAuthUIOptions, } from './auth-ui/types';
11
+ export { EdgeSparkAuthError, EdgeSparkConfigError, EdgeSparkError, EdgeSparkRuntimeError, } from './errors';
12
+ /**
13
+ * Locale helpers for managed auth UI labels.
14
+ *
15
+ * Auto-detection already happens by default inside `authUI.mount(...)`.
16
+ * Import these only when the app wants to force a preset or build a custom
17
+ * label object:
18
+ *
19
+ * ```ts
20
+ * es.authUI.mount(container, {
21
+ * redirectTo: "/dashboard",
22
+ * labels: fr,
23
+ * });
24
+ * ```
25
+ *
26
+ * `detectLocale()` is exported for advanced cases that need the same browser
27
+ * language matching outside the managed UI.
28
+ */
29
+ export { detectLocale, enUS, zhCN, ja, ko, es, ptBR, fr, de, it, ru, ar, hi, } from './locales';